在android中使用适配器进行聊天页面实现列表视图

时间:2014-07-28 07:09:41

标签: java android xml listview adapter

我正在使用以下代码为我的聊天应用程序使用适配器实现列表视图。但是当我执行apk时,应用程序退出时说不响应。请建议我改变。

Chatpage.java

public class chatpage extends Activity {
ArrayList<Message> messages;

ListView list;

ChatAdapter adapter;

static String sender = "9876543210";

String receiver;

EditText chatmessage;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);
    chatmessage = (EditText) findViewById(R.id.entermessage);

      list = (ListView) findViewById(R.id.list);

      try { 
          //adapter = new ChatAdapter(this, messages);
          adapter = new ChatAdapter(this, messages);
          list.setAdapter(adapter); 
          addNewMessage(new Message("test msg",false)); 
          chatmessage.setText("hey");
          } catch(Exception e) {
              chatmessage.setText(e.getMessage()); 
      } 

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.start_page, menu);
    return true;
}

public void sendMessage() {
    chatmessage.setText("send btn clicked");

      String msg = chatmessage.getText().toString(); addNewMessage(new
      Message(msg, true));
      int statusCode; 
try {
      SendMessageTask task = new SendMessageTask(); 
      task.execute(sender,receiver, msg);


          statusCode = task.get(); 
      } catch(Exception e) {
      statusCode = 0; // notify error?? 
      }

      if (statusCode == 1) { // show a 'check' mark to denote successfulv send
          } 
      else {
          // retry
          }
//    }


//  }    // remove after push messages feature is available 
//receiveMessages();
}

void receiveMessages() {
    ArrayList<String> msgs = new ArrayList<String>();

    try{
    ReceiveMessageTask task = new ReceiveMessageTask();
    task.execute();
        msgs = task.get();
    } catch (Exception e) {
        // notify error??
    }

    for (String m : msgs) {
        addNewMessage(new Message(m, false));
    }
}

void addNewMessage(Message m) {
    messages.add(m);
    adapter.notifyDataSetChanged();
    list.setSelection(messages.size() - 1);
}

}

ChatAdapter.java

public class ChatAdapter extends BaseAdapter {

private Context mContext;
private ArrayList<Message> mMessages;

public ChatAdapter(Context context, ArrayList<Message> messages) {
    super();
//  super(context, android.R.layout.simple_list_item_1,messages);
    this.mContext = context;
    this.mMessages = messages;
}

@Override
public int getCount() {
    return mMessages.size();
}

@Override
public Message getItem(int position) {
    return mMessages.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Message message = this.getItem(position);

    ViewHolder holder;
    if (convertView == null) {
        holder = new ViewHolder();
        convertView = LayoutInflater.from(mContext).inflate(R.layout.bubbledesign, parent, false);
        holder.message = (TextView) convertView.findViewById(R.id.message_text);
        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.message.setText(message.getMessage());

    LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();
    // check if it is a status message then remove background, and change
    // text color.
    if (message.isStatusMessage()) {
        holder.message.setBackground(null);
        lp.gravity = Gravity.LEFT;
    //  int c = R.color.textFieldColor;
   //   holder.message.setTextColor(c);
    } else {
        // Check whether message is mine to show green background and align
        // to right
        if (message.isMine()) {
            holder.message.setBackgroundResource(R.drawable.bubblenormal);
            lp.gravity = Gravity.RIGHT;
        }

        // If not mine then it is from sender to show orange background and
        // align to left
        else {
            holder.message.setBackgroundResource(R.drawable.bubblenormal);
            lp.gravity = Gravity.LEFT;
        }
        holder.message.setLayoutParams(lp);
    //  int c = R.color.textColor;
    //  holder.message.setTextColor(c);
    }
    return convertView;
}

private static class ViewHolder {
    TextView message;
}

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

Chat.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/topImage"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentTop="true"
        android:background="#F1760C" 
        android:contentDescription="topimage"/>

    <ImageView
        android:id="@+id/bottomImage"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/topImage"
        android:background="@drawable/app_background"
        android:tileMode="repeat"
        android:contentDescription="bottomimage" />

    <TextView
        android:id="@+id/backtocontacts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="@string/contacts"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/usertochat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:text="Rajat"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ffffff"
        android:textStyle="bold" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="#505050">

        <TextView
            android:id="@+id/add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="19dp"
            android:text=" +"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/entermessage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="22dp"
            android:layout_toLeftOf="@+id/sendmessage"
            android:background="@drawable/shapes2"
            android:ems="10"
            android:gravity="center"
            android:hint="Type your message here"
            android:textStyle="italic" />

        <TextView
            android:id="@+id/sendmessage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/entermessage"
            android:onClick="sendMessage"
            android:text="Send"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="20dp" />

    </RelativeLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="80dp"
        android:layout_marginTop="70dp" 
        app:listitem="@layout/bubbledesign">
    </ListView>

</RelativeLayout>

Message.java

public class Message {
/**
 * The content of the message
 */
String message;

/**
 * Time when message was sent or received
 */
String timeStamp;

/**
 * boolean to determine, who is sender of this message
 */
boolean isMine;

/**
 * boolean to determine, whether the message is a status message or not. it
 * reflects the changes/updates about the sender is writing, have entered
 * text etc
 */
boolean isStatusMessage;

/**
 * Constructor to make a Message object
 */
public Message(String message, boolean isMine) {
    super();
    this.message = message;
    this.isMine = isMine;
    this.isStatusMessage = false;
}

/**
 * Constructor to make a status Message object consider the parameters are
 * swaped from default Message constructor, not a good approach but have to
 * go with it.
 */
public Message(boolean status, String message) {
    super();
    this.message = message;
    this.isMine = false;
    this.isStatusMessage = status;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public boolean isMine() {
    return isMine;
}

public void setMine(boolean isMine) {
    this.isMine = isMine;
}

public boolean isStatusMessage() {
    return isStatusMessage;
}

public void setStatusMessage(boolean isStatusMessage) {
    this.isStatusMessage = isStatusMessage;
}

public String getTimeStamp() {
    return timeStamp;
}

public void setTimeStamp(String timeStamp) {
    this.timeStamp = timeStamp;
}
}

logcat的:

07-29 15:05:38.778: E/AndroidRuntime(942):  FATAL EXCEPTION: main
07-29 15:05:38.778: E/AndroidRuntime(942):  java.lang.NullPointerException
07-29 15:05:38.778: E/AndroidRuntime(942):  at com.classes.ChatAdapter.getCount(ChatAdapter.java:29)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.widget.AbsListView.onAttachedToWindow(AbsListView.java:2615)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.View.dispatchAttachedToWindow(View.java:12125)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2450)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2457)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2457)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2457)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2457)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1207)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.Choreographer.doFrame(Choreographer.java:532)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.os.Handler.handleCallback(Handler.java:730)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.os.Looper.loop(Looper.java:137)
07-29 15:05:38.778: E/AndroidRuntime(942):  at android.app.ActivityThread.main(ActivityThread.java:5103)
07-29 15:05:38.778: E/AndroidRuntime(942):  at java.lang.reflect.Method.invokeNative(Native Method)
07-29 15:05:38.778: E/AndroidRuntime(942):  at java.lang.reflect.Method.invoke(Method.java:525)
07-29 15:05:38.778: E/AndroidRuntime(942):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
07-29 15:05:38.778: E/AndroidRuntime(942):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-29 15:05:38.778: E/AndroidRuntime(942):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

问题在于您的ArrayList<Message> messages,因为它从未在您的代码中初始化。您可以在活动中定义它,然后将其传递给适配器而不进行初始化,这样当适配器运行getCount()方法时,它会尝试返回mMessages的大小,该大小在该点将为空,因此会导致空指针异常。

在活动的onCreate()方法中添加以下行

messages = new ArrayList<Message>();

将它传递给适配器之前。因此,您的onCreate()方法应如下所示。

protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.chat);
  chatmessage = (EditText) findViewById(R.id.entermessage);

  list = (ListView) findViewById(R.id.list);

  try { 
      /** You need the following line added to your code */
      messages = new ArrayList<Message>();
      adapter = new ChatAdapter(this, messages); //In this line the messages was not initialised in your code
      list.setAdapter(adapter); 
      addNewMessage(new Message("test msg",false)); 
      chatmessage.setText("hey");
      } catch(Exception e) {
          chatmessage.setText(e.getMessage()); 
  } 
}