我觉得这是一个非常简单的修复,但我是一般的android和sqlite。我有一个数组从数据库中获取数据,然后在列表中显示它们。但是,每次重新启动应用程序时,列表都会再次将项目添加到列表中。我怎么能不这样做?
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();
}
}
这是mysqlitehelper的代码
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Contacts Table Columns names
private static final String TABLE_CONTACTS = "tasklist1";
private static final String KEY_ID = "id";
private static final String KEY_TASK = "task";
private static final String KEY_DESC = "desc";
private static final String KEY_MOD = "module";
private static final String KEY_DATE = "date";
private static final String KEY_TYPE = "type";
private static final String KEY_STATUS = "status";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "tasklist1";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TASKLIST_TABLE = "CREATE TABLE tasklist1 ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"task TEXT, "+
"desc TEXT, "+
"module TEXT, "+
"date TEXT, "+
"type TEXT, "+
"status INTEGER )";
db.execSQL(CREATE_TASKLIST_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older task list table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// create fresh task list table
this.onCreate(db);
}
public void insertTask(tasklist tasklist){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, tasklist.getTask());
values.put(KEY_DESC, tasklist.getDesc());
values.put(KEY_MOD, tasklist.getModule());
values.put(KEY_DATE, tasklist.getDate());
values.put(KEY_TYPE, tasklist.getType());
values.put(KEY_STATUS, tasklist.getStatus());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public List<tasklist> getAlltasklist(int passedid) {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS +
" where id = " + passedid;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDesc(cursor.getString(2));
contact.setModule(cursor.getString(3));
contact.setDate(cursor.getString(4));
contact.setType(cursor.getString(5));
contact.setStatus(cursor.getInt(6));
String name = cursor.getString(1);
String desc =cursor.getString(2);
String module =cursor.getString(3);
String date = cursor.getString(4);
String type = cursor.getString(5);
int status = cursor.getInt(6);
ViewAssign.task= name;
ViewAssign.desc=desc;
ViewAssign.module=module;
ViewAssign.date=date;
ViewAssign.type=type;
ViewAssign.status=status;
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public List<tasklist> getSometasklist() {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDate(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(4);
MainActivity.ArrayofName.add(name);
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public void deleteTask(long row) {
// Deletes a row given its rowId, but I want to be able to pass
// in the name of the KEY_NAME and have it delete that row.
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=" + row, null);
db.close();
}
}
答案 0 :(得分:3)
我怀疑结果是:
public static ArrayList<String> ArrayofName = new ArrayList<String>();
这是一个静态变量,意味着in some circumstances,当你第二次运行时,它仍然会在应用程序首次运行时添加你添加的对象。
可能的解决方案:
答案 1 :(得分:0)
我知道我迟到了,但也许会帮助别人 您需要将ArrayList分成两部分 将以下代码放在MainActivity
中ArrayofName = new ArrayList<String>();
并将以下内容放在onCreate()或onResume()方法
中public class JsonReading extends AppCompatActivity {
public ListView listView;
ArrayList<Monitor> lista=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_reading);
Worker worker=new Worker();
worker.execute();
}
public class Worker extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... voids) {
HttpURLConnection connection=null;
InputStream inputStream=null;
InputStreamReader inputStreamReader=null;
BufferedReader bufferedReader=null;
try {
URL url=new URL("https://api.myjson.com/bins/dkit2");
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
//connection.connect();
Log.d("JSON","Se deschide conexiunea");
inputStream=connection.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
bufferedReader=new BufferedReader(inputStreamReader);
String line=null;
StringBuilder builder=new StringBuilder();
while((line=bufferedReader.readLine())!=null){
Log.d("JSON",line);
builder.append(line);
}
String entireJson=builder.toString();
Log.d("JSON",entireJson);
JSONObject monitors=new JSONObject(entireJson);
JSONArray listaJson=monitors.getJSONArray("monitors");
for(int i=0;i<listaJson.length();i++){
JSONObject elementLista=listaJson.getJSONObject(i);
Log.d("JSON",elementLista.toString());
Monitor monitorNou=new Monitor();
monitorNou.setNr_inventar(Integer.parseInt(elementLista.getString("serviceNumber")));
monitorNou.setProducator(elementLista.getString("producer"));
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-mm-yyyy");
monitorNou.setData_intrarii(simpleDateFormat.parse(elementLista.getString("serviceDate")));
//diagonal
monitorNou.setDiagonala(Integer.parseInt(elementLista.getString("diagonal")));
//tip
String tip=elementLista.getString(elementLista.getString("tip"));
if(tip.equals("ALB")){
monitorNou.setTipMonitor(EnumTipMonitor.ALB);
}else{
monitorNou.setTipMonitor(EnumTipMonitor.NEGRU);
}
//owner
monitorNou.setProprietar(elementLista.getString("owner"));
lista.add(monitorNou);
}
}catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}finally {
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStreamReader!=null){
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection!=null){
connection.disconnect();
}
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//afisare in listView
if(lista!=null){
//I believe this is the problem since the listView is not displayed
listView=(ListView)findViewById(R.id.listView_json);
CustomAdapter adapter=new CustomAdapter(getApplicationContext(),R.layout.row_list_item,lista);
listView.setAdapter(adapter);
}
}
}