【问题标题】:Android: ListView from MySQL only display the last elementAndroid:来自 MySQL 的 ListView 仅显示最后一个元素
【发布时间】:2015-09-30 08:59:21
【问题描述】:

我正在尝试从 MySql 数据库中检索数据并将其放在 ListView 上,一切正常,我什至将这些数据放入 textviews(动态)并且它工作正常。但是当我使用ListView 时,只显示了最后一个元素,我认为这意味着每个新元素都会覆盖旧元素,对吧?

我能做些什么来解决这个问题?这是我的代码告诉我出了什么问题??

public class MakeAppointementActivity extends AppCompatActivity {

public List<AvailabilityList> customList;
public ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_make_appointement);
    lv=(ListView)findViewById(R.id.listView);

    Intent intent=getIntent();


    new RetrieveTask().execute();

}

private class RetrieveTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String strUrl = "availableAppointments1.php";
        URL url;
        StringBuffer sb = new StringBuffer();
        try {
            url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream iStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
            String line;
            while( (line = reader.readLine()) != null){
                sb.append(line);
            }

            reader.close();
            iStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        new ParserTask().execute(result);
    }
}

// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>> {
    @Override
    protected List<HashMap<String, String>> doInBackground(String... params) {
        AppointementJSONParser appointementParser = new AppointementJSONParser();
        JSONObject json = null;
        try {
            json = new JSONObject(params[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return appointementParser.parse(json);
    }

 @Override
 protected void onPostExecute(List<HashMap<String, String>> result) {
             customList=new ArrayList<>(); / move it to here
            for (int i = 0; i < result.size(); i++) {
                HashMap<String, String> appointement = result.get(i);
                String fromT = appointement.get("fromT");
                String toT = appointement.get("toT");
                String date = appointement.get("date");

                addAvailableAppoint(fromT,toT,date);
            }
            updateListView(); // update listview when you add all data to arraylist
        }
    }

    private void addAvailableAppoint(final String fromT, final String toT, final String date) {
        customList.add(new AvailabilityList(fromT));
    }

    // split new function for update listview
    private updateListView(){
        ArrayAdapter adapter=new    DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
        adapter.notifyDataSetChanged();
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
                intent.putExtra("fromT", fromT);
                intent.putExtra("toT", toT);
                intent.putExtra("date", date);
                startActivity(intent);
            }
        });

    }

}

【问题讨论】:

  • 因为每次迭代都调用 addAvailableAppoint() 为您的列表创建一个新适配器(带有一个项目)。所以最后你的 ListView 中只有最后一项。
  • 我想知道为什么!!我现在知道了。谢谢

标签: android mysql listview


【解决方案1】:

试试这个代码

     .....// your above code



     @Override
     protected void onPostExecute(List<HashMap<String, String>> result) {
                 customList=new ArrayList<>(); / move it to here
                for (int i = 0; i < result.size(); i++) {
                    HashMap<String, String> appointement = result.get(i);
                    String fromT = appointement.get("fromT");
                    String toT = appointement.get("toT");
                    String date = appointement.get("date");

                    addAvailableAppoint(fromT,toT,date);
                }
                updateListView(); // update listview when you add all data to arraylist
            }
        }

        private void addAvailableAppoint(final String fromT, final String toT, final String date) {
            customList.add(new AvailabilityList(fromT));
        }

        // split new function for update listview
        private updateListView(){
            ArrayAdapter adapter=new    DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
            adapter.notifyDataSetChanged();
            lv.setAdapter(adapter);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
                    // intent.putExtra("fromT", fromT); // change it to
                    intent.putExtra("fromT", customList.get(position).getFromT());  
                    intent.putExtra("toT", toT);
                    intent.putExtra("date", date);
                    startActivity(intent);
                }
            });

        }
}

希望有帮助

【讨论】:

  • @Fadwa_lmh 如果您认为这是正确的,您应该将其标记为正确答案。谢谢
  • 你好!这段代码对我来说很好用,但现在我不知道它有什么问题!!每当我点击一个项目时,它都会将最后一个项目的值放到意图中!!
  • 你能不能再更新一下你的代码,我会方便检查
  • 我已经更新了我的 anwser。我在公共无效onItemClick() 中做了一些改变。请检查一下
  • 所以我是否也必须更改我的 AvailabilityList 类并添加 toT 和日期??
【解决方案2】:

您为每个项目创建新的 ArrayList customList=new ArrayList&lt;&gt;();
例如,在 OnCreate 中只创建一次列表。

此外,您每次添加项目时都会创建新的适配器,适配器也应该只在 OnCreate 中创建一次,然后您应该使用 adapter.NotifyDataSetChanged() 更新数据

【讨论】:

  • 我明白了!!谢谢你,它真的帮助我理解了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多