Android:删除行后更新时的SQLite数据库ID混淆

时间:2016-05-31 20:00:28

标签: android database sqlite android-sqlite

我在这里使用了SQLite数据库指南,http://www.tutorialspoint.com/android/android_sqlite_database.htm,我似乎很难理解为什么删除行后我的rowID没有遵循正确的顺序。

我的代码遵循该数据库的一般格式,但是,每当我从列表中删除一行时,它会移动ID,并且一旦我创建并尝试打开下一行数据,它将无法以相同的方式工作。请帮助我理解并解决这个问题!感谢。

编辑:此人也有类似的问题,但那里的解决方案没有为我修复任何问题。 database id's are interchanged android sqlite

HomeActivity.java

public class HomeActivity extends AppCompatActivity {

public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
StatisticsDbAdapter mydb;

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

    mydb = new StatisticsDbAdapter(this);
    ArrayList array_list = mydb.getAllStats();
    ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);

    obj = (ListView) findViewById(R.id.listView1);
    obj.setAdapter(arrayAdapter);
    obj.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            int id_To_Search = arg2 + 1;

            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", id_To_Search);

            Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);

            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    switch (item.getItemId()) {
        case R.id.item1:
            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", 0);

            Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
            intent.putExtras(dataBundle);

            startActivity(intent);
            return true;
        case R.id.clear_data:
            mydb.removeAll();
        default:
            return super.onOptionsItemSelected(item);
    }
}

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}
}

DisplayStatsActivity.java

public class DisplayStatsActivity extends AppCompatActivity {
private StatisticsDbAdapter mydb;

EditText title, singles, doubles, triples, homeruns, atbats, walks, hitbypitch, strikeouts, runs, runsbattedin, stolenbases, caughtstealing;
int id_To_Update = 0;


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

    title = (EditText) findViewById(R.id.editTitle);
    singles = (EditText) findViewById(R.id.editsingles);
    doubles = (EditText) findViewById(R.id.editdoubles);
    triples = (EditText) findViewById(R.id.edittriples);
    homeruns = (EditText) findViewById(R.id.edithomeruns);
    atbats = (EditText) findViewById(R.id.editatbats);
    walks = (EditText) findViewById(R.id.editwalks);
    hitbypitch = (EditText) findViewById(R.id.edithitbypitch);
    strikeouts = (EditText) findViewById(R.id.editstrikeouts);
    runs = (EditText) findViewById(R.id.editruns);
    runsbattedin = (EditText) findViewById(R.id.editrbis);
    stolenbases = (EditText) findViewById(R.id.editsteals);
    caughtstealing = (EditText) findViewById(R.id.editcaughtstealing);

    mydb = new StatisticsDbAdapter(this);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        int Value = extras.getInt("id");

        if (Value > 0) {
            //means this is the view part not the add contact part

            Cursor rs = mydb.getData(Value);
            id_To_Update = Value;

            if (rs != null && rs.moveToFirst()) {

                String ctitle = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_TITLE));
                String csingles = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_SINGLES));
                String cdoubles = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_DOUBLES));
                String ctriples = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_TRIPLES));
                String chomeruns = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_HOMERUNS));
                String catbats = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_ATBATS));
                String cwalks = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_WALKS));
                String chitbypitch = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_HITBYPITCH));
                String cstrikeouts = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_STRIKEOUTS));
                String cruns = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_RUNS));
                String crbis = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_RUNSBATTEDIN));
                String cstolenbases = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_STOLENBASES));
                String ccaughtstealing = rs.getString(rs.getColumnIndex(StatisticsDbAdapter.COLUMN_CAUGHTSTEALING));


                if (!rs.isClosed()) {
                    rs.close();
                }

                Button b = (Button) findViewById(R.id.button1);
                b.setVisibility(View.INVISIBLE);

                title.setText((CharSequence) ctitle);
                title.setFocusable(false);
                title.setClickable(false);

                singles.setText((CharSequence) csingles);
                singles.setFocusable(false);
                singles.setClickable(false);

                doubles.setText((CharSequence) cdoubles);
                doubles.setFocusable(false);
                doubles.setClickable(false);

                triples.setText((CharSequence) ctriples);
                triples.setFocusable(false);
                triples.setClickable(false);

                homeruns.setText((CharSequence) chomeruns);
                homeruns.setFocusable(false);
                homeruns.setClickable(false);

                atbats.setText((CharSequence) catbats);
                atbats.setFocusable(false);
                atbats.setClickable(false);

                walks.setText((CharSequence) cwalks);
                walks.setFocusable(false);
                walks.setClickable(false);

                hitbypitch.setText((CharSequence) chitbypitch);
                hitbypitch.setFocusable(false);
                hitbypitch.setClickable(false);

                strikeouts.setText((CharSequence) cstrikeouts);
                strikeouts.setFocusable(false);
                strikeouts.setClickable(false);

                runs.setText((CharSequence) cruns);
                runs.setFocusable(false);
                runs.setClickable(false);

                runsbattedin.setText((CharSequence) crbis);
                runsbattedin.setFocusable(false);
                runsbattedin.setClickable(false);

                stolenbases.setText((CharSequence) cstolenbases);
                stolenbases.setFocusable(false);
                stolenbases.setClickable(false);

                caughtstealing.setText((CharSequence) ccaughtstealing);
                caughtstealing.setFocusable(false);
                caughtstealing.setClickable(false);
            }
        }
    }

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        int Value = extras.getInt("id");
        if (Value > 0) {
            getMenuInflater().inflate(R.menu.display_statistic, menu);
        } else {
            getMenuInflater().inflate(R.menu.main_menu, menu);
        }
    }
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
        case R.id.Edit_Contact:
            Button b = (Button) findViewById(R.id.button1);
            b.setVisibility(View.VISIBLE);
            title.setEnabled(true);
            title.setFocusableInTouchMode(true);
            title.setClickable(true);

            singles.setEnabled(true);
            singles.setFocusableInTouchMode(true);
            singles.setClickable(true);

            doubles.setEnabled(true);
            doubles.setFocusableInTouchMode(true);
            doubles.setClickable(true);

            triples.setEnabled(true);
            triples.setFocusableInTouchMode(true);
            triples.setClickable(true);

            homeruns.setEnabled(true);
            homeruns.setFocusableInTouchMode(true);
            homeruns.setClickable(true);

            atbats.setEnabled(true);
            atbats.setFocusableInTouchMode(true);
            atbats.setClickable(true);

            walks.setEnabled(true);
            walks.setFocusableInTouchMode(true);
            walks.setClickable(true);

            hitbypitch.setEnabled(true);
            hitbypitch.setFocusableInTouchMode(true);
            hitbypitch.setClickable(true);

            strikeouts.setEnabled(true);
            strikeouts.setFocusableInTouchMode(true);
            strikeouts.setClickable(true);

            runs.setEnabled(true);
            runs.setFocusableInTouchMode(true);
            runs.setClickable(true);

            runsbattedin.setEnabled(true);
            runsbattedin.setFocusableInTouchMode(true);
            runsbattedin.setClickable(true);

            stolenbases.setEnabled(true);
            stolenbases.setFocusableInTouchMode(true);
            stolenbases.setClickable(true);

            caughtstealing.setEnabled(true);
            caughtstealing.setFocusableInTouchMode(true);
            caughtstealing.setClickable(true);

            return true;
        case R.id.Delete_Contact:

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.deleteContact)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mydb.deleteStat(id_To_Update);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog d = builder.create();
            d.setTitle("Are you sure?");
            d.show();

            return true;
        default:
            return super.onOptionsItemSelected(item);

    }
}

public void run(View view)
{
    Bundle extras = getIntent().getExtras();
    if(extras !=null)
    {
        int Value = extras.getInt("id");
        if(Value>0){
            if(mydb.updateStats(id_To_Update,title.getText().toString(), singles.getText().toString(),
                    doubles.getText().toString(), triples.getText().toString(),
                    homeruns.getText().toString(), atbats.getText().toString(),
                    walks.getText().toString(), hitbypitch.getText().toString(),
                    strikeouts.getText().toString(), runs.getText().toString(),
                    runsbattedin.getText().toString(), stolenbases.getText().toString(),
                    caughtstealing.getText().toString())){
                Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
                startActivity(intent);
            }
            else{
                Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
            }
        }
        else{
            if(mydb.insertStat(title.getText().toString(), singles.getText().toString(),
                    doubles.getText().toString(), triples.getText().toString(),
                    homeruns.getText().toString(), atbats.getText().toString(),
                    walks.getText().toString(), hitbypitch.getText().toString(),
                    strikeouts.getText().toString(), runs.getText().toString(),
                    runsbattedin.getText().toString(), stolenbases.getText().toString(),
                    caughtstealing.getText().toString())){
                Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
            }

            else{
                Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
            }
            Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
            startActivity(intent);
        }
    }
}

StatisticsDbAdapter.java

public class StatisticsDbAdapter extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "statistics.db";
private static final int DATABASE_VERSION = 1;

//every one of these columns represents the information about the data
public static final String STATS_TABLE = "stats";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_SINGLES = "singles";
public static final String COLUMN_DOUBLES = "doubles";
public static final String COLUMN_TRIPLES = "triples";
public static final String COLUMN_HOMERUNS = "homeruns";
public static final String COLUMN_ATBATS = "atbats";
public static final String COLUMN_WALKS = "walks";
public static final String COLUMN_HITBYPITCH = "hitbypitch";
public static final String COLUMN_STRIKEOUTS = "strikeouts";
public static final String COLUMN_RUNS = "runs";
public static final String COLUMN_RUNSBATTEDIN = "runsbattedin";
public static final String COLUMN_STOLENBASES = "stolenbases";
public static final String COLUMN_CAUGHTSTEALING = "caughtstealing";

public StatisticsDbAdapter(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

/*

private String[] allColumns = {COLUMN_ID, COLUMN_TITLE, COLUMN_SINGLES, COLUMN_DOUBLES,
        COLUMN_TRIPLES, COLUMN_HOMERUNS, COLUMN_ATBATS, COLUMN_WALKS, COLUMN_HITBYPITCH,
        COLUMN_STRIKEOUTS, COLUMN_RUNS, COLUMN_RUNSBATTEDIN, COLUMN_STOLENBASES,
        COLUMN_CAUGHTSTEALING, COLUMN_DATE};

public static final String CREATE_TABLE_STATS = "create table " + STATS_TABLE +
        " ( " + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE +
        " text not null " + COLUMN_SINGLES + " text not null " + COLUMN_DOUBLES +
        " text not null " + COLUMN_TRIPLES + " text not null " + COLUMN_HOMERUNS +
        " text not null " + COLUMN_ATBATS + " text not null " + COLUMN_WALKS +
        " text not null " + COLUMN_HITBYPITCH + " text not null " + COLUMN_STRIKEOUTS +
        " text not null " + COLUMN_RUNS + " text not null " + COLUMN_RUNSBATTEDIN +
        " text not null " + COLUMN_STOLENBASES + " text not null " + COLUMN_CAUGHTSTEALING +
        " text not null " + COLUMN_DATE + ");";

private SQLiteDatabase sqlDB;
private Context context;

*/

//removed TITLE
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "create table stats " + "(id integer primary key autoincrement, title text, singles text," +
                    " doubles text, triples text, homeruns text, atbats text, walks text," +
                    " hitbypitch text, strikeouts text, runs text, runsbattedin text," +
                    " stolenbases text, caughtstealing text)"


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

//removed String title
public boolean insertStat(String title, String singles, String doubles, String triples,
                          String homeruns, String atbats, String walks, String hitbypitch,
                          String strikeouts, String runs, String runsbattedin,
                          String stolenbases, String caughtstealing) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("title", title);
    contentValues.put("singles", singles);
    contentValues.put("doubles", doubles);
    contentValues.put("triples", triples);
    contentValues.put("homeruns", homeruns);
    contentValues.put("atbats", atbats);
    contentValues.put("walks", walks);
    contentValues.put("hitbypitch", hitbypitch);
    contentValues.put("strikeouts", strikeouts);
    contentValues.put("runs", runs);
    contentValues.put("runsbattedin", runsbattedin);
    contentValues.put("stolenbases", stolenbases);
    contentValues.put("caughtstealing", caughtstealing);
    db.insert(STATS_TABLE, null, contentValues);
    return true;
}

public Cursor getData(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM stats where id = " + id, null);
    res.moveToFirst();

    return res;

}

public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, STATS_TABLE);
    return numRows;
}

public boolean updateStats(Integer id, String title, String singles, String doubles,
                           String triples, String homeruns, String atbats, String walks,
                           String hitbypitch, String strikeouts, String runs,
                           String runsbattedin, String stolenbases, String caughtstealing) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("title", title);
    contentValues.put("singles", singles);
    contentValues.put("doubles", doubles);
    contentValues.put("triples", triples);
    contentValues.put("homeruns", homeruns);
    contentValues.put("atbats", atbats);
    contentValues.put("walks", walks);
    contentValues.put("hitbypitch", hitbypitch);
    contentValues.put("strikeouts", strikeouts);
    contentValues.put("runs", runs);
    contentValues.put("runsbattedin", runsbattedin);
    contentValues.put("stolenbases", stolenbases);
    contentValues.put("caughtstealing", caughtstealing);
    db.update(STATS_TABLE, contentValues, "id = ? ", new String[]{Integer.toString(id)});
    return true;
}


public Integer deleteStat(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(STATS_TABLE, "id = ? ", new String[]{Integer.toString(id)});
}

public void removeAll() {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(STATS_TABLE, null, null);
}

public ArrayList<String> getAllStats() {
    ArrayList<String> array_list = new ArrayList<String>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery("select * from " + STATS_TABLE, null);
    res.moveToFirst();

    while (res.isAfterLast() == false) {
        array_list.add(res.getString(res.getColumnIndex(COLUMN_TITLE)));
        array_list.add(res.getString(res.getColumnIndex(COLUMN_ID)));

        res.moveToNext();
    }
    db.close();
    return array_list;
}
}

0 个答案:

没有答案