如何以编程方式清除android中的用户数据?

时间:2015-10-10 11:08:30

标签: java android android-intent android-activity

你好我是android的新手,我跟着一个tutorial解释了如何在android中清除app数据,但是当我试图清除我的数据时,我得到了一个null对象引用错误。

Main.java

public class MainActivity extends ActionBarActivity {
        Button b;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b = (Button)findViewById(R.id.start);  
            addDataInAppDir();

            b.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    ClearDataApplication.getInstance().clearApplicationData(getBaseContext());  
                }


            });
        }

        private void addDataInAppDir() {
            SharedPreferences settings = getSharedPreferences("sample", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("key1", true);
            editor.putString("key2", "Some strings in prefs");
            editor.commit();

            try {

                final String FILECONTENT = "This is string in file samplefile.txt";
                FileOutputStream fout = openFileOutput("samplefile.txt", MODE_PRIVATE);
                OutputStreamWriter osw = new OutputStreamWriter(fout);
                osw.write(FILECONTENT);
                osw.flush();
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

ClearDataApplication.java

  public class ClearDataApplication extends Application 
    {
        private static ClearDataApplication instance;

           @Override
           public void onCreate() {
               super.onCreate();
               instance = this;
           }

           public static ClearDataApplication getInstance() {
               return instance;
           }

           public void clearApplicationData(Context mContext) {

               File cache = mContext.getCacheDir();  
               File appDir = new File(cache.getParent());

               if(appDir.exists()) {
                   String[] children = appDir.list();

                   for(String s : children) {
                       if(!s.equals("lib")) {
                           deleteDir(new File(appDir, s));
                       }
                   }
               }
           }


           public static boolean deleteDir(File dir) {
               if (dir != null && dir.isDirectory()) {
                   String[] children = dir.list();
                   for (int i = 0; i < children.length; i++) {
                       boolean success = deleteDir(new File(dir, children[i]));
                       if (!success) {
                           return false;
                       }
                   }
               }

               return dir.delete();
           }
    }

logcat的

10-10 16:25:55.589: E/AndroidRuntime(6121): FATAL EXCEPTION: main
10-10 16:25:55.589: E/AndroidRuntime(6121): Process: com.example.fetchdata, PID: 6121
10-10 16:25:55.589: E/AndroidRuntime(6121): java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.fetchdata.ClearDataApplication.clearApplicationData(android.content.Context)' on a null object reference
10-10 16:25:55.589: E/AndroidRuntime(6121):     at com.example.fetchdata.MainActivity$1.onClick(MainActivity.java:29)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at android.view.View.performClick(View.java:4756)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at android.view.View$PerformClick.run(View.java:19749)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at android.os.Handler.handleCallback(Handler.java:739)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at android.os.Handler.dispatchMessage(Handler.java:95)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at android.os.Looper.loop(Looper.java:135)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at android.app.ActivityThread.main(ActivityThread.java:5221)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at java.lang.reflect.Method.invoke(Native Method)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at java.lang.reflect.Method.invoke(Method.java:372)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
10-10 16:25:55.589: E/AndroidRuntime(6121):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

3 个答案:

答案 0 :(得分:0)

您是否在manifest.xml中的应用标记下添加了android:name="**/ClearDataApplication"?赞

<Application
    android:name="path of ClearDataApplication"
    ...
</Application>

答案 1 :(得分:0)

NPE说你的ClearDataApplication.getInstance()返回null。

ClearDataApplication扩展了Application,这意味着它可以在运行过程的生命周期中代表Application。您不需要getInstance()方法,因为运行时已经保证只有一个实例。而是从您的活动中调用getApplication()并将其投射到ClearDataApplicatiom。

为了使上述功能正常工作,您还需要对清单文件进行更改,以指定ClearDataApplication应该用作Application的表示形式。

<application android:name=".ClearDataApplication" ...>

参考: http://developer.android.com/guide/topics/manifest/application-element.html#nm

答案 2 :(得分:0)

您是否已将ClearDataApplication设置为Android清单文件中的应用程序应用程序。可能不会调用ClearDataApplication类中的onCreate方法。