dimanche 29 novembre 2015

ListView duplicates items everytime I restart the activity

I feel like this is a really simple fix but I am new the android and sqlite in general. I have a array that takes data from a database and then shows them in a list. However every time I restart the app the list adds the items once again into the list. How can I make it not do this?

package com.example.assignmenttracker;

import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.assignmenttracker.MySQLiteHelper;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.app.Activity;

public class MainActivity extends Activity {
 private ListView ListView;
 private Button addbutton;
 public final static String ID_EXTRA="com.example.assignmenttracker._ID";
 public static ArrayList<String> ArrayofName = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.addbutton = (Button)this.findViewById(R.id.button1);
        this.addbutton.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
          Intent intent=new Intent(MainActivity.this, AddAssign.class);
          startActivity(intent);
          }
        });
    }
    private void populateListView() {
        MySQLiteHelper db = new MySQLiteHelper(this);

        List<tasklist> contacts = db.getSometasklist();       

        for (tasklist cn : contacts) {
            Log.d("Reading: ", "Reading all contacts..");
            String log = "Id: "+cn.getID()+" ,Task: " + cn.getTask() + " ,Date: " + cn.getDate() + " ,Status: " + cn.getStatus();
            Log.d("Name: ", log);
            }
        ListView = (ListView) findViewById(R.id.listView1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, ArrayofName);
        ListView.setAdapter(adapter);

        ListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
                Intent i = new Intent(MainActivity.this, ViewAssign.class);
                i.putExtra(ID_EXTRA, String.valueOf(id));
                startActivity(i);}
        });

    }
    @Override
    public void onResume() {
        super.onResume();
        populateListView();
    }
}

Aucun commentaire:

Enregistrer un commentaire