Android - 每次加载MainActivity时都会复制ListView对象

时间:2014-03-06 23:27:54

标签: android listview

我在列表中有20个联系人,您可以单击每个联系人以转到他们的详细信息视图。但是,回到列表后,再次添加相同的20个联系人。我知道onCreate()代码刚刚被执行,但我不知道如何解决这个问题。

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

2 个答案:

答案 0 :(得分:2)

只需跳过填充ListView boolean控制器的代码段,即可检查是否已填充。{/ p>

boolean listViewPopulated = false;

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

----编辑----

尝试这样的事情:

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

答案 1 :(得分:0)

联系人是您活动的静态成员,是否已静态初始化? 如果它不是一个大问题,因为它只是在创建过程时初始化一次,而不是活动,并且你继续为每个onCreate添加相同的contac。

- 编辑 -

由于罪魁祸首是联系人而不是ListView,简单的解决方案是在try / catch块之前添加一个条件:

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

应该仍然执行设置适配器和onclick侦听器的其余部分。