**



  我想在SQLite数据库列表视图中删除并更新一行
  使用Alert对话框在任何项目上计时。
  操作不正常,这是什么错误?
       08-25 09:40:14.429 8664-8664 / com.example.user.dbprojectsqlite E / SpannableStringBuilder:SPAN_EXCLUSIVE_EXCLUSIVE范围不能包含
  零长度
              SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
          08-25 09:40:53.180 8664-8664 / com.example.user.dbprojectsqlite E / SpannableStringBuilder:SPAN_EXCLUSIVE_EXCLUSIVE范围不能包含
  零长度
              SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度


**

MyDatabaseHelper.java

package com.example.user.dbprojectsqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="Gymnesium";
    private static final String TRAINEE_TABLE_NAME="Trainee";
    private static final int VERSION_NUMBER=5;

     static final String TRAINEE_ID="traineeId";
     static final String TRAINEE_NAME="traineeName";
     static final String TRAINEE_AGE="traineeAge";
     static final String TRAINEE_GENDER="traineeGender";
     static final String TRAINEE_IMAGE="traineeImage";

    private static final String CREAE_TABLE_TRAINEE="CREATE TABLE "
            +TRAINEE_TABLE_NAME+"("+TRAINEE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT," +
            ""+TRAINEE_NAME+" VARCHAR(255),"+TRAINEE_AGE+" INTEGER,"+TRAINEE_GENDER+" VARCHAR(255))";

    private static final String DROP_TABLE_TRAINEE="DROP TABLE IF EXISTS "+TRAINEE_TABLE_NAME;

    private Context context;

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION_NUMBER);
        this.context=context;
    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        try{

            Toast.makeText(context,"onCreate is called",Toast.LENGTH_SHORT).show();
            sqLiteDatabase.execSQL(CREAE_TABLE_TRAINEE);

        }catch (Exception e){
            Toast.makeText(context,"Exception :"+e,Toast.LENGTH_SHORT).show();

        }


    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        try {
            Toast.makeText(context,"onCreate is called",Toast.LENGTH_SHORT).show();
            sqLiteDatabase.execSQL(DROP_TABLE_TRAINEE);
            onCreate(sqLiteDatabase);
        }catch (Exception e){
            Toast.makeText(context,"Exception :"+e,Toast.LENGTH_SHORT).show();

        }

    }


    public long insertData(String name,String age,String gender){
        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
        ContentValues contentValues=new ContentValues();
        //contentValues.put(TRAINEE_IMAGE,traineeImg);
        contentValues.put(TRAINEE_NAME,name);
        contentValues.put(TRAINEE_AGE,age);
        contentValues.put(TRAINEE_GENDER,gender);
        long rowId=sqLiteDatabase.insert(TRAINEE_TABLE_NAME,null,contentValues);
        return rowId;
    }

    public Cursor displayAllData(){
       SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
       Cursor cursor=sqLiteDatabase.rawQuery("SELECT * FROM "+TRAINEE_TABLE_NAME,null);
       return cursor;
    }

    public Boolean updateData(String id,String name,String age,String gender){
        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
        ContentValues contentValues=new ContentValues();
        contentValues.put(TRAINEE_ID,id);
        contentValues.put(TRAINEE_NAME,name);
        contentValues.put(TRAINEE_AGE,age);
        contentValues.put(TRAINEE_GENDER,gender);
        sqLiteDatabase.update(TRAINEE_TABLE_NAME,contentValues,TRAINEE_ID+" = ?",new String[]{id});
        return true;
    }

    public int deleteData(String id){
        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
        return sqLiteDatabase.delete(TRAINEE_TABLE_NAME,TRAINEE_ID+" = ?",new String[]{id});
    }
}


TraineeListActivity.java

package com.example.user.dbprojectsqlite;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class TraineeListActivity extends AppCompatActivity {
    private ListView TraineeListView;
    private MyDatabaseHelper myDatabaseHelper;

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

        TraineeListView=findViewById(R.id.traineeList);
        myDatabaseHelper=new MyDatabaseHelper(this);
        loadData();
    }

    public void loadData(){

        ArrayList<String>traineeListData=new ArrayList<>();
        Cursor cursor=myDatabaseHelper.displayAllData();
        if(cursor.getCount()==0){
            Toast.makeText(getApplicationContext(),"No data is available",Toast.LENGTH_SHORT).show();
        }else {
            while (cursor.moveToNext()){
                traineeListData.add("ID :"+cursor.getString(0)+" \n "+"Name :"+cursor.getString(1)+" \n "+"Age :"+cursor.getString(2)+" \n "+"Gender :"+cursor.getString(3));
            }
        }
        ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.trainee_item,R.id.traineeTextView,traineeListData);
        TraineeListView.setAdapter(adapter);

        TraineeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int position, long l) {
                //String SelectedItem=adapterView.getItemAtPosition(i).toString();
                //Toast.makeText(TraineeListActivity.this,"Selected item: "+SelectedItem,Toast.LENGTH_SHORT).show();
                CharSequence[] items={"update","delete"};
                AlertDialog.Builder dialog=new AlertDialog.Builder(TraineeListActivity.this);
                dialog.setTitle("Choose an action");
                dialog.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if(i==0){
                            Cursor c=myDatabaseHelper.displayAllData();
                            ArrayList<Integer>arrId=new ArrayList<>();
                            while ((c.moveToNext())){
                                arrId.add(c.getInt(0));
                            }
                            showDialogUpdate(TraineeListActivity.this,arrId.get(position));
                        }
                        if(i==1){
                            Cursor c=myDatabaseHelper.displayAllData();
                            ArrayList<Integer>arrId=new ArrayList<Integer>();
                            while ((c.moveToNext())){
                                arrId.add(c.getInt(0));
                            }
                            showDialogDelete(arrId.get(position));

                        }
                    }
                });
                dialog.show();
            }
        });

    }

    private void showDialogDelete(final int idRecord) {
        final AlertDialog.Builder dialogDelete=new AlertDialog.Builder(TraineeListActivity.this);
        dialogDelete.setTitle("Warning!!");
        dialogDelete.setMessage("Are you sure to delete?");
       // final EditText idText=findViewById(R.id.idET);
        dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                try {
                    myDatabaseHelper.deleteData(MyDatabaseHelper.TRAINEE_ID);
                    Toast.makeText(TraineeListActivity.this,"Deleted data",Toast.LENGTH_SHORT).show();


                }catch (Exception e){
                    Log.e("error",e.getMessage());

                }

            }
        });
        dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        dialogDelete.show();
    }

    private void showDialogUpdate(Activity activity, final int position){
        final Dialog dialog=new Dialog(activity);
        dialog.setContentView(R.layout.trainee_update);
        dialog.setTitle("Update");
        final EditText idText=dialog.findViewById(R.id.idET);

        final EditText nameText=dialog.findViewById(R.id.nameET);
        final EditText ageText=dialog.findViewById(R.id.ageET);
        final EditText genText=dialog.findViewById(R.id.genderET);
        Button updateBT=dialog.findViewById(R.id.updateBtn);

        int width=(int)(activity.getResources().getDisplayMetrics().widthPixels*0.95);
        int height=(int)(activity.getResources().getDisplayMetrics().heightPixels*0.7);
        dialog.getWindow().setLayout(width,height);
        dialog.show();

        updateBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    myDatabaseHelper.updateData(
                            idText.getText().toString().trim(),
                            nameText.getText().toString().trim(),
                            ageText.getText().toString().trim(),
                            genText.getText().toString().trim()
                    );
                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(),"Update Successfully",Toast.LENGTH_SHORT).show();

                }catch (Exception e){
                    Log.e("Update error",e.getMessage());
                }
                myDatabaseHelper.updateData(MyDatabaseHelper.TRAINEE_ID,MyDatabaseHelper.TRAINEE_NAME,MyDatabaseHelper.TRAINEE_AGE,MyDatabaseHelper.TRAINEE_GENDER);


            }
        });
    }

   /* private void updateTraineeList() {
        Cursor cursor=myDatabaseHelper.displayAllData();
        TraineeListView.clear();
        while (cursor.moveToNext()){
            int id=cursor.getInt(0);
            String name=cursor.getString(1);
            String age=cursor.getString(2);
            String phone=cursor.getString(3);

        }
    }*/

}

最佳答案

尝试此操作,您传递idRecord从表而不是My DatabaseHelper.TRAINEE ID删除数据

  private void showDialogDelete(final int idRecord) {
    final AlertDialog.Builder dialogDelete=new AlertDialog.Builder(TraineeListActivity.this);
    dialogDelete.setTitle("Warning!!");
    dialogDelete.setMessage("Are you sure to delete?");
   // final EditText idText=findViewById(R.id.idET);
    dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            try {
                myDatabaseHelper.deleteData(idRecord);
                Toast.makeText(TraineeListActivity.this,"Deleted data",Toast.LENGTH_SHORT).show();


            }catch (Exception e){
                Log.e("error",e.getMessage());

            }

        }
    });
    dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });
    dialogDelete.show();
}

10-06 09:35