简体   繁体   中英

Implement list view using adapter for chatpage in android

I am using the following code to implement list view using adapter for my chat application. But when i execute the apk, the application quits by saying not responding. Please suggest me the changes.

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)

The problem is with your ArrayList<Message> messages , because it is never been initialised in you code. You define it in your activity but then pass it to the adapter without initialising it so when your adapter runs getCount() method it tries to return size of mMessages which would be null at that point and hence would result in Null Pointer Exception.

In your onCreate() method of the activity add the following line

messages = new ArrayList<Message>();

before passing it to the adapter. So your onCreate() method should look something like below.

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()); 
  } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM