Button to set different activity colour - java

I am trying to set the background colour of a different activity from the activity main but I am getting a null pointer.
This is the main:
View activity;
activity = findViewById(R.layout.activity_connect_four);
The button:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
// null pointer on below line
activity.findViewById(android.R.id.content)
.setBackgroundColor(Color.BLACK);
}
});
The logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.con4.MainActivity$4.onClick(MainActivity.java:80)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Where the logCat is pointing to, I don't know what to change. Any help I would be grateful

You're receiving a NPE because that activity and view is not inflated, therefore it returns as null. The way you're setting the background color is flawed by nature. By setting it as you are, even without the NPE, you're storing a setting in the memory of the device. The moment that the device kills your activity, you'll lose that information. As an alternative, you need to store this setting on the device for later retrieval. For what you're attempting to do, I would recommend using SharedPreferences.
In your settings Activity:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
prefs.edit().putInt(BACKGROUND_COLOR, Color.BLACK).commit();
}
});
BACKGROUND_COLOR is a key variable that could be set to "background_color". Then when you start you other activity:
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
int color = prefs.getInt(BACKGROUND_COLOR, Color.WHITE);
And use that color to set the background. Using this method, the background color will be saved to the device until it gets overridden (settings change) or the app is uninstalled.
If you want this to be the background of all of your activity, I suggest having all activities extending a base activity and implementing that code there.
You can check out other storage methods here: http://developer.android.com/guide/topics/data/data-storage.html

Related

WindowLeaked issue

I am having a big problem with WindowLeaked:
E/WindowManager: android.view.WindowLeaked: Activity CrearGrupo has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3702bf39 V.E..... R....... 0,0-960,883} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at es.uva.tel.gco.CrearGrupo$2.onClick(CrearGrupo.java:175)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Here the code:
final Dialog dialog2 = new Dialog(activity, R.style.dialog);
tituloDialogo=res.getString(R.string.crearGrupoDiálogo);
dialog2.setTitle(tituloDialogo +" "+listaAsignaturas.get(pos));
dialog2.setContentView(R.layout.prefijo_grupo);
if (control == 0){
//listNotebooks(pos);
Intent intent=new Intent(getApplicationContext(),MostrarCrearGrupos.class);
intent.putExtra("asignatura",listaAsignaturas.get(pos));
intent.putExtra("prefijo",prefGrupo.getText().toString());
intent.putExtra("nombreLibreta",notebookName);
startActivity(intent);
}
}
});
dialog2.show();
Dialog is a normal window with 2 inputs that let you enter one name and 1 prefix but when I try to show another dialog the app crash.
I already look for a solution and try to solve it with:
#Override
public void onDestroy() {
super.onDestroy();
if (dialog2 != null) {
dialog2.dismiss();
dialog2 = null;
}
}
#Override
protected void onPause(){
super.onPause();
if (dialog2 != null) {
dialog2.dismiss();
dialog2 = null;
}
}
#Override
protected void onStop(){
super.onStop();
if (dialog2 != null) {
dialog2.dismiss();
dialog2 = null;
}
}
But it doesnt work. Any ideas.
Thx for your answers. :)
In you case, you are try to call dialog2.show() after starting the new activity. Remove that and your code will work.
Here is the main reason why Leaked windows error occurs:
We know that every Activity Android has an WindowManager window manager, likewise, is built on top of a Activity dialog box, PopupWindow also has the corresponding WindowManager window manager. Because the dialog box, the PopupWindown from the Activity and should not exist alone, So when a Dialog or a PopupWindow is displayed when we go to finish () carrying the Dialog (or PopupWindow) Activity, Window Leaked exception will be thrown., Because the Dialog (or PopupWindow) WindowManager have who can not affiliated., So the window manager it has leaked.
Android.view.WindowLeaked usually occur in the display of Activity and Dialog.
Create Activity in a Dialog, and if you turn off Dialog first and then close the Activity is normal, if you shut down the Activity first and then close the Dialog will error the error android.view.WindowLeaked.
Analysis the reason is: Dialog is created based on Activity: new ProgressDialog (this); this is Activity. Activtity finish first, then Dialog will have no attachment, so will report android.view.WindowLeaked.

Null Pointer Exception when loading SharedPreference value into fragment string

I'm receiving a null pointer exception when trying to load the string value from sharedpreferences into the string value on my fragment.
I have the sharedpreference working correctly, so I know the string is being saved, but I can't replace the string value in my fragment with the sharedpreference value.
MainActivity
SharedPreferences saveLocation = getSharedPreferences(SAVE, MODE_PRIVATE);
SharedPreferences.Editor editor = saveLocation.edit();
editor.putString("name", marker.getTitle());
editor.commit(); //applies the name to XML
FlickrFragment
public class FlickrFragment extends Fragment{
GridView mGridView;
ArrayList<GalleryItem> mItems;
ThumbnailDownloader mThumbnailThread;
String textToSearch = "Keating Hall";
Basically "Keating Hall" is the text that's being used to generate a gridview of photos. That works correctly, however, I'm trying to replace "Keating Hall" with the sharedpreference value, but have been unsuccessful in all methods that I've tried.
Please let me know if my description needs to be updated to better reflect what I need help with.
Thank you.
Updated: Included LogCat
12-14 15:12:25.161 14902-14902/com.example.ramap E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ramap, PID: 14902
java.lang.NullPointerException
at com.example.ramap.FlickrFragment.<init>(FlickrFragment.java:41)
at com.example.ramap.adapter.TabsPagerAdapter.getItem(TabsPagerAdapter.java:25)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:97)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
at android.support.v4.view.ViewPager.populate(ViewPager.java:987)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:16660)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16660)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
at android.view.View.measure(View.java:16660)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
at android.view.View.measure(View.java:16660)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2058)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1189)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1374)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1076)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5905)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:807)
at android.view.Choreographer.doCallbacks(Choreographer.java:601)
at android.view.Choreographer.doFrame(Choreographer.java:562)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:791)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5633)
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:896)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
at dalvik.system.NativeStart.main(Native Method)

Return To Title Bar When The Lock Button Is Pressed Android

I have a really simple 2 activity app, title screen and main game. I'm trying to make it so that when the user presses the lock button, the app will reappear in the title screen when they unlock the phone. The problem I'm having is that over half the time, I'm getting an exception in the title screen activity when I unlock the phone again. Here's what I've got so far, I know this is probably not the best way, but I was struggling a little. Here's what I'm doing in the main game activity
// On pause, return to main title page
#Override
public void onPause() {
super.onPause();
// Create intent to go back to the title menu
Intent intent = new Intent(this, ActivityTitle.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
And here's what's causing the error in the title bar
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_screen);
// Make sure that the volume buttons change the media volume in the app
setVolumeControlStream(AudioManager.STREAM_MUSIC);
radioGroupSound = (RadioGroup) findViewById(R.id.radioGroupSound);
radioGroupText = (RadioGroup) findViewById(R.id.radioGroupText);
// Make the start text blink
TextView myText = (TextView) findViewById(R.id.textViewStart );
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500); //You can manage the time of the blink with this parameter
anim.setStartOffset(500);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
myText.startAnimation(anim);
}
It's the very last line that's causing the exception - myText.startAnimation(anim).
Here's the error log
07-19 19:49:52.729 26036-26036/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.chrisbjohnson.colorbubbles/com.chrisbjohnson.colorbubbles.ActivityTitle}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:945)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3719)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.chrisbjohnson.colorbubbles.ActivityTitle.onCreate(ActivityTitle.java:44)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
Any thoughts would be appreciated. Either a different way to handle it, or a way to fix what I'm doing.
Thanks.
After all the time spent trying to figure this out, I realized I was just wasting my time. I fixed it by just making the lock screen not work in my app. Kind of a workaround, but the best thing I could find without wasting weeks of my life.

Simple SharedPreferences in Android

I'm having a problem, and I already tried everything I found on this site, it's not helping, so I'm asking this question myself.
my code is:
public class MyActivity extends Activity{
protected PositionSense positionSense;
protected Preferences preferences;
String IP;
String ID;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
positionSense = new PositionSense(this, null);
SharedPreferences settings = getSharedPreferences("preferences", 0);
IP = settings.getString("ip", "http://192.168.1.3:8080/servlet");
ID = settings.getString("id", "USER");
}
Later on, I use these variables in a background running thread that contacts the servlet and sends some info (including position and ID of the user which is saved in preferences)
I'm not posting all of that because I don't want to clog up the thread more than necessary (but if it is needed, I will post it all)
In any case, it doesn't work and it gives me the following error log:
09-14 16:47:20.854: WARN/dalvikvm(552): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
09-14 16:47:20.884: ERROR/AndroidRuntime(552): FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3044)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3039)
... 11 more
Caused by: java.lang.NullPointerException
at com.moodswings.MoodSwingsActivity.clickHappy(MoodSwingsActivity.java:94)
... 14 more
I don't know what to do about it.
Can someone give me the SIMPLEST possible way to save 2 strings in preferences in one activity that are used in some other activity within the same application? It's supposed to be really simple, but I simply cannot make it work, and I'm nearing my deadline.
Thanks!
To save to shared preferences you can try:
String ip = "192.168.1.1";
SharedPreferences prefs = getSharedPreferences("IP", Context.MODE_PRIVATE);
prefs.edit().putString("Sample IP", ip).commit();
To get the information from the shared preferences you can try:
String newIP = prefs.getString("Sample IP");//You can also place a default value if needed; to bypass the null character.
Now to pass them into activities you can try doing an intent call like below
**Activity One
Intent intent = new Intent(getApplicationContext(),SecondActivity.class);
intent.putExtra("IP",newIp);
startActivity(intent);
**Activity Two
Bundle extras = intent.getExtras();
String tmp = extras.getString("IP");
Also you can use this link to reference.

convert String to CharSequence or char[] in Java (Android 1.6 API)

i've got a String that i need to convert to a CharSequence. the data MUST necessarily be a String, as it's returned from:
String ip = pref.getString("ip", "0.0.0.0");
which grabs a user preference String. the data needs to be passed to any of these functions:
final void setText(int resid)
final void setText(int resid, TextView.BufferType type)
final void setText(char[] text, int start, int len)
void setText(CharSequence text, TextView.BufferType type)
final void setText(CharSequence text)
i tried using the bottom function first, but you can't pass it a String (even though String implements CharSequence). it'll compile but it crashes. casting it to a CharSequence in the function call like this doesn't work either:
ipIn.setText((CharSequence)ip);
then i tried using the array version by calling:
ipIn.setText(ip.toCharArray(), 0, ip.toCharArray().length-1);
still crashes. here's the output from 'adb logcat':
E/AndroidRuntime(16642): FATAL EXCEPTION: main
E/AndroidRuntime(16642): java.lang.NullPointerException
E/AndroidRuntime(16642): at com.conceptualsystems.android4api.sms.smsMobile.onCreateDialog(smsMobile.java:81)
E/AndroidRuntime(16642): at android.app.Activity.onCreateDialog(Activity.java:2472)
E/AndroidRuntime(16642): at android.app.Activity.createDialog(Activity.java:881)
E/AndroidRuntime(16642): at android.app.Activity.showDialog(Activity.java:2547)
E/AndroidRuntime(16642): at android.app.Activity.showDialog(Activity.java:2514)
E/AndroidRuntime(16642): at com.conceptualsystems.android4api.sms.smsMobile.onOptionsItemSelected(smsMobile.java:120)
E/AndroidRuntime(16642): at android.app.Activity.onMenuItemSelected(Activity.java:2195)
E/AndroidRuntime(16642): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:730)
E/AndroidRuntime(16642): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
E/AndroidRuntime(16642): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
E/AndroidRuntime(16642): at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532)
E/AndroidRuntime(16642): at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
E/AndroidRuntime(16642): at android.view.View$PerformClick.run(View.java:8816)
E/AndroidRuntime(16642): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime(16642): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(16642): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(16642): at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(16642): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(16642): at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(16642): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(16642): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(16642): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 1099): Force finishing activity
what's interesting is that it crashes when AlertDialog.Builder.setView(View) is called if i set the text first, but crashes on setText if i call it after setView. here's some code to put things into context:
final View dialogLayout = inflater.inflate(R.layout.dialog_wifi_pref, null);
builder = new AlertDialog.Builder(this);
builder.setView(dialogLayout);
builder.setTitle(R.string.opt_ip_config);
String ip = pref.getString("ip", "0.0.0.0");
String port = pref.getString("port", "3005");
EditText ipIn = (EditText)findViewById(R.id.wifi_ip_in);
EditText portIn = (EditText)findViewById(R.id.wifi_port_in);
//ipIn.setText(ip.toCharArray(), 0, ip.toCharArray().length-1);
//portIn.setText((CharSequence)port.toString());
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// change to sqlite /////
/////////////////////////
//nothing here yet
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
dialog = builder.create();
this is all part of the onCreateDialog override and exists inside a case statement. 'dialog', 'inflater', and 'builder' are defined above (properly). and like i said, the error changes depending on whether call setView or setText first. i'm not sure which one i'm actually supposed to do first.
the bottom line: i have to get a String into this EditText box. how does i?
Try running this through a debugger. You are probably passing a null reference into your method, thus the NullPointerException. That would explain why the code compiles but fails at runtime.
Im not sure about your code.but if you have problem in converting. Best way will be to try to make this conversion in a working sample in activity like:
public class test extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
//Here do your converting operation
//
}catch(Exception e){
//show any error during converting
}
android.util.Log.v("conv",
//here you can show results in logcat
);
}
}
if you get expected results , check your dialog with fixed data.
final step mix logic (conversion) + View (dialog) .. and you will be happy .. ;)
The most likely explanation is that the text String you are setting is null. The second alternative does ip.toCharArray() which will definitely throw an NPE if ip is null. The first alternative most likely will too, though the NPE may happen a bit later.
In other circumstances, you might get this kind of problem if you called EditText.setText() in the wrong thread. But that shouldn't be the problem here since you are in the process of creating the widget.
fixed.
the problem actually had nothing at all to do with the class casting. the problem was in the way i was referring to the dialog layout's views. i replaced this line:
EditText ipIn = (EditText)findViewById(R.id.wifi_ip_in);
with this line:
EditText ipIn = (EditText)dialogLayout.findViewById(R.id.wifi_ip_in);
i guess when you inflate a dialog, you have to refer to the inflated instance explicitly, otherwise android won't know which instance of the dialog to change? so the null pointer was actually the dialog EditText ipIn not getting set properly.
thanks to all who contributed.

Categories

Resources