qq_16207577
wksnsw
采纳率0%
2015-05-11 02:27 阅读 5.9k

android ListView Adapter不显示

//activity
package wk.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import wk.bluetooth.StartServer.ChatListItem;

public class StartClient extends Activity implements OnItemClickListener ,OnClickListener{

private ListView mListView;
ChatAdapter mAdapter;
private ArrayList<ChatListItem> list;

private EditText sendMessage;
private Button sendButton;
private TextView title;
private ImageButton back;

private String joinChatRoomName;
private String address;
private String nowTime;

private BluetoothSocket socket;
private BluetoothDevice device = null;
private clientThread startClient = null;
private readThread mreadThread = null;
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();



Context mContext;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.chat);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.titlebar);
    Bundle bundle = this.getIntent().getExtras();
    joinChatRoomName = bundle.getString("joinChatRoomName");
    address = bundle.getString("address");

    mContext = this;
    init();
}
private  void init(){
    device = mBluetoothAdapter.getRemoteDevice(address);

    list = new ArrayList<ChatListItem>();
    mAdapter = new ChatAdapter(mContext, list);
    mListView = (ListView) findViewById(R.id.chat_list);
    mListView.setAdapter(mAdapter);
    //mListView.setOnItemClickListener(this);
    mListView.setFastScrollEnabled(true);

    title = (TextView) findViewById(R.id.title);
    title.setText(joinChatRoomName);


    back = (ImageButton) findViewById(R.id.back);
    back.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if(mreadThread!=null){
                mreadThread.interrupt();
            }
            if(startClient != null){
                startClient.interrupt();
            }
            list.clear();
            StartClient.this.finish();
        }
    });


    sendMessage = (EditText)findViewById(R.id.MessageText);
    sendButton = (Button)findViewById(R.id.btn_msg_send);
    sendButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg= sendMessage.getText().toString();
            if(msg.length()>0){
                SendMessageHandle(msg);
                sendMessage.setText("");
                sendMessage.clearFocus();
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(sendMessage.getWindowToken(), 0);

            }else{
                Toast.makeText(mContext, "消息发送失败", Toast.LENGTH_SHORT).show();
                sendMessage.setText("");
                sendMessage.clearFocus();
            }

        }
    });
    if(Bluetooth.joinChatRoom.get(address)) {
        Log.d("StartClient","join again");
        mreadThread = new readThread();
        mreadThread.start();

    }else{
        Log.d("StartClient","first time join");
        startClient = new clientThread();
        startClient.start();
    }


}

private class clientThread extends Thread {
    @Override
    public void run() {
        try {

            Message msg2 = new Message();
            msg2.obj = "正在加入"+device.getName()+"的聊天室";
            msg2.what = 2;
            LinkDetectedHandler.sendMessage(msg2);
            //创建一个Socket连接:只需要服务器在注册时的UUID号
            socket = Bluetooth.joinChatRoomSocket.get(address);
            //连接
            socket.connect();
            Bluetooth.joinChatRoomSocket.put(address,socket);
            Bluetooth.joinChatRoom.put(address,true);


           // new IsNotConnected().start();

            //启动接受数据
            mreadThread = new readThread();
            mreadThread.start();
        }
        catch (IOException e)
        {
            Bluetooth.joinChatRoom.put(address,false);
            Message msg = new Message();
            msg.obj = "加入聊天室失败,请断开重试";
            msg.what = 2;
            LinkDetectedHandler.sendMessage(msg);
        }

    }
}

//读取数据
private class readThread extends Thread {
@Override
public void run() {
Log.d("StartClient","read buffer");
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;

        try {
            mmInStream = Bluetooth.joinChatRoomSocket.get(address).getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        while (true) {
            try {
                // Read from the InputStream
                if ((bytes = mmInStream.read(buffer)) > 0) {
                    byte[] buf_data = new byte[bytes];
                    for (int i = 0; i < bytes; i++) {
                        buf_data[i] = buffer[i];
                    }

                    String s = new String(buf_data);
                    Log.d("ReceiveMessage",s+"-------");
                    if(s.equals("MARLBORO")){
                        continue;
                    }

                    Message message = new Message();
                    message.obj = s;
                    message.what = 1;
                    LinkDetectedHandler.sendMessage(message);
                }
            } catch (IOException e) {
                try {
                    mmInStream.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                break;
            }

        }
    }
}

private Handler LinkDetectedHandler = new Handler() {
    //what = 0发送的消息
    //what = 1接受的消息
    //what = 2公共消息
    @Override
    public void handleMessage(Message msg) {
        Log.d("ReceiveMessage", msg.obj + "   " + msg.what);
        SimpleDateFormat formatter = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        nowTime = formatter.format(new Date(System.currentTimeMillis()));

        list.add(new ChatListItem((String) msg.obj, nowTime, msg.what));

        Log.d("ReceiveMessage","list size"+list.size());

        Log.d("ReceiveMessage","adddddddddddd");
        mAdapter.notifyDataSetChanged();
        mListView.setSelection(list.size() - 1);


    }

};

private void SendMessageHandle(String msg){
    Log.d("StartClient","send message"+msg);
    try {
        OutputStream outputStream = Bluetooth.joinChatRoomSocket.get(address).getOutputStream();
        outputStream.write(msg.getBytes());
    } catch (Exception e) {}
    Message m = new Message();
    m.obj = msg;
    m.what = 0;
    LinkDetectedHandler.sendMessage(m);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
}
@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
}

public class joinChatListItem {
    String message;
    Integer flag;

    public joinChatListItem(String msg, Integer f) {
        message = msg;
        flag = f;
    }
}

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • qq_16207577 wksnsw 2015-05-11 02:29

    //adapter
    package wk.bluetooth;

    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import wk.bluetooth.StartServer.ChatListItem;

    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;

    /**

    • Created by wk on 2015/5/4.
      */
      public class ChatAdapter extends BaseAdapter {
      private ArrayList list;
      private LayoutInflater mInflater;

      public ChatAdapter(Context context, ArrayList l) {
      list = l;
      mInflater = LayoutInflater.from(context);
      }

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

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

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

      @Override
      public int getItemViewType(int position) {
      return position;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder viewHolder = null;
      int[] textView ={R.id.send_text,R.id.receive_text,R.id.receive_text};
      int[] imageView = {R.id.send_head_image,R.id.receive_head_image, R.id.receive_head_image};
      int[] layout = {R.layout.send_message,R.layout.receive_message, R.layout.receive_message};
      Log.d("ChatAdapter","hhhhhhhhhhhhhhhhhhhh");
      ChatListItem item=list.get(position);
      Log.d("ChatAdapter","item.flag "+item.flag+"item.mes "+item.message);
      // if(convertView == null){
      Log.d("ChatAdapter","--"+item.message+" -- "+ item.flag);
      convertView = mInflater.inflate(layout[item.flag], null);
      viewHolder=new ViewHolder(
      // convertView.findViewById(R.id.list_child),
      (TextView) convertView.findViewById(textView[item.flag])
      , (TextView) convertView.findViewById(R.id.message_time)
      ,(ImageView) convertView.findViewById(imageView[item.flag])
      );
      convertView.setTag(viewHolder);
      //}

      //else{
        //  Log.d("ChatAdapter","nullllllllllll");
         // viewHolder = (ViewHolder)convertView.getTag();
      //}
      if(item.flag==2){
          Log.d("ChatAdapter",item.message+"--"+item.flag);
          viewHolder.time.setText(item.message);
          viewHolder.msg.setVisibility(View.GONE);
          viewHolder.img.setVisibility(View.GONE);
      }else {
          viewHolder.msg.setVisibility(View.VISIBLE);
          viewHolder.img.setVisibility(View.VISIBLE);
          viewHolder.time.setText(item.time);
          viewHolder.msg.setText(item.message);
      }
      return convertView;
      

      }

      class ViewHolder {
      protected TextView msg;
      protected TextView time;
      protected ImageView img;

      public ViewHolder(TextView message, TextView t, ImageView im){
          this.msg = message;
          this.time = t;
          this.img = im;
      
      }
      

      }
      }

    我能收到socket发送的消息,但是我多次调用这个activity后 list没有add数据adapter也没有调用日志
    运行结果

    点赞 评论 复制链接分享
  • danielinbiti danielinbiti 2015-05-11 02:49

    只要没有点返回之类的按钮,list应该是不断增大了。先跟踪看看list没有增加的原因吧

    点赞 评论 复制链接分享

相关推荐