简体   繁体   English

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

[英]How to get all items in arraylist and display it in a listview

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

} }

This is my Chat screen activity.I retrieve the values from the sqlite database and store it in a arraylist. 这是我的聊天屏幕活动。我从sqlite数据库中检索值并将其存储在arraylist中。 When i try to get the data from the arraylist and show in the listview it also shows last item in the arraylist. 当我尝试从arraylist中获取数据并显示在listview中时,它还会显示arraylist中的最后一项。 How to get all the items in arraylist and load it in the listview. 如何获取arraylist中的所有项目并将其加载到listview中。 How to do this? 这个怎么做? Please help to do this 请帮忙

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

The above code is the method of database helper. 上面的代码是数据库助手的方法。

Write this lines outside your for loop. 将此行写在您的for循环之外。

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

Add adapter code in outside of the loop and refresh the list.Because your calling receiveMessage() after that only your setting adapter that is the issue 在循环外添加适配器代码并refresh因为在此之后您只调用设置适配器,这是因为您调用receiveMessage()

1.Main Activity call method like this after listView initialization call receiveMessage() 1.在listView初始化调用receiveMessage()之后的listView Activity这样的调用方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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