如何从URL获取数据库多条记录并在Android Table中展示?
Hey Rajvinder, I see exactly what's going on here—let's fix this so all 5 of your messages show up in the table!
The Root Problem
Right now, in your doInBackground loop, you're overwriting the same message_id, sender_id, etc. variables with each iteration. By the end of the loop, those variables only hold the last message's data. Then in onPostExecute, you only create one TableRow using those final values—so only the last message gets displayed (wait, actually you said it shows the first? Wait no, wait—wait in your loop you're assigning message_id = ""+message.getInt("message_id"); each time, so after the loop finishes, those variables have the last item's data. But you said it shows the first? Maybe a typo, regardless, the core issue is you're not storing all the messages, and not creating rows for each one.)
The Fix
We need to store all the messages we fetch, then loop through that collection in onPostExecute to create a TableRow for every entry. Here's how to adjust your code step by step:
1. First, create a simple model class to hold each message's data (cleaner than using loose variables)
Add this class somewhere in your project (either inside your Activity or as a separate file):
public class Message { private String messageId; private String senderId; private String receiverId; private String content; private String date; public Message(String messageId, String senderId, String receiverId, String content, String date) { this.messageId = messageId; this.senderId = senderId; this.receiverId = receiverId; this.content = content; this.date = date; } // Getters to access the data public String getMessageId() { return messageId; } public String getSenderId() { return senderId; } public String getReceiverId() { return receiverId; } public String getContent() { return content; } public String getDate() { return date; } }
2. Modify your AsyncTask to store all messages and pass them to onPostExecute
We'll change the AsyncTask's return type to an ArrayList<Message> so we can send all fetched messages to the UI thread:
private class MyTask extends AsyncTask<Void, Void, ArrayList<Message>> { @Override protected ArrayList<Message> doInBackground(Void... params) { ArrayList<Message> messageList = new ArrayList<>(); // Store all messages here Intent myNewIntent = getIntent(); URL url = null; try { url = new URL("http://192.168.59.1:8080/WebApplication2/cegepgim/mobile/message"); HttpURLConnection client = (HttpURLConnection) url.openConnection(); client.setRequestMethod("GET"); int responseCode = client.getResponseCode(); System.out.println("\n Sending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); InputStreamReader myInput = new InputStreamReader(client.getInputStream()); BufferedReader in = new BufferedReader(myInput); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("The response is " + response.toString()); JSONObject mainObject = new JSONObject(response.toString()); JSONArray jsonArray = mainObject.getJSONArray("message"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject message = jsonArray.getJSONObject(i); // Extract data for this single message String messageId = "" + message.getInt("message_id"); String senderId = "" + message.getInt("sender_id"); String receiverId = "" + message.getInt("receiver_id"); String content = message.getString("message_content"); String date = message.getString("message_date"); // Add this message to our list messageList.add(new Message(messageId, senderId, receiverId, content, date)); } } catch (MalformedURLException | ProtocolException | IOException | JSONException e) { e.printStackTrace(); } return messageList; // Send all messages to onPostExecute } @Override protected void onPostExecute(ArrayList<Message> messageList) { super.onPostExecute(messageList); // Loop through every message and create a TableRow for each for (Message msg : messageList) { TableRow tr = new TableRow(Main3Activity.this); // Create and populate each TextView for the row TextView mszid = new TextView(Main3Activity.this); mszid.setText(msg.getMessageId()); tr.addView(mszid); TextView sendid = new TextView(Main3Activity.this); sendid.setText(msg.getSenderId()); tr.addView(sendid); TextView receid = new TextView(Main3Activity.this); receid.setText(msg.getReceiverId()); tr.addView(receid); TextView mszcontent = new TextView(Main3Activity.this); mszcontent.setText(msg.getContent()); tr.addView(mszcontent); TextView mszdate = new TextView(Main3Activity.this); mszdate.setText(msg.getDate()); tr.addView(mszdate); // Add the completed row to your table myTable1.addView(tr); } } }
Key Changes Explained
- Instead of overwriting single variables, we store every message in an
ArrayList<Message>during the fetch - The AsyncTask now returns this list to
onPostExecute, so we have access to all data on the UI thread - We loop through the list in
onPostExecuteto create a unique TableRow for each message, ensuring all entries are displayed
This should make all 5 of your messages show up in the table as expected!
内容的提问来源于stack exchange,提问作者Rajvinder Kaur

