Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java CursorIndexOutOfBoundsException错误-数据库android_Java_Android_Database_Sqlite - Fatal编程技术网

Java CursorIndexOutOfBoundsException错误-数据库android

Java CursorIndexOutOfBoundsException错误-数据库android,java,android,database,sqlite,Java,Android,Database,Sqlite,我知道这个问题反复出现,但没有一个解决方案对我有效 我是sql数据库新手。我正在练习来自网站教程点的示例。例子 我正在获取.CursorIndexOutOfBoundsException:请求索引0,从数据库中删除名称时出现大小为0的错误。因此,如果我在数据库中添加4个名称并开始删除第一个名称,它将被删除,然后单击第二个名称,它将显示此错误(.CursorIndexOutOfBoundsException:请求索引0,大小为0)。然后,如果我点击第三个名字,我可以删除这个名字,但第四个名字也会出

我知道这个问题反复出现,但没有一个解决方案对我有效

我是sql数据库新手。我正在练习来自网站教程点的示例。例子 我正在获取.CursorIndexOutOfBoundsException:请求索引0,从数据库中删除名称时出现大小为0的错误。因此,如果我在数据库中添加4个名称并开始删除第一个名称,它将被删除,然后单击第二个名称,它将显示此错误(.CursorIndexOutOfBoundsException:请求索引0,大小为0)。然后,如果我点击第三个名字,我可以删除这个名字,但第四个名字也会出现同样的错误。 我希望用户可以从数据库中删除任何行,或者可以删除整行

错误

分贝

public类DBHelper扩展了SQLiteOpenHelper{
公共静态最终字符串数据库\u NAME=“MyDBName.db”;
公共静态最终字符串CONTACTS\u TABLE\u NAME=“CONTACTS”;
公共静态最终字符串联系人\u COLUMN\u ID=“ID”;
公共静态最终字符串CONTACTS\u COLUMN\u NAME=“NAME”;
私有HashMap-hp;
公共DBHelper(上下文){
super(上下文,数据库名称,null,1);
}
@凌驾
public void onCreate(SQLiteDatabase db){
db.execSQL(
“创建表联系人”+
(id整数主键,名称文本)
);
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
db.execSQL(“如果存在联系人,则删除表”);
onCreate(db);
}
公共布尔值insertContact(字符串名称){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues ContentValues=新ContentValues();
contentValues.put(“name”,name);
db.insert(“contacts”,null,contentValues);
返回true;
}
公共游标getData(int-id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor res=db.rawQuery(“从联系人中选择*,其中id=“+id+”,null);
返回res;
}
公共int numberOfRows(){
SQLiteDatabase db=this.getReadableDatabase();
int numRows=(int)DatabaseUtils.queryNumEntries(db,CONTACTS\u TABLE\u NAME);
返回numRows;
}
公共布尔updateContact(整数id、字符串名称){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues ContentValues=新ContentValues();
contentValues.put(“name”,name);
update(“contacts”,contentValues,“id=?”,新字符串[]{Integer.toString(id)});
返回true;
}
公共整数删除联系人(整数id){
SQLiteDatabase db=this.getWritableDatabase();
返回db.delete(“联系人”,
“id=?”,
新字符串[]{Integer.toString(id)});
}
公共阵列列表getAllCotacts(){
ArrayList数组_list=新建ArrayList();
//hp=新HashMap();
SQLiteDatabase db=this.getReadableDatabase();
Cursor res=db.rawQuery(“从联系人中选择*”,null);
res.moveToFirst();
while(res.isAfterLast()==false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME));
res.moveToNext();
}
返回数组_列表;
}
设备详细性

public class devicedetailsActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.devicedetails_layout);
    FullScreencall();
    mydb = new DBHelper(this);
    ArrayList array_list = mydb.getAllCotacts();
    ArrayAdapter arrayAdapter=new ArrayAdapter(this,R.layout.simple_list_item_1, array_list);

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

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

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

            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });
}
public void FullScreencall() {
    if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api


        int mUIFlag = View.SYSTEM_UI_FLAG_LOW_PROFILE
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;


        getWindow().getDecorView().setSystemUiVisibility(mUIFlag);

    } else if(Build.VERSION.SDK_INT >= 19) {
        //for new api versions.
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_FULLSCREEN;

        decorView.setSystemUiVisibility(uiOptions);
    }
}

@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);
    getMenuInflater().inflate(R.menu.home, 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(),DetailsActivity.class);
            intent.putExtras(dataBundle);

            startActivity(intent);
            return true;
        case R.id.item2: dataBundle = new Bundle();
            dataBundle.putInt("id", 0);
             intent = new Intent(getApplicationContext(),MainActivity.class);
            intent.putExtras(dataBundle);

            startActivity(intent);
            return true;


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

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}
公共类devicedetailsActivity扩展了AppCompativeActivity{
公共最终静态字符串EXTRA_MESSAGE=“MESSAGE”;
私有ListView obj;
DBHelper mydb;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.devicedetails\U布局);
全屏调用();
mydb=新的DBHelper(this);
ArrayList数组_list=mydb.getAllCotacts();
ArrayAdapter ArrayAdapter=新的ArrayAdapter(这个,R.layout.simple\u list\u item\u 1,array\u list);
obj=(ListView)findViewById(R.id.listView1);
对象设置适配器(阵列适配器);
obj.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
公共视图单击(AdapterView arg0、视图arg1、整型arg2、长型arg3){
//TODO自动生成的方法存根
int id_To_Search=arg2+1;
Bundle-dataBundle=新Bundle();
dataBundle.putInt(“id”,id到搜索);
Intent Intent=new Intent(getApplicationContext(),DetailsActivity.class);
意向。额外支出(数据绑定);
星触觉(意向);
}
});
}
公共空全屏调用(){
如果(Build.VERSION.SDK_INT>11&&Build.VERSION.SDK_INT<19){//lower api
int mUIFlag=View.SYSTEM\u UI\u FLAG\u LOW\u PROFILE
|View.SYSTEM\u UI\u FLAG\u HIDE\u导航
|View.SYSTEM\u UI\u FLAG\u全屏显示;
getWindow().getDecorView().SetSystemActivity(mUIFlag);
}else if(Build.VERSION.SDK_INT>=19){
//对于新的api版本。
View decorView=getWindow().getDecorView();
int uiOptions=View.SYSTEM\u UI\u FLAG\u HIDE\u导航
|View.SYSTEM\u UI\u FLAG\u沉浸式\u粘性
|View.SYSTEM\u UI\u FLAG\u全屏显示;
decorView.设置系统兼容性(uiOptions);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
getMenuInflater().充气(R.menu.home,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
super.onOptionsItemSelected(项目);
开关(item.getItemId()){
案例R.id.item1:Bundle-dataBundle=new Bundle();
dataBundle.putInt(“id”,0);
Intent Intent=new Intent(getApplicationContext(),DetailsActivity.class);
意向。额外支出(数据绑定);
星触觉(意向);
返回true;
案例R.id.item2:dataBundle=newbundle();
dataBundle.putInt(“id”,0);
intent=newintent(getApplicationContext(),MainActivity.class);
意向。额外支出(数据绑定);
星触觉(意向);
返回true;
违约:
返回super.onOptionsItemSelected(项目);
}
}
公共布尔onKeyDown(int-keycode,KeyEvent
public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";

private HashMap hp;

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

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "create table contacts " +
                    "(id integer primary key, name text)"
    );
}

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

public boolean insertContact(String name) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", name);

    db.insert("contacts", null, contentValues);
    return true;
}

public Cursor getData(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
    return res;
}

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

public boolean updateContact(Integer id, String name) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", name);

    db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
    return true;
}

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

public ArrayList<String> getAllCotacts() {
    ArrayList<String> array_list = new ArrayList<String>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts", null );
    res.moveToFirst();

    while(res.isAfterLast() == false){
        array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
        res.moveToNext();
    }
    return array_list;
}
public class devicedetailsActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.devicedetails_layout);
    FullScreencall();
    mydb = new DBHelper(this);
    ArrayList array_list = mydb.getAllCotacts();
    ArrayAdapter arrayAdapter=new ArrayAdapter(this,R.layout.simple_list_item_1, array_list);

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

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

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

            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });
}
public void FullScreencall() {
    if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api


        int mUIFlag = View.SYSTEM_UI_FLAG_LOW_PROFILE
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;


        getWindow().getDecorView().setSystemUiVisibility(mUIFlag);

    } else if(Build.VERSION.SDK_INT >= 19) {
        //for new api versions.
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_FULLSCREEN;

        decorView.setSystemUiVisibility(uiOptions);
    }
}

@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);
    getMenuInflater().inflate(R.menu.home, 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(),DetailsActivity.class);
            intent.putExtras(dataBundle);

            startActivity(intent);
            return true;
        case R.id.item2: dataBundle = new Bundle();
            dataBundle.putInt("id", 0);
             intent = new Intent(getApplicationContext(),MainActivity.class);
            intent.putExtras(dataBundle);

            startActivity(intent);
            return true;


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

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}
public class DetailsActivity extends AppCompatActivity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;

TextView name ;

int id_To_Update = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.details);
    FullScreencall();
    name = (TextView) findViewById(R.id.editTextName);


    mydb = new DBHelper(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;
            rs.moveToFirst();
            String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
            if (!rs.isClosed())  {
                rs.close();
            }
            Button b = (Button)findViewById(R.id.button1);
            b.setVisibility(View.INVISIBLE);

            name.setText((CharSequence)nam);
            name.setFocusable(false);
            name.setClickable(false);
        }
    }
}
public void FullScreencall() {
    if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api


        int mUIFlag = View.SYSTEM_UI_FLAG_LOW_PROFILE
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;


        getWindow().getDecorView().setSystemUiVisibility(mUIFlag);

    } else if(Build.VERSION.SDK_INT >= 19) {
        //for new api versions.
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_FULLSCREEN;

        decorView.setSystemUiVisibility(uiOptions);
    }
}

@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_contact, menu);
        } else{
            getMenuInflater().inflate(R.menu.back, 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);
            name.setEnabled(true);
            name.setFocusableInTouchMode(true);
            name.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(),devicedetailsActivity.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;
        case R.id.back:
            Intent intent = new Intent(getApplicationContext(),devicedetailsActivity.class);
            startActivity(intent);
            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.updateContact(id_To_Update,name.getText().toString()
                    )){
                Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),devicedetailsActivity.class);
                startActivity(intent);
            } else{
                Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
            }
        } else{
            if(mydb.insertContact(name.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(),devicedetailsActivity.class);
            startActivity(intent);
        }
    }
}
name = (TextView) findViewById(R.id.editTextName);
    mydb = new DBHelper(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);
            //Check if cursor has value
            if(rs != null && rs.getCount() > 0){  
              id_To_Update = Value;
              rs.moveToFirst();
              String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
              if (!rs.isClosed())  {
                  rs.close();
              } 
              Button b = (Button)findViewById(R.id.button1);
              b.setVisibility(View.INVISIBLE);

              name.setText((CharSequence)nam);
              name.setFocusable(false);
              name.setClickable(false);
          }
        }
    }
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);
        if(rs.moveToFirst()) {
            id_To_Update = Value;
            rs.moveToFirst();
            String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
            Button b = (Button)findViewById(R.id.button1);
            b.setVisibility(View.INVISIBLE);

            name.setText((CharSequence)nam);
            name.setFocusable(false);
            name.setClickable(false);
        }
        if (!rs.isClosed())  {
            rs.close();
        }
    }
}