【问题标题】:NullpointerException with context [closed]带有上下文的 NullpointerException [关闭]
【发布时间】:2013-01-04 07:15:54
【问题描述】:

我正在尝试在 AsyncTask 中获取共享首选项,但我不明白。

我必须如何在这里使用上下文?

package com.example.wettkampftimerbt;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

public class network extends AsyncTask<URL, String, String> {

    private final String PREFS_NAME = "prefs", W1 = "w1",  W2="w2", W3="w3", W4="w4", 
            W5="w5", W6="w6", W7="w7", SENDBEG="sendbeg", SENDEND="sendend";
    int w1, w2, w3, w4, w5, w6, w7, sendend, sendbeg;

    protected String doInBackground(URL... params) {
        int c2, c3, c4, c5, c6;
        int w0 = 00;
        try {
            w1 = sendbeg;
            c2 = w2;
            c3 = w3;
            c4 = w4;
            c5 = w5;
            c6 = w6;
            w7 = sendend;

            Socket ss = new Socket("192.168.3.100", 4455);
            System.out.println(ss);
            boolean stopData = true;
            System.out.println("lane1 stop send");
            DataOutputStream dos = new DataOutputStream(
                    ss.getOutputStream());
            while (stopData) {
                dos.writeByte(w0);
                dos.writeByte(w1);
                dos.writeByte(c2);
                dos.writeByte(c3);
                dos.writeByte(c4);
                dos.writeByte(c5);
                dos.writeByte(c6);
                dos.writeByte(w7);
                stopData=false;
            }
        } catch (IOException e) {
            System.out.println("IO error" + e);
            e.printStackTrace();
        }

        return "Done";
    }

    public void onPreExecute(){
        Context context = network.this;
        SharedPreferences prefs = context.getSharedPreferences("PREFS_NAME");

        doInBackground();
    }

    public void getPrefs (Context context){         
        w1= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W1, "00"));
        w2= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W2, "00"));
        w3= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W3, "00"));
        w4= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W4, "00"));
        w5= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W5, "00"));
        w6= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W6, "00"));
        w7= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W7, "00"));
        sendbeg= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(SENDBEG, "00"));
        sendend= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(SENDEND, "00"));
    }
}

这是sn-p,我的问题是:我没有错误,除了nullPointerException(由getPrefs(null);?引起)在开始。有人可以帮我吗?

我已经阅读了很多上下文解释,甚至我访问过的 Android 开发者网站,但我不明白上下文是什么,以及它到底做了什么。

编辑:感谢您的快速回答,但它仍然无法正常工作。我现在把整个活动放在这里,你给了我一个样本,但我现在出错了。这取决于我,还是 Eclipse 讨厌我?

EDIT2:我自己调用 doInBackground,因为它不是自己启动的。

EDIT3:现在解决了,它有效^^我直接从我的主要活动中调用getPrefs,然后从getPrefs 调用网络......到目前为止很好,但是:我收到了这个NetworkOnMainThreadException错误。现在该怎么办?

【问题讨论】:

  • getPrefs(null); ??????????? (是的,很多?,但我真的很困惑)
  • 这就是我用 ctrl+1 oo 说的黯然失色
  • 当您尝试访问它时,您认为这不会导致空指针异常?
  • 这就是我的想法...因为我特别提到了它^^

标签: android android-asynctask nullpointerexception sharedpreferences android-context


【解决方案1】:

试试这个:

1) 在 Async 类中定义一个局部变量(在您的情况下是网络类)

Context context;

2) 在您的异步任务中创建构造函数以接受上下文:

public network(Context context) {
    this.context = context;       
}

3) 现在,在onPreExecute() 中调用getPrefs 时,像这样调用:

getPrefs(context);

4) 你可以像这样从你的 MainActivity 调用这个类:

network networkObj= new network(MainActivity.this);
networkObj.execute(url);

【讨论】:

    【解决方案2】:

    你必须将你的类的上下文提供给getPrefs()。 使用getPrefs(yourActivity.this)

    【讨论】:

      【解决方案3】:

      有两种选择:

      1.将 AsyncTask 定义为 Activity 的内部类
      您的 AsyncTask 类不得是静态的才能使其正常工作。

      public class MyActivity extends Activity {
          ...    
      
          private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
              ...
      
              public void onPreExecute() {
                  Context context = MyActivity.this;
                  SharedPreferences prefs = context.getSharedPreferences("PREFS_NAME");
              }
          }
      
      }
      

      2。将您的活动/上下文传递给您的 AsyncTask 构造函数并维护对其的 WeakReference
      您的 AsyncTask 类应该是静态的。不要只维护对您的活动/上下文的硬引用(除非它是应用程序上下文),否则您泄漏内存:

      public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
      
          private WeakReference<Context> mContextRef;
      
          public MyAsyncTask(Context context) {
              mContextRef = new WeakReference<Context>(context);
          }
      
          ...
      
          public void onPreExecute() {
              Context context = mContextRef.get();
              // context may be null if the activity has been destroyed
              if (context != null) {
                  SharedPreferences prefs = context.getSharedPreferences("PREFS_NAME");
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 2012-08-26
        • 2012-03-23
        • 2015-02-27
        相关资源
        最近更新 更多