为什么MessageAdapter.getData()'在null对象引用上

时间:2015-09-17 17:29:15

标签: android android-studio

我试图从GCM更改chatroom.java的createReplayMsg消息资源,但为什么apapter.getData()。添加错误?

它告诉我java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()'在null对象引用上。

也许我应该使用AsyncTask来完成它?

PS。我是第一次使用这个论坛,其他资源在这 - > https://github.com/yyting/yoyotrip或者告诉我,谢谢。

logcat的:

09-17 16:42:14.410    8416-8416/com.example.yoyotrip E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.yoyotrip, PID: 8416
    java.lang.RuntimeException: Unable to start receiver com.example.yoyotrip.GCM.GcmBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2586)
            at android.app.ActivityThread.access$1700(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
            at com.example.yoyotrip.GCM.GcmBroadcastReceiver.onReceive(GcmBroadcastReceiver.java:63)

chatroom.java

package com.example.yoyotrip;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.Toast;

import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.example.yoyotrip.chat.MessageInputToolBox;
import com.example.yoyotrip.chat.OnOperationListener;
import com.example.yoyotrip.chat.Option;

public class chatroom extends ActionBarActivity {

    private MessageInputToolBox box;
    public ListView             listView;
    public MessageAdapter       adapter;
    public List<Message> messages ;
    @SuppressLint("UseSparseArrays")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.chatroom);

        initMessageInputToolBox();

        initListView();
    }

    /**
     * init MessageInputToolBox
     */
    @SuppressLint("ShowToast")
    public void initMessageInputToolBox(){
            box = (MessageInputToolBox) findViewById(R.id.messageInputToolBox);
        box.setOnOperationListener(new OnOperationListener() {

            @Override
            public void send(String content) {

                System.out.println("===============" + content);
                int rd=(int)(Math.random()*99)+1;
                Message message = new Message(0, 1, rd%2==1?"Tom":"helen", "avatar", "Jerry", "avatar", content, true, true, new Date());
                adapter.getData().add(message);
                listView.setSelection(listView.getBottom());

                //Just demo
                createReplayMsg(message);
            }


            @Override
            public void selectedFace(String content) {

                System.out.println("===============" + content);
                Message message = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Tomcat", "avatar", "Jerry", "avatar", content, true, true, new Date());
                adapter.getData().add(message);
                listView.setSelection(listView.getBottom());

                //Just demo
                createReplayMsg(message);
            }


            @Override
            public void selectedFuncation(int index) {

                System.out.println("===============" + index);

                switch (index) {
                    case 0:
                        //do some thing
                        break;
                    case 1:
                        //do some thing
                        break;

                    default:
                        break;
                }
                Toast.makeText(chatroom.this, "Do some thing here, index :" +index, Toast.LENGTH_LONG).show();

            }

        });

        ArrayList<String> faceNameList = new ArrayList<String>();
        for(int x = 1; x <= 10; x++){
            faceNameList.add("big"+x);
        }
        for(int x = 1; x <= 10; x++){
            faceNameList.add("big"+x);
        }

        ArrayList<String> faceNameList1 = new ArrayList<String>();
        for(int x = 1; x <= 7; x++){
            faceNameList1.add("cig"+x);
        }


        ArrayList<String> faceNameList2 = new ArrayList<String>();
        for(int x = 1; x <= 24; x++){
            faceNameList2.add("dig"+x);
        }

        Map<Integer, ArrayList<String>> faceData = new HashMap<>();
        faceData.put(R.drawable.em_cate_magic, faceNameList2);
        faceData.put(R.drawable.em_cate_rib, faceNameList1);
        faceData.put(R.drawable.em_cate_duck, faceNameList);
        box.setFaceData(faceData);


        List<Option> functionData = new ArrayList<Option>();
        for(int x = 0; x < 5; x++){
            Option takePhotoOption = new Option(this, "Take", R.drawable.take_photo);
            Option galleryOption = new Option(this, "Gallery", R.drawable.gallery);
            functionData.add(galleryOption);
            functionData.add(takePhotoOption);
        }
        box.setFunctionData(functionData);
    }



    private void initListView(){
        listView = (ListView) findViewById(R.id.messageListview);

        //create Data
        Message message = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hi,大家好我是你們的導遊", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 8));
        Message message1 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hello", false ,true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)* 8));
        Message message2 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "helen", "avatar", "Jerry", "avatar", "我們要在哪集合??", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
        Message message3 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "台北車站嗎!?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
        Message message4 = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "big3", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
        Message message5 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "可以在229公園那邊嗎?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
//        Message message6 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_FAIL, "Tom", "avatar", "Jerry", "avatar", "test send fail", true, false, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
//        Message message7 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SENDING, "Tom", "avatar", "Jerry", "avatar", "test sending", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));

        messages = new ArrayList<Message>();
        messages.add(message);
        messages.add(message1);
        messages.add(message2);
        messages.add(message3);
        messages.add(message4);
        messages.add(message5);
//        messages.add(message6);
//        messages.add(message7);

        adapter = new MessageAdapter(this, messages);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        listView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                box.hide();
                return false;
            }
        });

    }

    //change message resource from GCM   
    public void createReplayMsg(final Message message){

        final Message reMessage = new Message(message.getType(), 1, message.getFromUserName(), "avatar", "Jerry", "avatar",
                message.getType() == 0 ? "Re:" + message.getContent() : message.getContent(),
                false, true, new Date()
        );

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000 * (new Random().nextInt(3) +1));
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.getData().add(reMessage);
                            adapter.notifyDataSetChanged();
                            listView.setSelection(listView.getBottom());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

MessageAdapter.java

package com.example.yoyotrip.chat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.example.yoyotrip.R;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.ImageLoader;

public class MessageAdapter extends BaseAdapter {

    private Context context;
    private List<Message> data = null;

    public MessageAdapter(Context context, List<Message> list) {
        super();
        this.context = context;
        this.data = list;
    }

    @Override
    public int getCount() {
        return data != null ? data.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return this.data.get(position).getIsSend() ? 1 : 0;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }



    @SuppressLint("InflateParams")
    public View getView(int position, View convertView, ViewGroup parent) {

        final Message message = data.get(position);
        boolean isSend = message.getIsSend();

        ViewHolder viewHolder = null;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            if (isSend) {
                convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_right, null);
            } else {
                convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_left, null);
            }
            viewHolder.sendDateTextView = (TextView) convertView.findViewById(R.id.sendDateTextView);
            viewHolder.sendTimeTextView = (TextView) convertView.findViewById(R.id.sendTimeTextView);
            viewHolder.userAvatarImageView = (ImageView) convertView.findViewById(R.id.userAvatarImageView);
            viewHolder.userNameTextView = (TextView) convertView.findViewById(R.id.userNameTextView);
            viewHolder.textTextView = (TextView) convertView.findViewById(R.id.textTextView);
            viewHolder.photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
            viewHolder.faceImageView = (ImageView) convertView.findViewById(R.id.faceImageView);
            viewHolder.failImageView = (ImageView) convertView.findViewById(R.id.failImageView);
            viewHolder.sendingProgressBar = (ProgressBar) convertView.findViewById(R.id.sendingProgressBar);


            viewHolder.isSend = isSend;
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        try {
            String dateString = DateFormat.format("yyyy-MM-dd h:mmaa", message.getTime()).toString();
            String[] t = dateString.split(" ");
            viewHolder.sendDateTextView.setText(t[0]);
            viewHolder.sendTimeTextView.setText(t[1]);

            if(position == 0){
                viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
            }else{
                //TODO is same day ?
                Message pmsg = data.get(position-1);
                if(inSameDay(pmsg.getTime(), message.getTime())){
                    viewHolder.sendDateTextView.setVisibility(View.GONE);
                }else{
                    viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
                }

            }

        } catch (Exception e) {
        }

        viewHolder.userNameTextView.setText(message.getFromUserName());




        switch (message.getType()) {
        case 0://text
            viewHolder.textTextView.setText(message.getContent());
            viewHolder.textTextView.setVisibility(View.VISIBLE);
            viewHolder.photoImageView.setVisibility(View.GONE);
            viewHolder.faceImageView.setVisibility(View.GONE);
            if(message.getIsSend()){
                LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
                sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
                viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);

                LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
                layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
                if( message.getSendSucces() != null && message.getSendSucces() == false){
                    viewHolder.failImageView.setVisibility(View.VISIBLE);
                    viewHolder.failImageView.setLayoutParams(layoutParams);
                }else{
                    viewHolder.failImageView.setVisibility(View.GONE);
                }

                if(message.getState() != null && message.getState() == 0){
                    viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
                    viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
                }else{
                    viewHolder.sendingProgressBar.setVisibility(View.GONE);
                }

            }else{
                viewHolder.failImageView.setVisibility(View.GONE);
                viewHolder.sendingProgressBar.setVisibility(View.GONE);

                LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
                sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.textTextView);
                viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
            }


            break;
        case 1://photo
            viewHolder.textTextView.setVisibility(View.GONE);
            viewHolder.photoImageView.setVisibility(View.VISIBLE);
            viewHolder.faceImageView.setVisibility(View.GONE);

            //TODO set image
            int id = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
            viewHolder.photoImageView.setImageResource(id);


            if(message.getIsSend() ){
                LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
                sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
                viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);

                LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
                layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
                if(message.getSendSucces() != null && message.getSendSucces() == false){
                    viewHolder.failImageView.setVisibility(View.VISIBLE);
                    viewHolder.failImageView.setLayoutParams(layoutParams);
                }else{
                    viewHolder.failImageView.setVisibility(View.GONE);
                }

                if(message.getState() != null && message.getState() == 0){
                    viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
                    viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
                }else{
                    viewHolder.sendingProgressBar.setVisibility(View.GONE);
                }

            }else{
                viewHolder.failImageView.setVisibility(View.GONE);
                LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
                sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.photoImageView);
                viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
            }


            break;

        case 2://face
            viewHolder.photoImageView.setVisibility(View.GONE);
            viewHolder.textTextView.setVisibility(View.GONE);
            viewHolder.faceImageView.setVisibility(View.VISIBLE);
            int resId = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
            viewHolder.faceImageView.setImageResource(resId);

            if(message.getIsSend()){
                LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
                sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
                viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);

                LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
                layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
                if(message.getSendSucces() != null && message.getSendSucces() == false){
                    viewHolder.failImageView.setVisibility(View.VISIBLE);
                    viewHolder.failImageView.setLayoutParams(layoutParams);
                }else{
                    viewHolder.failImageView.setVisibility(View.GONE);
                }

                if(message.getState() != null && message.getState() == 0){
                    viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
                    viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
                }else{
                    viewHolder.sendingProgressBar.setVisibility(View.GONE);
                }

            }else{
                viewHolder.failImageView.setVisibility(View.GONE);

                LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
                sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.faceImageView);
                viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
            }

            break;

        default:
            viewHolder.textTextView.setText(message.getContent());
            viewHolder.photoImageView.setVisibility(View.GONE);
            viewHolder.faceImageView.setVisibility(View.GONE);
            break;
        }

//      viewHolder.textTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

        return convertView;
    }


    public List<Message> getData() {
        return data;
    }

    public void setData(List<Message> data) {
        this.data = data;
    }


    public static boolean inSameDay(Date date1, Date Date2) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);
        int year1 = calendar.get(Calendar.YEAR);
        int day1 = calendar.get(Calendar.DAY_OF_YEAR);

        calendar.setTime(Date2);
        int year2 = calendar.get(Calendar.YEAR);
        int day2 = calendar.get(Calendar.DAY_OF_YEAR);

        if ((year1 == year2) && (day1 == day2)) {
            return true;
        }
        return false;
    }


    static class ViewHolder {

        public ImageView userAvatarImageView;
        public TextView sendDateTextView;
        public TextView userNameTextView;

        public TextView textTextView;
        public ImageView photoImageView;
        public ImageView faceImageView;

        public ImageView failImageView;
        public TextView sendTimeTextView;
        public ProgressBar sendingProgressBar;

        public boolean      isSend = true;
    }


}

GcmBroadcastReceiver.java

package com.example.yoyotrip.GCM;

/**
 * Created by colm on 2015/8/3.
 */

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.ListView;

import com.example.yoyotrip.MainActivity;
import com.example.yoyotrip.R;
import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.util.Date;



public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    public static final int NOTIFICATION_ID = 0;
    public ListView             listView;
    public MessageAdapter       adapter;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        String messageType = gcm.getMessageType(intent);
        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                    .equals(messageType)) {
                Log.i(getClass() + " GCM ERROR", extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                    .equals(messageType)) {
                Log.i(getClass() + " GCM DELETE", extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                    .equals(messageType)) {
                Log.i(getClass() + " GCM MESSAGE", extras.toString());
                if (extras.getString("title") .equals("chat")) {
                    /*show noteic*/
                    Intent i = new Intent(context, MainActivity.class);
                    i.setAction("android.intent.action.MAIN");
                    i.addCategory("android.intent.category.LAUNCHER");
                    MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
                            R.drawable.icon, "noteic", extras
                                    .getString("message"), extras.getString("whofrom"), false,
                            PendingIntent.getActivity(context, 0, i,
                                    PendingIntent.FLAG_CANCEL_CURRENT));
                    //message addchat
                    final Message message = new Message(0, 1, extras.getString("whofrom"), "avatar", "Jerry", "avatar", extras.getString("message"), false, true, new Date());
                    adapter.getData().add(message);
                    adapter.notifyDataSetChanged();
                    listView.setSelection(listView.getBottom());
                } else if (extras.getString("title").equals("GCM")) {
                    Intent i = new Intent(context, MainActivity.class);
                    i.setAction("android.intent.action.MAIN");
                    i.addCategory("android.intent.category.LAUNCHER");
                    MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
                            R.drawable.icon, "GCM noteic", extras
                                    .getString("message"), "yoyotrip", false,
                            PendingIntent.getActivity(context, 0, i,
                                    PendingIntent.FLAG_CANCEL_CURRENT));
                }
            }
        }
        setResultCode(Activity.RESULT_OK);
    }
}

1 个答案:

答案 0 :(得分:0)

您永远不会使用适配器的构造函数在GcmBroadcastReceiver中创建新实例。您的适配器将始终为null,因此,getData()调用NullPointerExceptions。