Xonal
Xonal

Reputation: 1360

Android - ListView objects being duplicated every time the MainActivity loads

I have 20 contacts in a list and you can click on each one to go to their detail view. However, upon going back to the list, the same 20 contacts are added in again. I understand that the onCreate() code is just being executed again, but I'm not sure how to fix the issue.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //ArrayList<contact> contacts = new ArrayList<contact>();

    BufferedReader br = null;

    try {
        String s;
        InputStream stream = getAssets().open("contacts.json");
        br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

        StringBuilder sb = new StringBuilder();
        while((s = br.readLine()) != null) {
            sb.append(s);
        }
        s = sb.toString();


        JSONArray ja = new JSONArray(s);
          for (int i = 0; i < ja.length(); i++) {
            JSONObject obj = ja.getJSONObject(i);
            contact c = new contact(); // Creates an empty contact object
            phone p = new phone(); // Creates an empty phone object
            // Retrieves contact information from JSONObject
            String detailsURL = obj.getString("detailsURL"); 
            String name = obj.getString("name");
            int employeeId = obj.getInt("employeeId");
            String company = obj.getString("company");              
            String imageURL = obj.getString("smallImageURL");
            long birthdate = obj.getLong("birthdate");
            JSONObject phone = obj.getJSONObject("phone");
            String workPhone = phone.getString("work");
            String homePhone = phone.getString("home");
            if(phone.has("mobile")){
                    String mobilePhone = phone.getString("mobile");
                    p.setMobilePhone(mobilePhone);
            }
            //Sets contact values to retrieved JSON data and adds to the ArrayList
            c.setName(name);
            c.setEmployeeId(employeeId);
            c.setCompany(company);
            c.setImageURL(imageURL);
            c.setBirthdate(birthdate);
            p.setWorkPhone(workPhone);
            p.setHomePhone(homePhone);
            c.setPhone(p);
            c.setDetailsURL(detailsURL);

            contacts.add(c);
          }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.d("contact", "file");
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("contact", "IO");
    }


    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView1);
    myAdapter adapter = new myAdapter(this, contacts);
    list.setAdapter((ListAdapter) adapter);

    list.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(MainActivity.this, DetailView.class);
                intent.putExtra("contact", i);
                startActivity(intent);
          }
        });
}

Upvotes: 1

Views: 209

Answers (2)

Chike
Chike

Reputation: 306

Is contacts a static member of your activity, and statically initialized? If it is it's not a big mystery since it is only initialized once when the process is created, not the activity, and you keep adding the same contacs with each onCreate.

-- EDIT --

Since the culprit is contacts and not the ListView the simple solution will be to add a condition before the try/catch block:

if (contacts.isEmpty())
    try {
        ...
    }

The rest of the, setting adapter and onclick listener should still be executed.

Upvotes: 0

nKn
nKn

Reputation: 13761

Just skip the snippet that populates your ListView by putting a boolean controller that checks if it already has been populated.

boolean listViewPopulated = false;

if (!listViewPopulated) {
  // Populate your ListView
  ...
  listViewPopulated = true;
}

---- EDIT ----

Try something like this:

class YourClass extends WhatEver {
  boolean listViewPopulated = false;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!listViewPopulated) {
      //ArrayList<contact> contacts = new ArrayList<contact>();

      BufferedReader br = null;

      try {
        String s;
        InputStream stream = getAssets().open("contacts.json");
        br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

        StringBuilder sb = new StringBuilder();
        while((s = br.readLine()) != null) {
            sb.append(s);
        }
        s = sb.toString();


        JSONArray ja = new JSONArray(s);
          for (int i = 0; i < ja.length(); i++) {
            JSONObject obj = ja.getJSONObject(i);
            contact c = new contact(); // Creates an empty contact object
            phone p = new phone(); // Creates an empty phone object
            // Retrieves contact information from JSONObject
            String detailsURL = obj.getString("detailsURL"); 
            String name = obj.getString("name");
            int employeeId = obj.getInt("employeeId");
            String company = obj.getString("company");              
            String imageURL = obj.getString("smallImageURL");
            long birthdate = obj.getLong("birthdate");
            JSONObject phone = obj.getJSONObject("phone");
            String workPhone = phone.getString("work");
            String homePhone = phone.getString("home");
            if(phone.has("mobile")){
                    String mobilePhone = phone.getString("mobile");
                    p.setMobilePhone(mobilePhone);
            }
            //Sets contact values to retrieved JSON data and adds to the ArrayList
            c.setName(name);
            c.setEmployeeId(employeeId);
            c.setCompany(company);
            c.setImageURL(imageURL);
            c.setBirthdate(birthdate);
            p.setWorkPhone(workPhone);
            p.setHomePhone(homePhone);
            c.setPhone(p);
            c.setDetailsURL(detailsURL);

            contacts.add(c);
          }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.d("contact", "file");
      } catch (IOException e) {
        e.printStackTrace();
        Log.d("contact", "IO");
      }

      setContentView(R.layout.activity_main);
      list = (ListView) findViewById(R.id.listView1);
      myAdapter adapter = new myAdapter(this, contacts);
      list.setAdapter((ListAdapter) adapter);

      list.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(MainActivity.this, DetailView.class);
                intent.putExtra("contact", i);
                startActivity(intent);
          }
        });
      }

   listViewPopulated = true;
  }
}

Upvotes: 2

Related Questions