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

标签 android listview

我的列表中有 20 个联系人,您可以单击每个联系人以转到其详细信息 View 。但是,返回列表后,会再次添加相同的 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);
          }
        });
}

最佳答案

只需放置一个 boolean Controller 来检查它是否已被填充,从而跳过填充 ListView 的 fragment 。

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

关于Android - 每次加载 MainActivity 时都会复制 ListView 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238379/

相关文章:

android - 如何在 AndEngine 中移除碰撞的 box2d 物体?

java - 如何在 Android 中将 .mp4 视频作为背景视频播放?

android - onClick 上的 ListView 和 ListItem 行为

android - 又一个 getView 被多次调用

javascript - 单击行时无法转到新 Activity

android - 如何调整 ListView 项目的屏幕尺寸

Android 多点触控令人头疼

java - 访问已创建 View 的同一实例

java - 查看页面指示器 : listview empty in fragment empty on second time showing

android - 来自枚举的 AlertDialog Builder setSingleChoiceItems