4

I'm trying to retrieve data from MySql database and put it on a ListView, everything works fine, I even put that data into textviews(dynamically) and it works fine. But when I used a ListView, only the last element was displayed, I think that means every new element is overwritten the old one, right?

What can I do to solve this? here's my code tell what's wrong??

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

    }

}

2
  • 1
    Because for each iteration you call addAvailableAppoint() to create a new adapter for your list (with one item). So in the end you'll have only the last item in your ListView. Commented Sep 30, 2015 at 9:06
  • And i wonder why!! I understand now. thank you Commented Sep 30, 2015 at 10:22

2 Answers 2

1

Try this code

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

        }
}

Hope this help

Sign up to request clarification or add additional context in comments.

5 Comments

@Fadwa_lmh if you think this is correct you should mark it as correct answer. thank you
hello! this code was working so fine with me but now i don't know what's wrong with it!! whenever i click to an item it put the value of the last item to the intent!!
could you update your code again then I will easy for check
i have update my anwser. i have change a little bit in public void onItemClick(). please check it
so do i have to change my AvailabilityList class too and add toT & date??
1

You create new ArrayList for every item customList=new ArrayList<>();
Create list only once in OnCreate for example.

Also you create new Adapter every time you add an item, adapter should also be created only once in OnCreate then you should update data with adapter.NotifyDataSetChanged()

1 Comment

I understand now!! thank you it really helped me understand the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.