Android:自定义适配器无法在活动恢复时重新加载列表视图

时间:2014-02-22 22:00:54

标签: android android-listview android-activity android-adapter android-handler

我正在尝试使用列表视图上的自定义适配器显示收到的消息,直到现在一切正常,但当我按回并再次启动此活动时,只有消息发送有效,但收到的消息无法显示在列表显示。

到目前为止我已经完成的步骤:

  • 使用调试器查明消息是否为空,消息是否为空 收到而不是空的。

  • 在receive()函数中使用调试器,它首先出现 启动活动looper.loop()函数将控制权交还给 主线程,但下次在活动恢复时这个循环没有 似乎结束了(可能这是错误的原因)。

    p.s:在第一次启动此活动时,我可以显示收到的消息,但是当我返回并恢复活动时,receive()失败,我在这里一无所知,欢迎任何正确方向的小提示,谢谢你的时间。

    public class hotListener扩展了ListActivity {

    private XMPPConnection connection;
    private IBinder binder;
    private Handler mHandler = new Handler();
    private ArrayList<String> messages = new ArrayList<String>();
    ArrayList<ChatMessage> messagex= new ArrayList<ChatMessage>();;
    ChattingAdapter adaptex;
    Intent mIntent ;
    private ListView listview;
    EditText sender_message ;
    String msg;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listener);
        //messagex.add(new ChatMessage("Hello", false));
        adaptex  = new ChattingAdapter(getApplicationContext(),messagex);
        setListAdapter(adaptex);
    
        Button send_button = (Button) findViewById(R.id.chat_send_message);
        sender_message = (EditText) findViewById(R.id.chat_input);
        send_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msg = sender_message.getText().toString();
                sender_message.setText("");
                if(!(msg.length()==0)){
                    messagex.add(new ChatMessage(msg, true));
                    //addNewMessage(new ChatMessage(msg, true));
                    adaptex.notifyDataSetChanged();
                    getListView().setSelection(messagex.size()-1);
                }
    
            }
        });
        if(!isMyServiceRunning()){
            System.out.println("seems like service not running");
            startService(new Intent(this,xService.class));
            System.out.print(" now started ");
        }       
    }
    
    @Override
    protected void onStart(){
        super.onStart();
        Boolean kuch = bindService(new Intent(this,xService.class), mConnection,Context.BIND_AUTO_CREATE);
        //System.out.println(kuch);
        //System.out.println("bind done");        
    }
    
    private void receives(XMPPConnection connection2) {
            //ChatManager chatmanager = connection.getChatManager();
            connection2.getChatManager().addChatListener(new ChatManagerListener() {
    
                @Override
                public void chatCreated(Chat arg0, boolean arg1) {
                    arg0.addMessageListener(new MessageListener() {
    
                        @Override
                        public void processMessage(Chat chat, Message message) {
    
                            final String from = message.getFrom();
                            final String body = message.getBody();
                            mHandler.post(new Runnable() {
                                ChatMessage kudi = new ChatMessage(body, false);
                                @Override
                                public void run() {
                                    //setListAdapter(1);
                                    messagex.add(kudi);
                                    adaptex.notifyDataSetChanged();
                                    getListView().setSelection(messagex.size()-1);
                                    Toast.makeText(hotListener.this,body,Toast.LENGTH_SHORT).show();                                }
                            });
                            //System.out.println(String.format("Received message "+body +" from "+ from));
                        }
                    });
                }
            });
    }
    
    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
            if(xService.class.getName().equals(service.service.getClassName())){
                return true;
            }
        }
        //System.out.print("false");
        return false;
    }
    
    @Override
      protected void onResume() {
        bindService(new Intent(this, xService.class), mConnection, Context.BIND_AUTO_CREATE);
        setListAdapter(adaptex);
        adaptex.notifyDataSetChanged();
        super.onResume();
      }
     @Override
      protected void onPause() {
        unbindService(mConnection);
        super.onPause();
      }
    
     private ServiceConnection mConnection = new ServiceConnection() {
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
                connection = null;
                service = null;
            }
    
            @Override
            public void onServiceConnected(ComponentName name, IBinder binder) {
                //System.out.println("binding in hot listener");
                service = ((xService.MyBinder)binder).getService();
                connection = service.getConnection();
                receives(connection);
                Log.wtf("Service","connected");
            }
        };
    
        void addNewMessage(ChatMessage m)
        {
            System.out.println("1");
            messagex.add(m);
            System.out.println("2");
            adaptex.notifyDataSetChanged();
            System.out.println("3");
            getListView().setSelection(messagex.size()-1);
        }
    

    }

我的适配器:

import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class ChattingAdapter extends BaseAdapter{
    private Context mContext;
    private ArrayList<ChatMessage> mMessages;


    public ChattingAdapter(Context context, ArrayList<ChatMessage> messages) {
        super();
        this.mContext = context;
        this.mMessages = messages;
    }
    @Override
    public int getCount() {
        return mMessages.size();
    }
    @Override
    public Object getItem(int position) {       
        return mMessages.get(position);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ChatMessage message = (ChatMessage) this.getItem(position);

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

        holder.message.setText(message.getMessage());
        LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();      

        //Check whether message is mine to show green background and align to right

        if(message.isMine())

        {           holder.message.setBackgroundResource(R.drawable.msgbox_new_selected_go_up);         

                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.msgbox_other_go_up);

            lp.gravity = Gravity.LEFT;

        }
            holder.message.setLayoutParams(lp);
            //holder.message.setTextColor(R.color.textColor);   

        return convertView;
    }
    private static class ViewHolder
    {
        TextView message;
    }

    @Override
    public long getItemId(int position) {
        //Unimplemented, because we aren't using Sqlite.
        return position;
    }

}

0 个答案:

没有答案