它给我一个错误,因为我给了它一个值,所以不应该这样吗?

时间:2018-09-19 21:21:01

标签: java

我的主要活动:

public class DiaryActivity extends AppCompatActivity {

private ArrayList<String> allURL = new ArrayList<>();
public void setList(ArrayList<String> list) {
        this.allURL = list;
    }

    private void fireYourAsyncTask() {
        new shitson(this).execute();
    }

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary);
        fireYourAsyncTask();
}

我的其他.java:

public class shitson extends AsyncTask<Void, Void, ArrayList<String>> {

ArrayList<String> tmp;
private DiaryActivity activity;

public shitson(DiaryActivity diaryActivity) {
}

protected ArrayList<String> doInBackground(Void... arg0) {
    tmp = new ArrayList<>();
    HttpHandler sh = new HttpHandler();
    String url2 = "https://................";
    String jsonStr = sh.makeServiceCall(url2);

    if (jsonStr != null) {
        try {

            JSONArray urlOfURLs = new JSONArray(jsonStr);
            for (int i = 0; i < urlOfURLs.length(); i++) {
                JSONObject JSONURL = urlOfURLs.getJSONObject(i);
                String url = JSONURL.getString("url");
                tmp.add(url);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    writeout();
    return null;
}

@Override
protected void onPostExecute(ArrayList<String> strings) {
    super.onPostExecute(strings);
    activity.setList(tmp);
}

public void writeout() {
        for (String i : tmp) {
            Log.e("-0-0-0-0-0-0-0-", i);
        }
    }
}

我想要在DiaryActivity中的shitson.java中列出的列表。在shitson.java中,writeout()函数在Logcat中但在activity.setList(tmp)处写入正确的信息。我收到如下错误消息:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.petkovics.mango.DiaryActivity.setList(java.util.ArrayList)' on a null object reference
    at com.example.petkovics.mango.shitson.onPostExecute(shitson.java:57)
at com.example.petkovics.mango.shitson.onPostExecute(shitson.java:20)

自从我填写了“ tmp” ArrayList之后的writeout()函数以来,这是什么废话,它告诉我它必须执行的每个数据。但是仍然在onPostExecute中,它变得很疯狂...

1 个答案:

答案 0 :(得分:1)

你有

private DiaryActivity activity;

定义了名为DiaryActivity的未初始化activity对象。

你有构造函数

public shitson(DiaryActivity diaryActivity) {
}

DiaryActivity对象作为参数,但不执行任何操作,更重要的是,构造函数将activity保留为未初始化状态(因此为null)。

然后您使用 activity,即使它是null对象!

您的构造函数应该可能activity成员设置为传递的对象:

public shitson(DiaryActivity diaryActivity) {
    activity = diaryActivity;
}