[Q] Tabhost and fragments/activities - Android Studio

Hello,
I'm trying to create an app with some tabs that link to different activities, I was able to do that with tabhost and normal buttons with onClick=startActivity, but I had some problems losing the scrollbar position from tabs on every activity change.
Well, now I was reading about fragments, and its really interesting. i created the app with the codes below, I can click in every tab and I can see the content (just watched one tutorial with that), but I cant figure out how could I open one different activity in the FrameLayout when I click in each tab. I see that the code gets the tabs id and then uses it to create one text, what I cant figure out is how to verify if the ID is "X", it would open the "activity2", "....3", "....4", "...n". I tried to put some IFs inside it, but nothing worked.
Is there a way to do that ? This an ideal way of doing that or should I change something to make it easier and better ?
activity_main.xml
Code:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/horizontalScrollView"
android:scrollbars="none"
android:scrollbarSize="0dp">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</HorizontalScrollView>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
MainActivity.java
Code:
package com.example.tbarata.myapplication;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class MainActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("Tab 1111", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("Tab 2222", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("Tab 3333", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab44").setIndicator("Tab 44", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab5").setIndicator("Tab 55", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab6").setIndicator("Tab 66", null),
FragmentTab.class, null);
}
}
activity_fragment_layout.xml
Code:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#eaecee">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
FragmentTab.java
Code:
package com.example.tbarata.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTab extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_fragment_layout, container, false);
TextView tv = (TextView) v.findViewById(R.id.text);
tv.setText(this.getTag() + " Content");
return v;
}
}
Thanks very much!
barata

Plz, could anyone give me some light, or just some link of a tutorial ? Could be even in japanese
I was able to load one activity here comparing the tab id and loading the activity, but when I did that, the tabHost was deleted, so I repeat all the tabHost lines in this second activity, and I can see when I click in its tab its loaded, but the app crashes
Here is the code I've changed:
fragmentTab.java - Just to check the tab id and then load the activity, with only this worked great, but no tabs in the second activity
Code:
if (this.getTag() == "tab2") {
Intent intent = new Intent(getActivity(), fragment_layout2.class);
startActivity(intent);
}
} else {
TextView tv = (TextView) v.findViewById(R.id.text);
tv.setText(this.getTag() + " Content");
}
So in the fragment_layout2.java I repeated the codes to show the tabs, but when I click in this tab2 the app crashes:
Code:
public class fragment_layout2 extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_layout2);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("Tab 1111", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("Tab 2222", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("Tab 3333", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab44").setIndicator("Tab 44", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab5").setIndicator("Tab 55", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab6").setIndicator("Tab 66", null),
FragmentTab.class, null);
}
Thanks.
Barata

Related

Loading local html-page into webview?

I have a large set of html-pages (css-formatted, + some javascript) that I want saved inside the project so the user dont have to go online to browse for them from the app.
1) My first question is how do I open a a local html-page (named, for instance "myWebPage.html") in a WebView?
I know I can make a WebView load a html-string with the following code:
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@+id/webkit"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
WebKitTest.java
Code:
package com.androidspanishcourse.WebKitTest;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebKitTest extends Activity {
// Declare webview
WebView browser;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ?
browser=(WebView)findViewById(R.id.webkit);
// Loads html-string into webview
browser.loadData("<html><body>Hi dude<br><br>Hi again</body></html>", "text/html", "UTF-8");
}
}
But I dont know how to load a specific local html-page.
2) My second question is: where do I put the html-pages? I understand that resources are generally put in the /res/-folder of the project, but do I put them in a specific sub-folder of the res-folder?
http://developer.android.com/reference/android/webkit/WebView.html
1.Webview.loadUrl(String url)
2.The prefix "file:///android_asset/" will cause WebView to load content from the current application's 'assets' folder. For example, a myimage.gif file in the /assets folder can be used in the html image tag as:
<img src="file:///android_asset/myimage.gif">. Same applies to html file.
Thanks a lot, waacow
Also, apparently you need to add "browser.getSettings().setJavaScriptEnabled(true);" for the webview to be able to handle javascript.
Display HTML file from assets folder
Hello,
Just save your HTML file in your assets folder and then load it from assets to webview.
MainActivity.java
package com.deepshikha.htmlfromassets;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressDialog progressDialog;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
webview = (WebView)findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/download.html");
webview.requestFocus();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading");
progressDialog.setCancelable(false);
progressDialog.show();
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thanks!

[Q] .9 png's and layouts.. ?

I'm having trouble replacing certain drawables, i've made a few work, some others just don't get replaced.
Here's a bit for a part that works.
Code:
package mjxl.xposed.cm11;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
public class CM11transparentstuff implements IXposedHookZygoteInit, IXposedHookInitPackageResources {
private static String MODULE_PATH = null;
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
MODULE_PATH = startupParam.modulePath;
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
XModuleResources modRes = XModuleResources.createInstance(MODULE_PATH, resparam.res);
resparam.res.setReplacement("android", "drawable", "overscroll_edge", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
Now i want to replace the notification_bg_normal.9.png and notification_bg_normal_pressed.9.png with my versions.
Technically i should be able to add a line like this:
resparam.res.setReplacement("android", "drawable", "notification_bg_normal", modRes.fwd(R.drawable.not_bg_normal));
And ofcourse add the drawable (notification_bg_normal_BLA.9.png) in my folder (xhdpi in my case)
Then i've tried to do it in a different class like this, which fails aswell. :/
Code:
package mjxl.xposed.cm11;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
public class CM11notifications implements IXposedHookZygoteInit {
public void initZygote(StartupParam startupParam) throws Throwable {
XModuleResources modRes = XModuleResources.createInstance(startupParam.modulePath, null);
XResources.setSystemWideReplacement("android", "drawable", "notification_bg", modRes.fwd(R.drawable.notification_bg)); <<<<--- notification_bg.xml (doesnt work)
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal", modRes.fwd(R.drawable.not_bg_normal)); <<<<---- notification_bg_normal.9.png (also does not work)
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal_pressed", modRes.fwd(R.drawable.not_bg_normal_pressed));
}
}
Any help ? What am i missing ?
Just fyi, i don't have any Java programming experience.
I followed the steps on Github wiki, and i've made SOME stuff work.. Why don't these work ?
/added:
I also made this, it's in 'framework-res' aswell, but this one DOES seem to work.
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
public class ts2 implements IXposedHookZygoteInit, IXposedHookInitPackageResources {
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
resparam.res.setReplacement("android", "drawable", "overscroll_glow", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
resparam.res.setReplacement("android", "drawable", "overscroll_edge", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
Trying to hook the layout where the notification_bg.xml is called as background.
Following the "Modifying Layouts" on the Github Tutorial i came up to this:
Code:
package mjxl.xposed.cm11;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
public class CM11notifications implements IXposedHookInitPackageResources {
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
resparam.res.hookLayout("android", "layout", "notification_template_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_text", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_inbox", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_picture", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
}
}
Am i making any mistakes here ? i don't see it :/ i've tried setBackground instead of BackgroundResource, but that doesn't get accepted.. Neither does setBackgroundDrawable
edit: in initZygote with systemwideLayout
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
public class not implements IXposedHookZygoteInit {
@Override
public void initZygote(IXposedHookZygoteInit.StartupParam startupParam) throws Throwable {
XResources.hookSystemWideLayout("android", "layout", "notification_template_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_picture", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_text", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_inbox", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
}
}
How is it not working? Did you check the Xposed log to see if there are any errors there?
Did you verify the drawable you're trying to replace is also on your device (by e.g. decompiling framework-res.apk)? Some vendors remove/rename drawables that are present in AOSP and/or add their own.
I don't get any errors..
The files are there, I decompiled the files myself lol.
Also the log doesn't show either :/
This SHOULD work right?¿
(Added info, I'm working on CM11 sources)
It looks correct to me. Not sure why it wouldn't work. Maybe some of the drawables you're replacing aren't actually used where you think they're used?
GermainZ said:
It looks correct to me. Not sure why it wouldn't work. Maybe some of the drawables you're replacing aren't actually used where you think they're used?
Click to expand...
Click to collapse
I know that i need to address notification_bg.xml, which contains notification_bg_normal(_pressed).9.png (Blurred Sytem-UI by Serajr: clicky, PNG'sclicky)
I just want to replace the drawables. (either xml or the png's)
Another failed try:
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
public class notBG implements IXposedHookZygoteInit {
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
XposedBridge.log("y0");
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal_pressed", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
I will has continue.
Also i noticed, i'm replacing 'overscroll_edge' and 'overscroll_glow' (both framework-res package) in handleInitPackageResources while theoretically (according to the tutorials) it should be placed in initZygote
I did some more searching, think i might've found something. I'll keep you guys informed.
//edit: mehhh, im about to give up :/
Are your replacement 9 files 'built'?
PainToad said:
Are your replacement 9 files 'built'?
Click to expand...
Click to collapse
What exactly do you mean with 'built' ?
Also, even without the .9 files (by replacing it with a transparent 'newDrawable') it does not work :/

app doesn't lanch; java.lang.NullPointerException

Hello,
i am trying to launch my app on a samsung galaxy s3, but the activity doesn't launch
can someone help me?
error:
06-14 08:36:58.720 24601-24601/plopmenzinc.nsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: plopmenzinc.nsapp, PID: 24601
java.lang.RuntimeException: Unable to start activity ComponentInfo{plopmenzinc.nsapp/plopmenzinc.nsapp.Start}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at plopmenzinc.nsapp.Start.onCreate(Start.java:37)
at android.app.Activity.performCreate(Activity.java:5580)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)*
at android.app.ActivityThread.access$900(ActivityThread.java:170)*
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)*
at android.os.Handler.dispatchMessage(Handler.java:102)*
at android.os.Looper.loop(Looper.java:146)*
at android.app.ActivityThread.main(ActivityThread.java:5635)*
at java.lang.reflect.Method.invokeNative(Native Method)*
at java.lang.reflect.Method.invoke(Method.java:515)*
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)*
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)*
at dalvik.system.NativeStart.main(Native Method)*
start.java:
package plopmenzinc.nsapp;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.NfcAdapter;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageSwitcher;
import android.widget.TextView;
import android.widget.Toast;
public class Start extends AppCompatActivity {
int number = 0;
private ImageSwitcher sw;
public static final String MIME_TEXT_PLAIN = "text/plain";
public static final String TAG = "NfcDemo";
private TextView mTextView;
private NfcAdapter mNfcAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
sw.setImageResource(R.drawable.reclame);
if (mNfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "U kunt deze functie helaas niet gebruiken, omdat uw toestel geen NFC heeft.", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mNfcAdapter.isEnabled()) {
mTextView.setText("Om deze functie te gebruiken moet u NFC aanzetten.");
}
handleIntent(getIntent());
}
@override
protected void onResume() {
super.onResume();
/**
* It's important, that the activity is in the foreground (resumed). Otherwise
* an IllegalStateException is thrown.
*/
setupForegroundDispatch(this, mNfcAdapter);
}
@override
protected void onPause() {
/**
* Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
*/
stopForegroundDispatch(this, mNfcAdapter);
super.onPause();
}
@override
protected void onNewIntent(Intent intent) {
/**
* This method gets called, when a new Intent gets associated with the current activity instance.
* Instead of creating a new activity, onNewIntent will be called. For more information have a look
* at the documentation.
*
* In our case this method gets called, when the user attaches a Tag to the device.
*/
handleIntent(intent);
}
private void handleIntent(Intent intent) {
TextView var = (TextView) findViewById(R.id.score);
number++;
String disp = Integer.toString(number);
var.setText(disp);
final TextView CountDown = (TextView) findViewById(R.id.textView3);
new CountDownTimer(300000, 1000) {
public void onTick(long millisUntilFinished) {
CountDown.setText(millisUntilFinished / 1000 + " sec");
}
public void onFinish() {
CountDown.setText("0 sec");
}
}.start();
}
/**
* @param activity The corresponding {@link Activity} requesting the foreground dispatch.
* @param adapter The {@link NfcAdapter} used for the foreground dispatch.
*/
public void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{};
// Notice that this is the same filter as in our manifest.
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
filters[0].addDataType(MIME_TEXT_PLAIN);
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("Check your mime type.");
}
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
public void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
public void image_next(){
sw.setImageResource(R.drawable.reclame);
}
public void image_prev(){
sw.setImageResource(R.drawable.reclame2);
}
}
activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="(link)"
xmlns:tools="(link)"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
androidrientation="vertical"
androidaddingBottom="@dimen/activity_vertical_margin"
androidaddingLeft="@dimen/activity_horizontal_margin"
androidaddingRight="@dimen/activity_horizontal_margin"
androidaddingTop="@dimen/activity_vertical_margin"
tools:context="plopmenzinc.nsapp.Start"
android:saveEnabled="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Uw aantal punten:"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp"
android:singleLine="true"
android:textColor="#FF2646B0"
android:textSize="22sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/disp"
android:id="@+id/score"
android:layout_alignBottom="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView"
android:textSize="22sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tijd tot U weer kunt scannen:"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="34dp"
android:singleLine="true"
android:textColor="#FF2646B0"
android:textSize="22sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0 sec"
android:id="@+id/textView3"
android:singleLine="true"
android:textSize="22sp"
android:layout_alignTop="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:layout_toEndOf="@+id/textView2" />
<ImageSwitcher
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageSwitcher"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="275dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="prev"
android:id="@+id/button"
android:layout_alignTop="@+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="54dp"
android:layout_marginStart="54dp"
androidnClick="image_prev" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3"
androidnClick="image_next" />
</RelativeLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="(link)"
package="plopmenzinc.nsapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Start">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<activity
android:name="net.vrallev.android.nfc.demo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
</activity>
</manifest>
need to get this finished before thursday, so please help me
Well, thus far I see that you are making references to parts of the Layout View but I am not seeing where you are declaring your TextView / ImageView inside your XML layout, see below:
Code:
sw.setImageResource(R.drawable.reclame);
mTextView.setText("Om deze functie te gebruiken moet u NFC aanzetten.");
You need to have something like:
mTextView = (TextView)findViewbyId(R.id.TextViewId);
sw = (ImageView)findViewById(R.id.ImageViewId);
Fix those, try again and then return.

App crashes, onStart() crashing.

Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onStart(){
super.onStart();
String comments[] = {"Dare 1","Dare 2","Dare 3"};
Random rand = new Random();
int number = rand.nextInt(comments.length);
TextView t = (TextView) findViewById(R.id.msg);
t.setText(comments[number]);
}
public void tf(View view){
Intent myIntent = new Intent(this, TruthFemale.class);
startActivity(myIntent);
}
public void df(View view){
Intent myIntent = new Intent(this, DareFemale.class);
startActivity(myIntent);
}
public void tm(View view){
Intent myIntent = new Intent(this, TruthMale.class);
startActivity(myIntent);
}
public void dm(View view){
Intent myIntent = new Intent(this, DareMale.class);
startActivity(myIntent);
}
Code:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome Press Start"
android:layout_marginTop="51dp"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Truth"
android:id="@+id/btnTruthM"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="89dp"
android:onClick="tm"
android:background="#FF2F48EB" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dare"
android:id="@+id/btnDareM"
android:background="#FF2F48EB"
android:onClick="dm"
android:layout_alignTop="@+id/btnTruthM"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Truth"
android:id="@+id/btnTruthF"
android:layout_marginTop="89dp"
android:background="#e52feb"
android:onClick="tf"
android:layout_below="@+id/btnTruthM"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dare"
android:id="@+id/btnDareF"
android:background="#e52feb"
android:onClick="df"
android:layout_alignTop="@+id/btnTruthF"
android:layout_alignEnd="@+id/btnDareM" />
When i load the app it just crashes...
Found the issue. I didnt name the textview properly and was crashing because of it. Problem resolved...

Widget Show Other App's Icon

I'm trying to create a widget that will show the icon's of some app's installed on the device.
I manage to get a list of packages installed in the device, but i don't know how to get the icon from these.
I have this in my activity:
Code:
final static List<String> pacote_app = new ArrayList<String>();
final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
for (ApplicationInfo app : apps) {
//checks for flags; if flagged, check if updated system app
if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
// installedApps.add(app);
//it's a system app, not interested
} else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
//Discard this one
//in this case, it should be a user-installed app
} else {
String pacote = (String) app.packageName; //NOME DOS PACOTES
pacote_app.add(pacote);
}
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
WidgetViewsFactory
Code:
import static com.example.magcr23.mywidget.LoremActivity.pacote_app;
public class WidgetViewsFactory implements RemoteViewsService.RemoteViewsFactory {
Context context;
private Context ctxt=null;
private int appWidgetId;
public WidgetViewsFactory(Context ctxt, Intent intent) {
this.ctxt=ctxt;
appWidgetId=intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
@Override
public void onCreate() {}
@Override
public void onDestroy() {
// no-op
}
@Override
public int getCount() {
return(pacote_app.size());
}
@Override
public RemoteViews getViewAt(int position) {
RemoteViews row=new RemoteViews(ctxt.getPackageName(),
R.layout.list_item);
//FILL LIST
row.setTextViewText(android.R.id.text1, pacote_app.get(position));
//SEND WORD TO ACTIVITY
Intent i=new Intent();
Bundle extras=new Bundle();
extras.putString(WidgetProvider.EXTRA_WORD, pacote_app.get(position));
i.putExtras(extras);
row.setOnClickFillInIntent(android.R.id.text1, i);
//--------------
return(row);
}
@Override
public RemoteViews getLoadingView() {
return(null);
}
@Override
public int getViewTypeCount() {
return(1);
}
@Override
public long getItemId(int position) {
return(position);
}
@Override
public boolean hasStableIds() {
return(true);
}
@Override
public void onDataSetChanged() {
// no-op
}
}
WidgetProvider
Code:
public class WidgetProvider extends AppWidgetProvider{
public static String EXTRA_WORD=
"com.commonsware.android.appwidget.lorem.WORD";
@Override
public void onUpdate(Context ctxt, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int i=0; i<appWidgetIds.length; i++) {
Intent svcIntent=new Intent(ctxt, WidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews widget=new RemoteViews(ctxt.getPackageName(),
R.layout.novo_widget);
widget.setRemoteAdapter(appWidgetIds[i], R.id.listagem,
svcIntent);
Intent clickIntent=new Intent(ctxt, LoremActivity.class);
PendingIntent clickPI=PendingIntent
.getActivity(ctxt, 0,
clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
widget.setPendingIntentTemplate(R.id.listagem, clickPI);
appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
}
super.onUpdate(ctxt, appWidgetManager, appWidgetIds);
}
}
WidgetService
Code:
public class WidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return(new WidgetViewsFactory(this.getApplicationContext(),
intent));
}
Layout
Code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/widget_margin"
android:orientation="horizontal">
<ListView
android:id="@+id/listagem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
ListView Layout
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight"
android:textColor="#000"
/>
</LinearLayout>
(Whoops, topic a bit old, haven't see the date)
Hi,
You should give a look to PackageItemInfo methods, especially loadIcon (https://developer.android.com/refer...ml#loadIcon(android.content.pm.PackageManager)
In your code:
Code:
final static List<String> pacote_app = new ArrayList<String>();
final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
for (ApplicationInfo app : apps) {
//checks for flags; if flagged, check if updated system app
if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
// installedApps.add(app);
//it's a system app, not interested
} else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
//Discard this one
//in this case, it should be a user-installed app
} else {
String pacote = (String) app.packageName; //NOME DOS PACOTES
pacote_app.add(pacote);
// I guess you want to get your icon here
Drawable packageIcon = app.loadIcon(pm);
}
}
To show it, the easiest might be to add an ImageView and call setImageDrawable
Good luck!

Categories

Resources