0

我的活动中有 Asynctask。问题是当我在 onPostExecute() 中设置文本时,它给了我 NullPointerException。自定义对话框 XML 中的文本视图。我试图将 TextView 变量作为全局变量,但它是一回事。吐司工作正常。这是我的代码:

private class LikeDislike extends AsyncTask<String, Integer, JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            UserFunctions userFunction = new UserFunctions();
            JSONObject json;
            json = userFunction.likeDislike(params[0]);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            super.onPostExecute(json);

            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    //registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS); 
                    if(Integer.parseInt(res) == 1){
                        String like = json.getString("like");
                        String disLike = json.getString("dislike");
                        TextView likeText = (TextView) findViewById(R.id.likenumber);
                        TextView dislikeText = (TextView) findViewById(R.id.dislikenumber);
                        likeText.setText(like);
                        dislikeText.setText(disLike);
                        //TODO
                    }else{      
                        Context context = getApplicationContext();
                        int duration = Toast.LENGTH_LONG;
                        Toast toast = Toast.makeText(context, "error in parsing", duration);
                        toast.show();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
4

4 回答 4

1

您是说 TextViews 在您的 Dialog 中,然后您必须调用 myDialog.findViewById() 来获取视图。否则 findViewById() 尝试在您的活动中找到它。

于 2012-11-09T14:07:38.670 回答
0
TextView likeText = (TextView) findViewById(R.id.likenumber);
 TextView dislikeText = (TextView) findViewById(R.id.dislikenumber);

这应该在Oncreate()通过设置 xml 文件之后在您的方法中定义setcontentview()

于 2012-11-09T13:49:42.020 回答
0

它返回 null 是因为您没有要求正确的组件findViewById(int)

您必须在 onCreateDialog (或类似的东西)内部膨胀您的自定义 XML 时执行此操作。您设置为对话框布局的那个视图,您必须询问该视图findViewById(),然后您的 TextView 将在那里。

于 2012-11-09T14:05:30.473 回答
0

首先,id R.id.likenumber 和 R.id.dislikenumber 应该在你的 xml 中,你在 setContentView 中拥有,如果你使用
Custom XML for Dialog 然后使用

  TextView likeText = (TextView) YOURDIALOG.findViewById(R.id.likenumber);
  TextView dislikeText = (TextView) YOURDIALOG.findViewById(R.id.dislikenumber);
  likeText.setText(like);
  dislikeText.setText(disLike);   
于 2012-11-09T14:09:09.693 回答