Android SQLite更新行并更新游标创建的listview

Android SQLite更新行并更新游标创建的listview,android,sqlite,android-cursor,Android,Sqlite,Android Cursor,我有一个用户填写的表单,他们的数据使用SQLite存储在一行中,游标从表中获取他们的详细信息,并将其输出到listView中。 我希望用户能够再次填写该表单,以便更新他们的详细信息,并在listview中显示新的详细信息,以替换那里的旧详细信息。此时发生的情况是,当用户更新其详细信息(再次填写表单)时,将创建另一行,并在中输出新行以及listview中的原始行 MyDBHandler类 package com.astuetz.viewpager.extensions.sample; impor

我有一个用户填写的表单,他们的数据使用SQLite存储在一行中,游标从表中获取他们的详细信息,并将其输出到listView中。 我希望用户能够再次填写该表单,以便更新他们的详细信息,并在listview中显示新的详细信息,以替换那里的旧详细信息。此时发生的情况是,当用户更新其详细信息(再次填写表单)时,将创建另一行,并在中输出新行以及listview中的原始行

MyDBHandler类

package com.astuetz.viewpager.extensions.sample;

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

import java.util.ArrayList;
import java.util.List;

public class MyDBHandler extends SQLiteOpenHelper {

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

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "detailsDB.db";
public static final String TABLE_DETAILS = "details";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_FIRSTNAME = "firstname";
public static final String COLUMN_SURNAME = "surname";
public static final String COLUMN_PHONE = "phone";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_ADDRESS1 = "address1";
public static final String COLUMN_ADDRESS2 = "address2";

public static final String TABLE_KIN_DETAILS = "kindetails";
public static final String COLUMN_KIN_ID = "_id";
public static final String COLUMN_KIN_YOUREMAIL = "youremailkin";
public static final String COLUMN_KIN_FIRSTNAME = "firstnamekin";
public static final String COLUMN_KIN_SURNAME = "surnamekin";
public static final String COLUMN_KIN_PHONE = "phonekin";
public static final String COLUMN_KIN_EMAIL = "emailkin";
public static final String COLUMN_KIN_ADDRESS1 = "address1kin";
public static final String COLUMN_KIN_ADDRESS2 = "address2kin";

// Pass database information along to superclass
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = " CREATE TABLE " + TABLE_DETAILS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_FIRSTNAME + " TEXT, "
            + COLUMN_SURNAME + " TEXT, "
            + COLUMN_PHONE + " TEXT, "
            + COLUMN_EMAIL + " TEXT, "
            + COLUMN_ADDRESS1 + " TEXT, "
            + COLUMN_ADDRESS2 + " TEXT "
            + ");";

    String query2 = " CREATE TABLE " + TABLE_KIN_DETAILS + "("
            + COLUMN_KIN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_KIN_YOUREMAIL + " TEXT, "
            + COLUMN_KIN_FIRSTNAME + " TEXT, "
            + COLUMN_KIN_SURNAME + " TEXT, "
            + COLUMN_KIN_PHONE + " TEXT, "
            + COLUMN_KIN_EMAIL + " TEXT, "
            + COLUMN_KIN_ADDRESS1 + " TEXT, "
            + COLUMN_KIN_ADDRESS2 + " TEXT "
            + ");";
    db.execSQL(query);
    db.execSQL(query2);
}

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

//Add a new row to the database
public void addDetails(Details details) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_FIRSTNAME, details.getFirstname());
    values.put(COLUMN_SURNAME, details.getSurname());
    values.put(COLUMN_PHONE, details.getPhone());
    values.put(COLUMN_EMAIL, details.getEmail());
    values.put(COLUMN_ADDRESS1, details.getAddress1());
    values.put(COLUMN_ADDRESS2, details.getAddress2());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_DETAILS, null, values);
    db.close();
}


public void addKinDetails(KinDetails kinDetails){
    ContentValues values = new ContentValues();
    values.put(COLUMN_KIN_YOUREMAIL, kinDetails.getyourEmailkin());
    values.put(COLUMN_KIN_FIRSTNAME, kinDetails.getFirstnamekin());
    values.put(COLUMN_KIN_SURNAME, kinDetails.getSurnamekin());
    values.put(COLUMN_KIN_PHONE, kinDetails.getPhonekin());
    values.put(COLUMN_KIN_EMAIL, kinDetails.getEmailkin());
    values.put(COLUMN_KIN_ADDRESS1, kinDetails.getAddress1kin());
    values.put(COLUMN_KIN_ADDRESS2, kinDetails.getAddress2kin());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_KIN_DETAILS, null, values);
    db.close();
}






public List<Details> getAllDetails(){

    //create a new list in which we put all persons
    List<Details>detailsList = new ArrayList<>();

    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_DETAILS;

    //Cursor points to a location in your results
    Cursor c = db.rawQuery(query, null);
    //Move to the first row in your results

    if (c != null) {

        c.moveToFirst();

        //Position after the last row means the end of the results
        while (!c.isAfterLast()) {

            //create new details object
            Details details = new Details();

            //Here use static declared on top of the class..don't use "" for the table column
            details.set_id(c.getColumnIndex(COLUMN_ID));
            details.setFirstname(c.getString(c.getColumnIndex(COLUMN_FIRSTNAME)));
            details.setSurname(c.getString(c.getColumnIndex(COLUMN_SURNAME)));
            details.setPhone(c.getString(c.getColumnIndex(COLUMN_PHONE)));
            details.setEmail(c.getString(c.getColumnIndex(COLUMN_EMAIL)));
            details.setAddress1(c.getString(c.getColumnIndex(COLUMN_ADDRESS1)));
            details.setAddress2(c.getString(c.getColumnIndex(COLUMN_ADDRESS2)));

            detailsList.add(details);


            c.moveToNext();
        }

        c.close();
    }

    db.close();

    //return our list of persons
    return detailsList;

}
}
package com.astuetz.viewpager.extensions.sample;

import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.List;

public class DetailsAdapter extends ArrayAdapter<Details> {

private Context context;

//Constructor
public DetailsAdapter(Context context, int resource, List<Details> objects) {
    super(context, resource, objects);

    this.context = context;
}


//The get view is the most crucial part of the adapter, here the listview asks the
//adapter for the row to display

@Override
public View getView(int position, View row, ViewGroup parent) {

    //Get an instance of the holder
    Holder holder;


    //Check if this is the first time creating this row for the listview
    if (row == null){

        //Row was null, need to get components from the row_details.xml
        holder = new Holder();

        //get the Android's layout inflater service which will read row_details.xml
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //Fill the row view with the xml layout file
        row = inflater.inflate(R.layout.row_details, null);

        //Fill the holder with the text view components
        holder.textViewId = (TextView)row.findViewById(R.id.row_details_textview_id);
        holder.textViewName = (TextView)row.findViewById(R.id.row_details_textview_name);
        holder.textViewSurname = (TextView)row.findViewById(R.id.row_details_textview_surname);
        holder.textViewPhone = (TextView)row.findViewById(R.id.row_details_textview_phone);
        holder.textViewEmail = (TextView)row.findViewById(R.id.row_details_textview_email);
        holder.textViewAddress1 = (TextView)row.findViewById(R.id.row_details_textview_address1);
        holder.textViewAddress2 = (TextView)row.findViewById(R.id.row_details_textview_address2);

        //attach the holder to the row
        row.setTag(holder);

    }else{

        //row was created before! thus get the holder object from the row tag
        holder = (Holder)row.getTag();
    }


    //At this point we have our row, either created from new or got it from the row tag object
    //we can now fill the data

    //get our object from the list which is in the position of the listview
    //position is passed to the getView method by the listview



    Details details = getItem(position);

    holder.textViewId.setText("ID: " + details.get_id());
    holder.textViewName.setText("Firstname: " + details.getFirstname());
    holder.textViewSurname.setText("Surname: " + details.getSurname());
    holder.textViewPhone.setText("Phone: " + details.getPhone());
    holder.textViewEmail.setText("Email: " + details.getEmail());
    holder.textViewAddress1.setText("Address1: " + details.getAddress1());
    holder.textViewAddress2.setText("Address2: " + details.getAddress2());

    //return to listview to show
    return row;
}

//A holder will be responsible to hold the components to improve listview performance
//We replicate the components in the row_details.xml
private class Holder{

    TextView textViewName;
    TextView textViewId;
    TextView textViewSurname;
    TextView textViewPhone;
    TextView textViewEmail;
    TextView textViewAddress1;
    TextView textViewAddress2;

}

}
package com.astuetz.viewpager.extensions.sample;
导入android.content.ContentValues;
导入android.content.Context;
导入android.database.sqlite.SQLiteDatabase;
导入android.database.sqlite.SQLiteOpenHelper;
导入android.database.Cursor;
导入android.content.Context;
导入android.content.ContentValues;
导入java.util.ArrayList;
导入java.util.List;
公共类MyDBHandler扩展了SQLiteOpenHelper{
公共MyDBHandler(上下文){
super(上下文、数据库名称、null、数据库版本);
}
私有静态最终int数据库_VERSION=1;
私有静态最终字符串数据库\u NAME=“detailsDB.db”;
公共静态最终字符串表\u DETAILS=“DETAILS”;
公共静态最终字符串列_ID=“_ID”;
公共静态最终字符串列\u FIRSTNAME=“FIRSTNAME”;
公共静态最终字符串列\u姓氏=“姓氏”;
公共静态最终字符串列\u PHONE=“PHONE”;
公共静态最终字符串列\u EMAIL=“EMAIL”;
公共静态最终字符串列_ADDRESS1=“ADDRESS1”;
公共静态最终字符串列_ADDRESS2=“ADDRESS2”;
公共静态最终字符串表\u KIN\u DETAILS=“kindetails”;
公共静态最终字符串列\u KIN\u ID=“\u ID”;
公共静态最终字符串列\u KIN\u YOUREMAIL=“youremailkin”;
公共静态最终字符串列\u KIN\u FIRSTNAME=“firstnamekin”;
public static final String COLUMN\u KIN\u姓氏=“姓氏KIN”;
公共静态最终字符串列\u KIN\u PHONE=“phonekin”;
公共静态最终字符串列\u KIN\u EMAIL=“emailkin”;
公共静态最终字符串列\u kinu ADDRESS1=“address1kin”;
公共静态最终字符串列\u kinu ADDRESS2=“address2kin”;
//将数据库信息传递给超类
公共MyDBHandler(上下文上下文、字符串名称、SQLiteDatabase.CursorFactory工厂、int版本){
超级(上下文、数据库名称、工厂、数据库版本);
}
@凌驾
public void onCreate(SQLiteDatabase db){
String query=“创建表格”+表格详细信息+”(“
+列ID+“整数主键自动递增,”
+列_FIRSTNAME+“文本,”
+列_姓氏+“文本,”
+列\电话+“文本,”
+列_电子邮件+“文本,”
+列地址1+“文本,”
+列地址2+“文本”
+ ");";
String query2=“创建表格”+表格详细信息+”(“
+列\u KIN\u ID+“整数主键自动递增,”
+列\u kinu\u YOUREMAIL+“文本,”
+列\u KIN\u FIRSTNAME+“TEXT”
+列_KIN_姓氏+“文本,”
+列\u kinu\u PHONE+“文本,”
+列\u kinu\u EMAIL+“文本,”
+列\u kinu\u ADDRESS1+“文本”
+列地址2+“文本”
+ ");";
execSQL(查询);
db.execSQL(查询2);
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
db.execSQL(“如果存在删除表”+表的详细信息);
db.execSQL(“如果存在删除表”+表的详细信息);
onCreate(db);
}
//向数据库中添加新行
公共无效添加详细信息(详细信息){
ContentValues=新的ContentValues();
value.put(COLUMN_FIRSTNAME,details.getFirstname());
value.put(列_姓氏,details.get姓氏());
value.put(COLUMN_PHONE,details.getPhone());
value.put(COLUMN_EMAIL,details.getEmail());
value.put(列_ADDRESS1,details.getAddress1());
value.put(COLUMN_ADDRESS2,details.getAddress2());
SQLiteDatabase db=getWritableDatabase();
插入(表_详细信息,空,值);
db.close();
}
公共无效添加KinDetails(KinDetails KinDetails){
ContentValues=新的ContentValues();
value.put(COLUMN\ukinyourEmail,kindetals.getyourEmailkin());
put(COLUMN\u KIN\u FIRSTNAME,kindetals.getFirstnamekin());
value.put(列_KIN_姓氏,kindetals.getnameskin());
value.put(列\ KIN \ PHONE,kindetals.getPhonekin());
value.put(COLUMN_KIN_EMAIL,kindetals.getEmailkin());
put(第1列,kindetals.getAddress1kin());
put(第2列,kindetals.getAddress2kin());
SQLiteDatabase db=getWritableDatabase();
db.insert(表的详细信息,空,值);
db.close();
}
公共列表getAllDetails(){
//创建一个新列表,将所有人员放入其中
ListdetailsList=新的ArrayList();
SQLiteDatabase db=getWritableDatabase();
String query=“SELECT*FROM”+表格\详细信息;
//光标指向结果中的某个位置
游标c=db.rawQuery(查询,空);
//移动到结果的第一行
如果(c!=null){
c、 moveToFirst();
//最后一行后的位置表示结果结束
而(!c.isAfterLast()){
//创建新的详细信息对象
详细信息=新的详细信息();
//这里使用在类顶部声明的static..不要对表列使用“”
details.set_id(c.getColumnIndex(COLUMN_id));
setFirstname(c.getString(c.getColumnIndex(COLUMN_FIRSTNAME));
details.setSurname(c.getString(c.getColumnIndex(COLUMN_姓氏));
setPhone(c.getString(c.getColumnIndex(COLUMN_PHONE));
setEmail(c.getString(c.getColumnIndex(COLUMN_EMAIL));
setAddress1(c.getString(c.getColumnIndex(COLUMN_ADDRESS1));
package com.astuetz.viewpager.extensions.sample;

import com.astuetz.viewpager.extensions.sample.*;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
//import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.widget.Toast;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;


public class FragmentTab1 extends Fragment {
SharedPreferences sharedpreferences;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment1, container, false);
    super.onCreate(savedInstanceState);





    //setContentView(R.layout.fragment1);
    firstName = (TextView) rootView.findViewById(R.id.firstName);
    editTextName = (EditText) rootView.findViewById(R.id.editTextName);
    textView5 = (TextView) rootView.findViewById(R.id.surName);
    editTextSurname = (EditText) rootView.findViewById(R.id.editTextSurname);
    textView4 = (TextView) rootView.findViewById(R.id.mobile);
    editTextMobile = (EditText) rootView.findViewById(R.id.editTextMobile);
    textView2 = (TextView) rootView.findViewById(R.id.Email);
    editTextEmail = (EditText) rootView.findViewById(R.id.editTextEmail);
    textView3 = (TextView) rootView.findViewById(R.id.address1);
    editTextAddress1 = (EditText) rootView.findViewById(R.id.editTextAddress1);
    textView6 = (TextView) rootView.findViewById(R.id.address2);
    editTextAddress2 = (EditText) rootView.findViewById(R.id.editTextAddress2);

    dbHandler = new MyDBHandler(getActivity(), null, null, 1);

   /*sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    //sharedpreferences = this.getActivity().getSharedPreferences("pref",0);


    if (sharedpreferences.contains(FirstName))
    {
        firstName.setText(sharedpreferences.getString(FirstName, ""));

    }
    if (sharedpreferences.contains(SurName))
    {
        textView5.setText(sharedpreferences.getString(SurName, ""));

    }
    if (sharedpreferences.contains(Phone))
    {
        textView4.setText(sharedpreferences.getString(Phone, ""));

    }
    if (sharedpreferences.contains(Emails))
    {
        textView2.setText(sharedpreferences.getString(Emails, ""));

    }
    if (sharedpreferences.contains(Addresss1))
    {
        textView3.setText(sharedpreferences.getString(Addresss1,""));
    }
    if (sharedpreferences.contains(Addresss2))
    {
        textView6.setText(sharedpreferences.getString(Addresss2,""));
    }*/

    Button addButtonClicked = (Button)rootView.findViewById(R.id.addButtonClicked);
    addButtonClicked.setOnClickListener(new OnClickListener(){
        public void onClick(View v)
        {
            addButtonClicked(v);
        }
    });

    return rootView;
}



TextView firstName;
EditText editTextName;

TextView textView5;
EditText editTextSurname;

TextView textView4;
EditText editTextMobile;

TextView textView2;
EditText editTextEmail;

TextView textView3;
EditText editTextAddress1;

TextView textView6;
EditText editTextAddress2;

MyDBHandler dbHandler;


/*public static final String MyPREFERENCES = "MyPrefs" ;
public static final String FirstName = "firstNameKey";
public static final String SurName = "surNameKey";
public static final String Phone = "phoneKey";
public static final String Emails = "emailKey";
public static final String Addresss1 = "address1Key";
public static final String Addresss2 = "address2Key";*/






//validate email provided by user
private boolean isValidEmail(String email) {
    String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}



//Add details to the database and shared preferences
public void addButtonClicked(View view) {

    /*String n  = firstName.getText().toString();
    String sn  = textView5.getText().toString();
    String ph  = textView4.getText().toString();
    String e  = textView2.getText().toString();
    String ad1  = textView3.getText().toString();
    String ad2  = textView6.getText().toString();
    Editor editor = sharedpreferences.edit();
    editor.putString(FirstName, n);
    editor.putString(SurName, sn);
    editor.putString(Phone, ph);
    editor.putString(Emails, e);
    editor.putString(Addresss1, ad1);
    editor.putString(Addresss2, ad2);

    editor.commit();*/




    final String email = editTextEmail.getText().toString();
    if (!isValidEmail(email))
    {
        editTextEmail.setError("Invalid Email");
        Toast.makeText(getActivity().getApplicationContext(), "Invalid email format",
                Toast.LENGTH_LONG).show();

    }
    else if( editTextName.getText().toString().length() == 0 )
    {
        editTextName.setError("First name is required!");
        Toast.makeText(getActivity().getApplicationContext(), "First name is required",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextSurname.getText().toString().length() == 0 )
    {
        editTextSurname.setError("Surname is required!");
        Toast.makeText(getActivity().getApplicationContext(), "Surname is required",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextMobile.getText().toString().length() == 0 || editTextMobile.getText().toString().length() < 10 )
    {
        editTextMobile.setError("Not a valid number!");
        Toast.makeText(getActivity().getApplicationContext(), "Not a valid number",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextAddress1.getText().toString().length() == 0 )
    {
        editTextAddress1.setError("Address Line 1 is required!");
        Toast.makeText(getActivity().getApplicationContext(), "Address Line 1 is required",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextAddress2.getText().toString().length() == 0 )
    {
        editTextAddress2.setError("Address Line 2 is required!");
        Toast.makeText(getActivity().getApplicationContext(), "Address Line 2 is required",
                Toast.LENGTH_LONG).show();
    }
    else
    {
        Details details = new Details();
        details.setFirstname(editTextName.getText().toString());
        details.setSurname(editTextSurname.getText().toString());
        details.setPhone(editTextMobile.getText().toString());
        details.setEmail(editTextEmail.getText().toString());
        details.setAddress1(editTextAddress1.getText().toString());
        details.setAddress2(editTextAddress2.getText().toString());
        dbHandler.addDetails(details);
        Toast.makeText(getActivity().getApplicationContext(), "Details saved successfully",
                Toast.LENGTH_LONG).show();
    }

}

}
  //Updates the no of comments
public void updateDetails(Details details){

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    //Take new values from the details object provided
    values.put(COLUMN_FIRSTNAME, details.getFirstname());
    values.put(COLUMN_SURNAME, details.getSurname());
    values.put(COLUMN_PHONE, details.getPhone());
    values.put(COLUMN_EMAIL, details.getEmail());
    values.put(COLUMN_ADDRESS1, details.getAddress1());
    values.put(COLUMN_ADDRESS2, details.getAddress2());

    //Update the details object where id matches 
    db.update(TABLE_DETAILS, values, COLUMN_ID + "='" + details._id + "'", null);

    db.close();

}
Details details = new Details();

details.set_id(1);
details.setFirstname("Steve");

dbHandler.updateDetails(details);