数据库ID是互换的android sqlite

时间:2016-03-06 02:57:26

标签: java android database sqlite

大家好日子。我有这个代码,我在删除时遇到问题。例如,我的名单是Junko,Gemina和Fukar。如果我查看每个,他们会显示相同的细节。现在,如果我删除其中任何一个,例如。我删除了Fukar,它将被成功删除但是当我点击Gemina时,出现的细节是Junko。如果我点击Junko,它会说" 不幸的是,该应用程序停止了工作"。如果我添加新名称,例如。 Nimrod,它会成功添加,但当我查看Nimrod时,Gemina的细节将会出现。如果我添加另一个名字,Vourin,Gemina的数据将显示为它们的ID被互换,我认为错误在删除部分。我感谢任何评论。感谢。

以下是我的DBHelper.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.HashMap;



public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "contactdb.sqlite";
public static final String CONTACTS_TABLE_NAME = "mycontacts";
public static final String CONTACTS_COLUMN_ID  = "id";
public static final String CONTACTS_COLUMN_STUNAME = "name";
public static final String CONTACTS_COLUMN_STUPHONE = "phone";
public static final String CONTACTS_COLUMN_STUSTREET = "street";
public static final String CONTACTS_COLUMN_STUEMAIL = "email";
public static final String CONTACTS_COLUMN_STUCITY = "place";

private HashMap hp;

public DBHelper(Context context)
{
    super(context, DATABASE_NAME , null, 3);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "create table mycontacts " +
                    "(id integer primary key autoincrement, name text,phone text,email text, street text,place text)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS mycontacts");
    onCreate(db);
}
public boolean addStudentContact(String contactname,String contactphone,String contactstreet,String contactemail, String contactplace){
    /*,*/
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contantValues = new ContentValues();
    contantValues.put("name",contactname);
    contantValues.put("phone", contactphone);
    contantValues.put("street",contactstreet);
    contantValues.put("email",contactemail);
    contantValues.put("place",contactplace);
    db.insert("mycontacts", null, contantValues);
    db.close();
    return true;
}
public boolean updateStudentContact(Integer contactid,String contactname,String contactphone,String contactstreet,String contactemail, String contactplace)
{
    /*,String contactname,*/
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contantValues = new ContentValues();
    contantValues.put("name",contactname);
    contantValues.put("phone", contactphone);
    contantValues.put("street",contactstreet);
    contantValues.put("email",contactemail);
    contantValues.put("place",contactplace);
    db.update("mycontacts", contantValues, "id = ?", new String[]{Integer.toString(contactid)});
    db.close();
    return true;
}
public Integer deleteContact(Integer id){
    SQLiteDatabase db=this.getWritableDatabase();
    return db.delete("mycontacts","id = ?",new String[]{Integer.toString(id)});
}
public Cursor getData(int contactid){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor res=db.rawQuery("Select * from mycontacts where id = " + contactid + "", null);
    return res;
}
public int numberOfRows(){
    SQLiteDatabase db=this.getWritableDatabase();
    int numRows=(int) DatabaseUtils.queryNumEntries(db,CONTACTS_TABLE_NAME);
    return numRows;
}
 public ArrayList<Person> getAllStudentContacts(){
    ArrayList<Person> arraylist= new ArrayList<>();
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor=db.rawQuery("Select * from mycontacts",null);

    if (cursor.moveToFirst()) {
        do {

            Person person = new Person();
            person.name =   cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_STUNAME));
            person.ID = cursor.getInt(cursor.getColumnIndex(CONTACTS_COLUMN_ID));
            arraylist.add(person);
        } while (cursor.moveToNext());
    }
    return arraylist;
}
}

DisplayContact.java

package com.test.ppandey.contactapp;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayContact extends AppCompatActivity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb;
TextView name;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;

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

    name = (TextView) findViewById(R.id.editTextName);
    phone = (TextView) findViewById(R.id.editTextPhone);
    email = (TextView) findViewById(R.id.editTextStreet);
    street = (TextView) findViewById(R.id.editTextEmail);
    place = (TextView) findViewById(R.id.editTextCity);

    mydb = new DBHelper(this);

    Bundle extras = getIntent().getExtras();
    {
        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;
            rs.moveToFirst();

            String stuname = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUNAME));
            String stuphone = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUPHONE));
            String stuemail = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUEMAIL));
            String stustreet = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUSTREET));
            String stuplace = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUCITY));

            if (!rs.isClosed()) {
                rs.close();
            }
            Button b = (Button) findViewById(R.id.button1);
            b.setVisibility(View.INVISIBLE);

            name.setText((CharSequence) stuname);
            name.setFocusable(false);
            name.setClickable(false);

            phone.setText((CharSequence) stuphone);
            phone.setFocusable(false);
            phone.setClickable(false);

            email.setText((CharSequence) stuemail);
            email.setFocusable(false);
            email.setClickable(false);

            street.setText((CharSequence) stustreet);
            street.setFocusable(false);
            street.setClickable(false);

            place.setText((CharSequence) stuplace);
            place.setFocusable(false);
            place.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.menu_display_contact, menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_main, menu);
        }
    }
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
        case R.id.Edit_Contact:
            Button b = (Button) findViewById(R.id.button1);
            b.setVisibility(View.VISIBLE);
            name.setEnabled(true);
            name.setFocusableInTouchMode(true);
            name.setClickable(true);

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

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

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

            place.setEnabled(true);
            place.setFocusableInTouchMode(true);
            place.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.deleteContact(id_To_Update);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), MainActivity.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 saveData(View view) {
    /*, */
/*            mydb.addContact(name.getText().toString(),email.getText().toString(), street.getText().toString(), place.getText().toString(), phone.getText().toString());
    finish();*/
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        int Value = extras.getInt("id");
        if (Value > 0) {
            if (mydb.updateStudentContact(id_To_Update,   name.getText().toString(), phone.getText().toString(), street.getText().toString(),email.getText().toString(), place.getText().toString())) {
                Toast.makeText(getApplicationContext(), "Successfully Updated", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(), "Record not updated", Toast.LENGTH_SHORT).show();
            }
        } else {
            if (mydb.addStudentContact(name.getText().toString(), phone.getText().toString(),street.getText().toString(), email.getText().toString(),  place.getText().toString())) {
                Toast.makeText(getApplicationContext(), "Successfully Added", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Record not added", Toast.LENGTH_SHORT).show();
            }
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
        }
    }
}

}

MainActivity.java

package com.test.ppandey.contactapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE="MESSAGE";
private ListView objListView;
DBHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db=new DBHelper(this);
    ArrayList<Person> arrayList=db.getAllStudentContacts();
    ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList);

    objListView=(ListView)findViewById(R.id.listView1);
    objListView.setAdapter(arrayAdapter);
    objListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            long id_to_search = id;
            Bundle dataBundle = new Bundle();
            dataBundle.putLong("id", id_to_search);
            Intent intent = new Intent(getApplicationContext(), DisplayContact.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.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
   /* int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);*/
    super.onOptionsItemSelected(item);

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

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

            startActivityForResult(intent, 0);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    db=new DBHelper(this);
    ArrayList<Person> arrayList=db.getAllStudentContacts();
    ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList);

    objListView=(ListView)findViewById(R.id.listView1);
    objListView.setAdapter(arrayAdapter);
}

}

activity_display_contact.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/scrollView1"
>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="350dp"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.test.ppandey.contactapp.DisplayContact">

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="82dp"
        android:ems="10"
        android:inputType="text" >
    </EditText>

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editTextStreet"
        android:layout_below="@+id/editTextStreet"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editTextName"
        android:layout_alignParentLeft="true"
        android:text="@string/name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editTextCity"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="28dp"
        android:onClick="saveData"
        android:text="@string/save" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editTextEmail"
        android:layout_alignLeft="@+id/textView1"
        android:text="@string/email"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editTextPhone"
        android:layout_alignLeft="@+id/textView1"
        android:text="@string/phone"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/editTextEmail"
        android:layout_alignLeft="@+id/textView5"
        android:text="@string/street"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/editTextCity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editTextName"
        android:layout_below="@+id/editTextEmail"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:inputType="text" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editTextCity"
        android:layout_alignBottom="@+id/editTextCity"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/editTextEmail"
        android:text="@string/country"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/editTextStreet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editTextName"
        android:layout_below="@+id/editTextPhone"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editTextPhone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editTextStreet"
        android:layout_below="@+id/editTextName"
        android:ems="10"
        android:inputType="phone|text" />

    </RelativeLayout>
</ScrollView>

Person.java

package com.test.ppandey.contactapp;

/**
 * Created by Ariel on 08/03/2016.
 */
public class Person {

public String name;
public long ID;

private Person person; {
    name = new String(name);

 }
 private Person id; {
    ID = new long(id);

  }
}

我添加了Person.java并编辑了MainActivity.java和DBHelper.java

2 个答案:

答案 0 :(得分:1)

这是你的问题:

int id_to_search = position + 1;

您假设ID和位置同步。只要您不删除任何条目,这只是真实的。

,而不是使用位置来引用条目,你必须使用ID,因为它是不可变的。

从数据库中提取条目时,需要提取名称和ID,并将数据保存在适配器中,这样就可以通过ID来引用条目。

下面的一些代码(只是一个骨架):

1)为您的数据创建模型

public class Person {
    // consider making private and adding accessors
    public String name;
    public long id;
}

2)当您提取数据时,请提取名称和ID(您可以展开Person类和此函数以获取其他数据):

public List<Person> getAllStudentContacts(){
    List<Person> arraylist= new ArrayList<>();
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor=db.rawQuery("Select * from mycontacts",null);

    if (cursor.moveToFirst()) {
        do {
            Person person = new Person();
            person.name = cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_STUNAME));
            person.id = cursor.getInt(cursor.getColumIndex(CONTACTS_COLUMN_ID));
            arraylist.add(prson);
        } while (cursor.moveToNext());
    }
    return arraylist;
}

然后在适配器中使用Person对象中的ID来引用它,而不是位置。

答案 1 :(得分:-1)

您是否在每次插入/删除时从Android应用程序刷新“名称列表”?

也许通过在每次插入/删除后从代码中调用getAllStudentContacts()来重新填充Android应用程序的名称列表?

祝你好运