notifySetDataChanged()在列表视图的自定义适配器中引发NullPointer异常



我制作了一个自定义数组适配器,它可以更改列表布局中两个textView的字符串。问题是,当我调用notifySetDataChanged()函数时,它会抛出一个空指针异常。即使在参考了各种在线论坛后,我也无法确定这个错误的来源。

这是我的代码:

MessageAdapetr.java

import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
@SuppressLint("ViewHolder") public class MessageAdapter extends ArrayAdapter<TextMessage> {

 private Context context;
 public List<TextMessage> message;
    public MessageAdapter(Context context, List<TextMessage> message)
    {
        super(context, R.layout.message_layout);
        this.context = context;
        this.message = new ArrayList<TextMessage>();
        this.message = message;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.message_layout, parent, false);
        TextView your_first_text_view = (TextView) rowView.findViewById(R.id.textView1);
        TextView your_second_text_view = (TextView) rowView.findViewById(R.id.textView2);
        your_first_text_view.setText(message.get(position).getContent());
        your_second_text_view.setText(message.get(position).getSender());
        return rowView;
    }
}

编辑TextMessage.java

public class EditTextMessage extends ListActivity {
private TextMessage mTextMessage;
private EditText contentEditText;
private String content;
private Button sendButton;
private List<TextMessage> posts;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.activity_edit_text_message);
            posts = new ArrayList<TextMessage>();
        //
            ListView my_list_view = (ListView) findViewById(android.R.id.list);
            MessageAdapter my_adapter = new MessageAdapter(this, posts);
            my_list_view.setAdapter(my_adapter);
        //
    contentEditText = (EditText) findViewById(R.id.TypeMessage);
    sendButton = (Button)findViewById(R.id.SendButton);
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveNote();
        }
    });
    //Refreshes posts
            refreshPostList();
}
private void saveNote() {
    Intent intent = this.getIntent();
    content = contentEditText.getText().toString(); //contents of the edit text are stored in a string variable
    content = content.trim();

        if (!content.isEmpty()) {
            final ParseObject post = new ParseObject("Message");
            post.put("msg", content);
            post.put("sent", intent.getStringExtra("memberId"));
            post.put("sender", ParseUser.getCurrentUser());
            post.put("msg_sender", ParseUser.getCurrentUser().getString("username").toString());
            setProgressBarIndeterminateVisibility(true);
            post.saveInBackground(new SaveCallback() {
                public void done(ParseException e) {
                    setProgressBarIndeterminateVisibility(false);
                    if (e == null) {
                        // Saved successfully.
                        mTextMessage = new TextMessage(post.getObjectId(), content, post.getString("msg_sender"));
                        Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
                        refreshPostList();
                    } else {
                        // The save failed.
                        Toast.makeText(getApplicationContext(), "Failed to send", Toast.LENGTH_SHORT).show();
                        Log.d(getClass().getSimpleName(), "User update error: " + e);
                    }
                }
            });
    } 
    else if (content.isEmpty()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(EditTextMessage.this);
        builder.setMessage(R.string.edit_error_message)
            .setTitle(R.string.edit_error_title)
            .setPositiveButton(android.R.string.ok, null);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
private void refreshPostList() {
    final Intent intent = this.getIntent();
    ParseQuery<ParseObject> query = ParseQuery.getQuery("Message");
    setProgressBarIndeterminateVisibility(true);
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> postList, ParseException e) {
            setProgressBarIndeterminateVisibility(false);
            if (e == null) {
                // If there are results, update the list of posts
                // and notify the adapter
                posts.clear();
                for (ParseObject post : postList) {
                    if(
                            (post.getString("sent").toString().equals(ParseUser.getCurrentUser().getObjectId().toString())
                            &&(post.get("msg_sender").toString().equals(intent.getStringExtra("memberName"))))
                        ||
                            (post.get("msg_sender").toString().equals(ParseUser.getCurrentUser().getUsername().toString())
                            &&
                              (post.getString("sent").toString().equals(intent.getStringExtra("memberId"))))
                      )
                    {
                        TextMessage note = new TextMessage(post.getObjectId(), post.getString("msg"), 
                                post.getString("msg_sender"));
                        posts.add(note);
                    }
                }
               //
                ((MessageAdapter) getListAdapter())
                .notifyDataSetChanged();
               //
            } else {
                Log.d(getClass().getSimpleName(), "Error: Some error" + e.getMessage());
            }
        }
    });
}

}

Logcat:

09-25 00:54:01.900: E/AndroidRuntime(12896): FATAL EXCEPTION: main
09-25 00:54:01.900: E/AndroidRuntime(12896): java.lang.NullPointerException
09-25 00:54:01.900: E/AndroidRuntime(12896):    at ish.message.EditTextMessage$5.done(EditTextMessage.java:280)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at com.parse.FindCallback.internalDone(FindCallback.java:45)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at com.parse.FindCallback.internalDone(FindCallback.java:31)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at com.parse.Parse$5$1.run(Parse.java:891)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at android.os.Handler.handleCallback(Handler.java:615)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at android.os.Looper.loop(Looper.java:137)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at android.app.ActivityThread.main(ActivityThread.java:4960)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at java.lang.reflect.Method.invokeNative(Native Method)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at java.lang.reflect.Method.invoke(Method.java:511)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
09-25 00:54:01.900: E/AndroidRuntime(12896):    at dalvik.system.NativeStart.main(Native Method)

请随时询问更多信息。必需。提前谢谢。

更改这些行:

public MessageAdapter(Context context, List<TextMessage> message)
super(context, R.layout.message_layout);
MessageAdapter my_adapter = new MessageAdapter(this, posts);

public MessageAdapter(Context context, int resource, List<TextMessage> message)
super(context, resource ,message);
MessageAdapter my_adapter = new MessageAdapter(this, R.layout.message_layout , posts);

您没有将任何对象传递给适配器超级构造函数,因此在调用notifyDataSetChanged时,他不会更改任何内容,因为他没有要应用的列表项。

之后,请确保您正在更改传递给适配器的消息对象,您必须更改一个对象引用,而不是创建另一个对象,然后再进行更改。

希望它能帮助你!

相关内容

  • 没有找到相关文章

最新更新