每次开始活动时,Listview都会从数据库中弹出

时间:2016-05-25 12:43:38

标签: android sqlite listview

我正在将一些json数据提取到EventApp中,并且我试图在SQLite数据库中存储一些事件。我在另一个活动中显示事件,而不是主要事件,每当我从该活动返回到主活动时,我回到带有列表视图的活动,每次都会重复数据。因此,如果我点击该活动10次,我的数据在listview和数据库中也会获得10次。我怎样才能解决这个问题?

SQLiteDatabase db = getWritableDatabase();

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

//Add new row to the database
public void addEvent(Event ev){
    ContentValues contentValues = new ContentValues();
    contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
    contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
    contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
    contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
    contentValues.put(DatabaseHelper.URL, ev.getUrl());
    contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
    contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
    db.insert(TABLE_NAME, null, contentValues);
    //db.close();
}

//Delete event from database
public void deleteEvent(String eventTitle){
    db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}

public int deleteEvents() {
    return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}

//Print the database as string
public String databaseToString(){
    String dbString="";

    //points to a location in results
    Cursor c = getEvents();

    while (c.moveToNext()){
        if(c.getString(c.getColumnIndex("Title")) != null){
            dbString += c.getString(c.getColumnIndex("Title"));
            dbString += "\n";
        }
    }
    //db.close();
    return dbString;
}

public Cursor getEvents(){
    return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}

}

这是我显示数据库中数据的活动

public class StoredEventsActivity extends AppCompatActivity {

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

    setContentView(R.layout.stored_events);

    ListView listView = (ListView) findViewById(R.id.lv_stored_events);

    Intent intent = getIntent();
    ArrayList<Event> events = new ArrayList<Event>();

    events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");

    EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
    listView.setAdapter(adapter);
}

}

以下是返回存储事件的方法

public static ArrayList<Event> returnStoredEvents(){
    long id = -1;
    //getStoredEvents();
    Cursor c = eventsDB.getEvents();

    while (c.moveToNext()){
        id = c.getInt(c.getColumnIndex(eventsDB.ID));
        String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
        String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
        String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
        organizeEvents.add(new Event(title, start, end, true));
    }
    c.close();
    Log.d("DATABASE", organizeEvents.toString());
    return organizeEvents;
}

这是我实际添加一些事件的地方:

private void readEvents(String str){
    Event ev = null;
    try {
        JSONObject geoJSON = new JSONObject(str);
        JSONArray jsonEvents = geoJSON.getJSONArray("events");
        for (int i = 0; i < jsonEvents.length(); i++) {
            JSONObject event = jsonEvents.getJSONObject(i);
            JSONArray timeJsonEvent = event.getJSONArray("datelist");
            JSONObject time = timeJsonEvent.getJSONObject(0);

            title = event.getString("title_english");

            Date date = new Date(time.getLong("start"));
            startDate = dateFormat.format(date);

            date = new Date(time.getLong("end"));
            endDate = dateFormat.format(date);

            imageURL = event.getString("picture_name");
            url = event.getString("url");
            subtitle = event.getString("subtitle_english");
            description = event.getString("description_english");

            if (title.charAt(0) == 'T') {
                ev = new Event(title, startDate, endDate, true);
                eventsDB.addEvent(ev);
            }else {
                    ev = new Event(title, startDate, endDate, false);
            }

            // Process a newly found event
            final Event finalEv = ev;
            handler.post(new Runnable() {
                public void run() {
                    addNewEvent(finalEv);
                }
            });
        }
    }catch (Exception e) {
        Log.d(null, e.getMessage());
    }
}

这是我的主要内容:

public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    eventsDB = new DatabaseHelper(this);
    //storedEvents.addAll(EventsListFragment.returnStoredEvents());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getTitle().equals("Sort by name")){
        Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
        EventsListFragment.sort(-1);
    }else if (item.getTitle().equals("Sort by date")) {
        EventsListFragment.sort(1);
    }else if (item.getTitle().equals("Stored events")){
        showSavedEvents();
        Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
    }
    return true;
}

public void showSavedEvents(){
    intent = new Intent(this, StoredEventsActivity.class);
    intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
    startActivity(intent);
}

}

1 个答案:

答案 0 :(得分:0)

您需要从运行时插入数据,即需要存储用户输入的文本 否则,如果您对数据进行硬编码,则每次刷新活动时都会添加数据

尝试一次只存储一次数据

https://stackoverflow.com/a/37449709/6312749