How is the SwitchPreference intended to be used? (ClassCastException) - java

I tried to use 2 SwitchPreference in a PreferenceActivity. At the first start of the PreferenceActivity, everything works normal; the activity gets started without problem, the settings.xml is displayed
The problems start if one attends to close the PreferenceActivity or to change the state of the SwitchPreference: everytime the app is closed with a ClassCastException. This also occurs without a set dafaultValue. After that, the app will be closed if one attempts to open the PreferenceActivity.
Until now i do not access/influence the stored values programmatically in any way, for now i just want display the settings screen for testing purposes. The activity will be started if an menu item gets clicked in the calling activity via
final Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
I tried different suggested ways stated here such as defining boolean ressources and using them to set the defaultValue of the SwitchPreferences or using the method
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
in the main activity. None of that approaches worked. How is the SwitchPreference intended to be used, if it apparently can not save its one state wihtout causing an exception? Do one need to define specific xml attributes to make the preference work?
ClassCastException
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:242)
at android.preference.Preference.getPersistedBoolean(Preference.java:1637)
at android.preference.Preference.persistBoolean(Preference.java:1608)
at android.preference.TwoStatePreference.setChecked(TwoStatePreference.java:79)
at android.preference.SwitchPreference$Listener.onCheckedChanged(SwitchPreference.java:54)
at android.widget.CompoundButton.setChecked(CompoundButton.java:126)
at android.widget.Switch.setChecked(Switch.java:688)
at android.widget.CompoundButton.toggle(CompoundButton.java:87)
at android.widget.CompoundButton.performClick(CompoundButton.java:99)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
PreferenceActivity
public class SettingsActivity extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.addPreferencesFromResource(R.xml.settings);
}
}
settings.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
[...]
<PreferenceCategory
android:title="#string/sett_not_header">
<SwitchPreference
android:key="#+id/sett_not_on"
android:title="#string/sett_not_act_header"
android:summary="#string/sett_not_act_summ"
android:defaultValue="true"/>
<SwitchPreference
android:key="#+id/sett_not_mute"
android:title="#string/sett_not_mute_header"
android:summary="#string/sett_not_mute_summ"
android:defaultValue="true"/>
[...]
</PreferenceCategory>
</PreferenceScreen>

I was able to track down the cause of the exception:
In the field android:key i falsely used the expression #+id/in the assumption the key declaration would work the same way the id declaration works. Removing the expression #+id/allowed me to use the SwitchPreference without errors.

Related

Can an activity loose its intent extras?

The app crashes in setParametersFromIntent which is called in onCreate of the activity. The method throws a custom RumtimeException if a specific intent extra is not set.
The crash is only reported rarely, I was not able to reproduce the bug.
I checked the code and there seems to be no possible route the activity could be started without the parameter being set.
Caused by java.lang.RuntimeException: intent extra not set
at com.myapp.myapp.activities.MyActivity.setParametersFromIntent(MyActivity.java)
at com.myapp.myapp.activities.MyActivity.onCreate(MyActivity.java)
at android.app.Activity.performCreate(Activity.java:5442)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(NativeStart.java)
I read that upon recreation of an activity, the intent extras are also restored, so I rule that out as a possible cause.
Does the log give any hints about how the activity has been started?
The android.app.Instrumentation.callActivityOnCreate also seems suspicious, as instrumentation should be disabled in the released app. Could this be someone trying to analyze and mess around with the activity, causing this exception?

Android app crashes with java.lang.NoClassDefFoundError

I have an application that creates an Intent when selecting item menu, but the first time the user clicks this button, the app crashes with the following stack trace.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.systemsat.monitriip, PID: 17818
java.lang.NoClassDefFoundError: br.com.systemsat.monitriip.activity.ConfigurationActivity
at br.com.systemsat.monitriip.activity.MainActivity.onOptionsItemSelected(MainActivity.java:212)
at android.app.Activity.onMenuItemSelected(Activity.java:2912)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:421)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:188)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:103)
at android.support.v7.app.AppCompatDelegateImplV7.onMenuItemSelected(AppCompatDelegateImplV7.java:663)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:810)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:957)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:947)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:618)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:155)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Below is my Activity declaration inside AndroidManifest.xml:
<activity
android:name=".activity.ConfigurationActivity"
android:parentActivityName=".activity.MainActivity">
</activity>
Also, below is the line that is accused to be the cause of the problem by the call stack:
Intent hashCodeIntent = new Intent(getApplicationContext(), ConfigurationActivity.class);
Some answers found in StackOverflow pointed me that clean and rebuild would do the trick but I've tried without any luck. I have also tried adding MultiDex to gradle file as well as to my custom Application class, but that also resulted in a no go.
Could someone else have any insights as to what I might have done wrong? What is really intriguing is that this error only happens on the first time the user clicks the "Configuration" screen button. After the app crashes, the user can reopen it and click the button normally.
Thank you in advance.
UPDATE
I have forgot to mention that Android Monitor also logs the following info right before the crash:
Rejecting re-init on previously-failed class java.lang.Class<br.com.systemsat.monitriip.activity.ConfigurationActivity>
UPDATE 2
Here is my onOptionsItemSelected method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_action_config:
Intent hashCodeIntent = new Intent(this, ConfigurationActivity.class);
hashCodeIntent.putExtra("isConfigurationCall", true);
startActivity(hashCodeIntent);
break;
}
return true;
}
UPDATE 3
I have just generated an apk for testing purposes and the error did not show. Maybe it has something to do with debuging? Or even something to do with gradle version? I currently use the last version of gradle.
Try to change getAplicationContext() for getActivity()
Sometimes getAplicationContext returns null.

Starting Android activity gives NullPointerException

I have an activity, LookingForGPS, that starts another activity, Run. After starting Run, LookingForGPS doesn't finish, but rather continually updates some TextViews in Run:
Run run = new Run();
if(runHasBeenStarted)run.getAndSetValues(someParameters, this);
To my understanding, this returns the LookingForGPS activity. However, after a while (when the parameters are a certain value) I want to start a new activity, PostRun. The following method is called from the Run instance's getAndSetValues:
private void killEverythingAndProceed(Context context){
Intent finishRun = new Intent(context, PostRun.class);
//putting some extras into the intent
startActivity(finishRun);
}
I then get a NullPointerException at the line of startActivity:
11-17 08:34:33.647 2472-2472/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: lv.rv1g.kj0112.forward, PID: 2472
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3424)
at android.app.Activity.startActivityForResult(Activity.java:3385)
at android.app.Activity.startActivity(Activity.java:3627)
at android.app.Activity.startActivity(Activity.java:3595)
at lv.rv1g.kj0112.forward.Run.killEverythingAndProceed(Run.java:143)
at lv.rv1g.kj0112.forward.Run.getAndSetValues(Run.java:88)
at lv.rv1g.kj0112.forward.LookingForGPS.onLocationChanged(LookingForGPS.java:100)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:279)
at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:208)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:224)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
What am I doing horribly wrong? I guess it's my lack of knowledge about object-oriented programming that's causing this. It's not the extras causing it, and the context should be correct as well, as it works for another method from the same instance.
Edit: detailed explanation
The LookingForGPS activity has a LocationManager (not using a service because it has some limitations that are too complicated for me to work around). Each time onLocationChanged is called, the Run activity is instantiated (I check whether it has actually been started first, it gets started by the user independetly of the LocationManager), and the getAndSetValues method inside Run is called, giving a bunch of parameters. getAndSetValues then performs some calculations and updates some TextViews in the Run activity (which all works fine). A calculation is also performed to see whether a certain condition has been met. If it has been, the postRun activity is supposed to be started, which is when I run into the exception above.
Here's the problem:
Run run = new Run();
Looks like Run is an Activity. Never instantiate activities with new - you cannot use activities instantiated such way for anything you'd want to use an activity for. For example, to be used as a Context for startActivity().
Either use an Activity instance that has been set up by the system for you, or use an Intent to launch a new activity instance.

onclick Caused by: java.lang.NullPointerException

I'm new to Android development. I recently encoutered an issue when I hit a button on my application. I'm not sure what caused this because it worked flawlessly before I did some editing with the app, adding another activity, removing the software menu buttons on the splash screen, some other stuff. Not much of it had to do with the first activity which is where this problem exists. I would've posted all of the code but this website refused to let me do so
When I hit my button (readybutton) I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.unviewedchat/com.unviewedchat.SecondActivity}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.unviewedchat.SecondActivity.onCreate(SecondActivity.java:23)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
 
    
      
Button code (readybutton)
button1 = (Button)findViewById(R.id.readybutton);
button1.setOnClickListener(this);
}
Button button1;
private void readyButtonclick()
{
startActivity(new Intent("unviewedchat.SecondActivity"));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.readybutton:
readyButtonclick();
break;
}
}
SecondActivity row 22-23
button2 = (Button)findViewById(R.id.help);
button2.setOnClickListener(this); }
this code is for the software menu buttons to open the help screen, does this actually effect the button code for FirstActivity?
There is no code on SecondActivity that i'm trying to access, i'm trying to go to that activity when someone hits the button.
I attempted to post all of the error report, only to get told it wasn't formatted correctly when it was, either way I added almost all of it.
Just change:
startActivity(new Intent("unviewedchat.SecondActivity"));
with this:
startActivity(new Intent(this, SecondActivity.class));
Caused by: java.lang.NullPointerException
at com.unviewedchat.SecondActivity.onCreate(SecondActivity.java:23)
So in here:
SecondActivity row 22-23
button2 = (Button)findViewById(R.id.help);
button2.setOnClickListener(this); }
... button2 is null. Either your layout you've set with setContentView() does not contain a view with id help, or you haven't called setContentView() at all. In either case findViewById() returns null.
where in the SecondActivity do you declare button2?
you should do it in the onCreate method after setContentView()
and check your layout you are in SecondActivity if the button with that specific id "help" actually exists
Try the following
use the code following code
button2 = (Button)findViewById(R.menu.help);
instead of
button2 = (Button)findViewById(R.id.help);

I don't have force to close the application in android

i am developing an android application using a new device (Samsung galaxy core) the problem is when I try to run the application and I have an error in my code like infinity loop or something like that when the application run in my device a black screen appears and i can't do nothing only restart the device and start over again I don't see the dialog ( force to close application ... ) which I used to have in my old device any help please !
thanks for you answers and sorry if i wasn't so clear actually the problem is not in my code it's in the device (i think) for example in this code i haven't declare a new activity in Androidmanifest.xml
package com.exadle.df;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button);
final Intent intent = new Intent(MainActivity.this, newj.class);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.this.startActivity(intent);
}
});
}
}
so when the app crash a black screen appears and i can't do nothing ! even as you said "Hold the Home Button for couple of seconds, when the list of running applications shows up, flip your app out." the only thing i can do is Hold power Button to restart the phone
here is the logcat if it can help
05-25 15:04:32.281 21017-21017/com.exadle.df D/dalvikvm﹕ Late-enabling CheckJNI
05-25 15:04:32.401 21017-21017/com.exadle.df D/ActivityThread﹕ setTargetHeapUtilization:0.25
05-25 15:04:32.401 21017-21017/com.exadle.df D/ActivityThread﹕ setTargetHeapIdealFree:8388608
05-25 15:04:32.401 21017-21017/com.exadle.df D/ActivityThread﹕ setTargetHeapConcurrentStart:2097152
05-25 15:04:32.871 21017-21017/com.exadle.df D/libEGL﹕ loaded /system/lib/egl/libEGL_adreno200.so
05-25 15:04:32.881 21017-21017/com.exadle.df D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_adreno200.so
05-25 15:04:32.891 21017-21017/com.exadle.df D/libEGL﹕ loaded /system/lib/egl/libGLESv2_adreno200.so
05-25 15:04:32.891 21017-21017/com.exadle.df I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.107_msm8625_JB_REL_2.0.3_CL3357771_release_AU (CL3357771)
Build Date: 02/25/13 Mon
Local Branch:
Remote Branch: quic/jb_rel_2.0.3
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.107 + NOTHING
05-25 15:04:32.941 21017-21017/com.exadle.df D/OpenGLRenderer﹕ Enabling debug mode 0
05-25 15:04:37.531 21017-21017/com.exadle.df D/AndroidRuntime﹕ Shutting down VM
05-25 15:04:37.531 21017-21017/com.exadle.df W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41b78438)
05-25 15:04:37.541 21017-21017/com.exadle.df E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.exadle.df/com.exadle.df.newj}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1556)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1431)
at android.app.Activity.startActivityForResult(Activity.java:3429)
at android.app.Activity.startActivityForResult(Activity.java:3390)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:839)
at android.app.Activity.startActivity(Activity.java:3600)
at android.app.Activity.startActivity(Activity.java:3568)
at com.exadle.df.MainActivity$1.onClick(MainActivity.java:25)
at android.view.View.performClick(View.java:4191)
at android.view.View$PerformClick.run(View.java:17229)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
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:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
i am using Android Studio and i can't use stop execution !
Without the code for your app, I can't tell why it is hanging.
If you think it is stuck in an infinite loop, you can use tools to determine roughly where the loop is. A good pace to start is with the profiling tools in the Android Development Kit, which will tell you the method where the loop is occurring.
If you show us some of the code or logcat, we may be able to help more. But, I can offer my bit of advice.
When I come across something in my apps that is not working right, or it crashes when it comes to that bit of code, I comment out a few blocks of code at a time, and find the point at which the app runs correctly. So If I had an app that crashed when a specific method was called, I would systematically comment out parts of that method until it stopped crashing. If it only stopped when the entire method was commented out, then I would need to go into the code and try to spot the problem. However, if you comment out half of the method and the remaining code runs, then you know that the problem is in something you commented out. Then you can narrow that down to the exact problem.
Just make sure you comment out blocks of code that make sense. Don't just comment out a bracket, and then have your program give you errors. Comment out the code intelligently.
Since your entire app isn't working, make sure that your preliminary activity is set correctly in your Manifest. If it is your splash, make sure that it is called when the app starts. There is a setting/line of code in the manifest somewhere, but I forget where it is. If all of that is correct, then start commenting out the code in that activity systematically. Start with the last method called, then the second to last, and so on. When it starts running, look at the code you have commented out and try to find the problem.
This is all we can do without any code or logcat. If the problem turns out not to be in the code, but in the phone, then this would be better suited on the Android Enthusiasts forum. You could ask for a migration if this is the case. Hope this helps!
UPDATE
I am still not 100% sure what the problem is, but I can suggest some changes in your code that may or may not work.
Make sure your newj activity is in your Manifest.XML. There should be a line of code that says:
<activity android:theme="#style/AppBaseTheme" android:screenOrientation="portrait" android:name="newj"></activity>
If that doesn't help at all, you can try these also.
Instead of having your intent outside the click listener, put in inside. I find that having not in the same OnClickListener or if statement or method can cause a problem to two. So your code would be:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MainActivity.this, newj.class);
startActivity(intent); //and get rid of MainActivity.this.
}
});
If that doesn't work, then this method is more in-depth, but I think it is safer.
First, you want to go into the XML for your button, and add these two lines.
android:Clickable="true"
android:onClick="methodToBeCalled"
These two lines take the place of the OnClickListener, and make the button clickable and tell the program which method to call when the button is clicked. So you need to make a new method, outside of onCreate, that looks like this.
public static void methodToBeCalled(View view){
final Intent intent = new Intent(MainActivity.this, newj.class);
startActivity(intent);
}
So basically what happens is that the code in the XML makes the button clickable, and says to call the method, "methodToBeCalled" when it is clicked. Then it looks for that method in your mainActivity class (because that XML file is linked to this activity) and it runs that activity, starting the Intent intent which starts the Activity newj. Confusing, right? Not really. The XML tells the program to run the method "methodToBeCalled", which starts newj.
Try these methods in order. If method 1 doesn't work, move onto 2. Then 3. If none of these work, update your question with the new logcat, your entire MainActivity code, your entire activity_main XML code, and your entire AndroidManifest.XML code. We can move on from there.
If this does turn out to be a problem with your phone and not the code, flag for migration to Android Enthusiasts Stack Exchange. You will get better help there if this does turn out to be a problem with the phone itself, and not the code.
Hope this helps!

Categories

Resources