如何获取arraylist中的所有项目并将其显示在列表视图中

时间:2017-12-18 12:22:23

标签: java android arraylist

public class ChatBubbleActivity extends AppCompatActivity {
private static final String TAG = "ChatActivity";
Toolbar toolbar;
TextView tv_name;
List<ListData> dataList;
int user_id;
int msg_type = 1;
DatabaseHelper databaseHelper;
private ListView listView;
private EditText chatText;
private ImageButton buttonSend;
private String name, message, time;
private ChatArrayAdapter chatArrayAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    name = getIntent().getStringExtra("name");
    user_id = getIntent().getIntExtra("user_id", 0);
    databaseHelper = new DatabaseHelper(this);

    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
    toolbar.setTitleTextColor(getResources().getColor(R.color.white));
    toolbar.setSubtitleTextColor(getResources().getColor(R.color.white));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    receiveMessage();
    tv_name = findViewById(R.id.tv_name);
    buttonSend = findViewById(R.id.buttonSend);
    listView = findViewById(R.id.listView1);
    chatText = findViewById(R.id.chatText);
    listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    listView.setAdapter(chatArrayAdapter);
    chatArrayAdapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            listView.setSelection(chatArrayAdapter.getCount() - 1);
        }
    });
    tv_name.setText(name);
}

private void receiveMessage() {
    dataList = new ArrayList<>();
    dataList = databaseHelper.getSingleUserMsg(user_id);
    for (int i = 0; i < dataList.size(); i++) {
        ListData listData=dataList.get(i);
        message = listData.getMessage();
        time = listData.getCreated_at();
        msg_type = listData.getMsg_type();
        Log.d("Message",message);
        Date dateTime = null;
        try {
            dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a").parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        DateFormat timeFormatter = new SimpleDateFormat("h:mm a");
        int layout_resource;
        if (dataList.get(i).getMsg_type() == 0) {
            layout_resource = R.layout.item_chat_left;
        } else {
            layout_resource = R.layout.item_chat_right;
        }
        chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), layout_resource, dataList, msg_type);
        chatArrayAdapter.add(new ChatMessage(message, timeFormatter.format(dateTime)));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.conversation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

}

这是我的聊天屏幕活动。我从sqlite数据库中检索值并将其存储在arraylist中。当我尝试从 arraylist 获取数据并在列表视图中显示时,它还会显示arraylist中的最后一项。如何获取arraylist中的所有项目并将其加载到listview中。这该怎么做?请帮忙做这个

public List<ListData> getSingleUserMsg(int user_id) {
    List<ListData> listData = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("select message,created_at,msg_type from " + TABLE_MSG + " WHERE " + USER_ID + " = " + user_id + " ORDER BY " + CREATED_AT + ";", null);
    ListData listData1;
    while (cursor.moveToNext()) {
        listData1 = new ListData();
        String message = cursor.getString(cursor.getColumnIndexOrThrow("message"));
        String created_at = cursor.getString(cursor.getColumnIndexOrThrow("created_at"));
        String msg_type = cursor.getString(cursor.getColumnIndexOrThrow("msg_type"));
        listData1.setMessage(message);
        listData1.setMsg_type(Integer.parseInt(msg_type));
        listData1.setCreated_at(created_at);
        listData.add(listData1);
    }
    return listData;
}

上面的代码是数据库助手的方法。

2 个答案:

答案 0 :(得分:1)

将此行写在for循环之外。

chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), layout_resource, dataList, msg_type);
        chatArrayAdapter.add(new ChatMessage(message, timeFormatter.format(dateTime)));

答案 1 :(得分:1)

在循环外添加适配器代码并refresh列表。因为您之后调用receiveMessage()只有您的设置适配器是问题

1. listView初始化调用receiveMessage()

之后的主要活动调用方法
tv_name = findViewById(R.id.tv_name);
buttonSend = findViewById(R.id.buttonSend);
listView = findViewById(R.id.listView1);
chatText = findViewById(R.id.chatText);
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
receiveMessage();

  private void receiveMessage() {
    dataList = new ArrayList<>();
    dataList = databaseHelper.getSingleUserMsg(user_id);
    for (int i = 0; i < dataList.size(); i++) {
        ListData listData=dataList.get(i);
        message = listData.getMessage();
        time = listData.getCreated_at();
        msg_type = listData.getMsg_type();
        Log.d("Message",message);
        Date dateTime = null;
        try {
            dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a").parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        DateFormat timeFormatter = new SimpleDateFormat("h:mm a");
        int layout_resource;
        if (dataList.get(i).getMsg_type() == 0) {
            layout_resource = R.layout.item_chat_left;
        } else {
            layout_resource = R.layout.item_chat_right;
        }

    }
    chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), layout_resource, dataList, msg_type);
    chatArrayAdapter.add(new ChatMessage(message, timeFormatter.format(dateTime)));
    listView.setAdapter(chatArrayAdapter);
}