java Android 错误:应用程序意外停止,请重试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3222608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:51:06  来源:igfitidea点击:

Android error: The application has stopped unexpectedly please try again

javaandroid

提问by Vaibhav

I made an app which is just working fine. It displays the number of times app has been started. Here's the code:

我制作了一个运行良好的应用程序。它显示应用程序已启动的次数。这是代码:

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class PreferencesDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Get the app's shared preferences
        SharedPreferences app_preferences = 
            PreferenceManager.getDefaultSharedPreferences(this);

        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);

        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");

        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important
    }
}

If I change the int variable to string it throws an error saying: "app has stopped unexpectedly.. please try again later". Here's the code that throws error:

如果我将 int 变量更改为字符串,它会抛出一个错误:“应用程序意外停止......请稍后再试”。这是引发错误的代码:

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class pref extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String c = prefs.getString("c", "hello");
        TextView t = (TextView)findViewById(R.id.te);
        t.append(c);

        SharedPreferences.Editor edit = prefs.edit();
        edit.putString("c", "There");
        edit.commit();
    }

}

}

can anyone tell me where m I going wrong? Provided: I have correctly mentioned the textview in main.xml file.

谁能告诉我我哪里错了?提供:我在 main.xml 文件中正确提到了 textview。

Here are the LogCat details:

以下是 LogCat 的详细信息:

07-11 15:49:12.908: DEBUG/AndroidRuntime(521): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
07-11 15:49:12.918: DEBUG/AndroidRuntime(521): CheckJNI is ON
07-11 15:49:15.459: DEBUG/AndroidRuntime(521): --- registering native functions ---
07-11 15:49:19.049: DEBUG/AndroidRuntime(521): Shutting down VM
07-11 15:49:19.049: DEBUG/dalvikvm(521): Debugger has detached; object registry had 1 entries
07-11 15:49:19.079: INFO/AndroidRuntime(521): NOTE: attach of thread 'Binder Thread #4' failed
07-11 15:49:20.349: DEBUG/AndroidRuntime(530): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
07-11 15:49:20.359: DEBUG/AndroidRuntime(530): CheckJNI is ON
07-11 15:49:20.739: DEBUG/AndroidRuntime(530): --- registering native functions ---
07-11 15:49:22.492: INFO/ActivityManager(68): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.webkul.pref/.pref }
07-11 15:49:26.996: WARN/ActivityManager(68): Activity pause timeout for HistoryRecord{43f1d590 com.android.launcher/com.android.launcher2.Launcher}
07-11 15:49:27.484: DEBUG/AndroidRuntime(530): Shutting down VM
07-11 15:49:27.619: DEBUG/dalvikvm(530): Debugger has detached; object registry had 1 entries
07-11 15:49:28.649: INFO/ActivityManager(68): Start proc com.webkul.pref for activity com.webkul.pref/.pref: pid=537 uid=10038 gids={}
07-11 15:49:31.339: DEBUG/AndroidRuntime(537): Shutting down VM
07-11 15:49:31.339: WARN/dalvikvm(537): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-11 15:49:31.438: ERROR/AndroidRuntime(537): FATAL EXCEPTION: main
07-11 15:49:31.438: ERROR/AndroidRuntime(537): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.webkul.pref/com.webkul.pref.pref}: java.lang.ClassCastException: java.lang.Integer
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.ActivityThread.access00(ActivityThread.java:125)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.os.Looper.loop(Looper.java:123)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.ActivityThread.main(ActivityThread.java:4627)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at java.lang.reflect.Method.invokeNative(Native Method)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at java.lang.reflect.Method.invoke(Method.java:521)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at dalvik.system.NativeStart.main(Native Method)
07-11 15:49:31.438: ERROR/AndroidRuntime(537): Caused by: java.lang.ClassCastException: java.lang.Integer
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.ContextImpl$SharedPreferencesImpl.getString(ContextImpl.java:2699)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at com.webkul.pref.pref.onCreate(pref.java:17)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-11 15:49:31.438: ERROR/AndroidRuntime(537):     ... 11 more
07-11 15:49:31.646: WARN/ActivityManager(68):   Force finishing activity com.webkul.pref/.pref
07-11 15:49:34.053: DEBUG/dalvikvm(68): GC_FOR_MALLOC freed 13421 objects / 615120 bytes in 1300ms
07-11 15:49:34.129: WARN/ActivityManager(68): Activity pause timeout for HistoryRecord{43fd3ee8 com.webkul.pref/.pref}
07-11 15:49:34.739: WARN/ActivityManager(68): Launch timeout has expired, giving up wake lock!
07-11 15:49:37.479: INFO/Process(537): Sending signal. PID: 537 SIG: 9
07-11 15:49:37.559: WARN/InputManagerService(68): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@43ebfa20
07-11 15:49:37.779: INFO/ActivityManager(68): Process com.webkul.pref (pid 537) has died.
07-11 15:49:37.889: DEBUG/SntpClient(68): request time failed: java.net.SocketException: Address family not supported by protocol
07-11 15:49:46.680: WARN/ActivityManager(68): Activity destroy timeout for HistoryRecord{43fd3ee8 com.webkul.pref/.pref}

采纳答案by Vaibhav

okk got that now.. added a Context and refrenced it through it..

okk 现在明白了.. 添加了一个 Context 并通过它refrenced它..

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
//import android.preference.PreferenceManager;
import android.widget.TextView;

public class pref extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Context mContext = this.getApplicationContext();
        SharedPreferences prefs = mContext.getSharedPreferences("pref", 0);
        String c = prefs.getString("c", "hello");
        TextView t = (TextView)findViewById(R.id.te);
        t.append(c);

        SharedPreferences.Editor edit = prefs.edit();
        edit.putString("c", "There");
        edit.commit();
    }
}

回答by Pentium10

You need to learn how to Debug in Eclipse and how to use the ADBand DDMStools.

您需要学习如何在 Eclipse 中进行调试以及如何使用ADBDDMS工具。

In order to get more details about an exception/force close you need to look for a view in Eclipse called Logcat(you will find in the DDMSperspective) there you will find a detailed traceback when/what and on what line is the issue.

为了获得有关异常/强制关闭的更多详细信息,您需要在 Eclipse 中查找一个名为Logcat的视图(您将在DDMS透视图中找到),您将在那里找到详细的回溯何时/什么以及在哪一行出现问题。

For this you should read a complete article about Debugging in Android using Eclipse

为此,您应该阅读有关使用 Eclipse 在 Android 中进行调试的完整文章

alt text
(source: droidnova.com)

替代文字
(来源:droidnova.com

EDIT

编辑

It says clear what's the problem Caused by: java.lang.ClassCastException: java.lang.Integeron getString

它说清楚是什么问题Caused by: java.lang.ClassCastException: java.lang.IntegergetString

回答by ccheneson

From the doc of getString()from SharedPreferences

getString()来自SharedPreferences的文档

Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a String.

返回首选项值(如果存在)或 defValue。如果此名称不是字符串的首选项,则抛出 ClassCastException。

So my guess is that you have "c" key with a value different than a String. Maybe you have added it by mistake with putInt().

所以我的猜测是你有一个值不同于字符串的“c”键。也许你错误地添加了它putInt()

Try retrieving the "c" key with getInt()to see if you still have the exception.

尝试检索“c”键getInt()以查看是否仍有异常。