我有saveinSQL类(扩展SQLiteOpenHelper),我在其中定义了我的数据库访问方法。我在Create类中创建了一个数据库。我想在Home类中访问数据库。我能够在我的Home类中获取数据库中的行数,这意味着我可以访问数据库。但是我无法在游标的帮助下访问SQLite表的特定单元格中的数据条目。我的 getHeader 功能似乎有问题。有人请帮帮我。我正在处理的部分是 Home Class 的 onCreate 函数。我得到的错误是 android.database.CursorIndexOutOfBoundsException:请求索引1,大小为1
这是我的家庭班。我在 temp.header = mydb.getHeader(1);
上收到错误package com.example.yashubale.mypetitions;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ArrayList<Petition> ap;
saveinSQL mydb;
String a,b,c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Dashboard");
ap = new ArrayList<Petition>();
mydb = saveinSQL.getInstance(this);
int numPetitions = mydb.numberOfRows();
Toast.makeText(this , Integer.toString(numPetitions) , Toast.LENGTH_LONG).show();
Petition temp = new Petition();
// temp.header = mydb.getHeader(2);
temp.header = mydb.getHeader(1);
// temp.header = mydb.getHeader(3);
// for(int i= 1 ; i <= numPetitions ; i++){
//
// // temp.header = mydb.getHeader(i);
// temp.description = mydb.getDescription(i);
// temp.people = mydb.getPeople(i);
// //ap.add(temp);
// }
// ListView lv = (ListView) findViewById(R.id.listpetitions);
// customeAdapter ca = new customeAdapter(this,ap);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_create) {
startCreate(this);
} else if (id == R.id.nav_mypetitions) {
} else if (id == R.id.nav_dashboard) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void startCreate(Context c){
Intent intent = new Intent(c , Create.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
这是我的 saveinSQL类
package com.example.yashubale.mypetitions;
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;
public class saveinSQL extends SQLiteOpenHelper {
String header = new String();
String descrip = new String();
String people = new String();
Cursor res;
private static saveinSQL mInstance = null;
private Context myctx;
private static final int DATABASE_VERSION = 2;
private static final String PETITIONS_TABLE_NAME = "Petitions";
private static final String DATABASE_NAME = "myDB.db";
public static final String PETITIONS_COLUMN_ID = "id";
public static final String PETITIONS_COLUMN_HEADING = "heading";
public static final String PETITIONS_COLUMN_DESCRIPTION = "description";
public static final String PETITIONS_COLUMN_PEOPLE = "people";
public saveinSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myctx = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"create table Petitions" +
"(id integer primary key, heading text, description text, people text)"
);
}
public static synchronized saveinSQL getInstance(Context context) {
if (mInstance == null) {
mInstance = new saveinSQL(context.getApplicationContext());
}
return mInstance;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Petitions");
onCreate(db);
}
public boolean insertPetition (String heading, String description,String people)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("heading", heading);
contentValues.put("description", description);
contentValues.put("people", people);
db.insert("Petitions", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
res = db.rawQuery( "select * from Petitions where id="+id+"", null );
return res;
}
public String getHeader(int id){
SQLiteDatabase db = this.getReadableDatabase();
res = db.rawQuery("select * from Petitions where id=" + id + "", null);
res.moveToPosition(id);
// for(int i = 1; i < id; i++){
// res.moveToNext();
// }
header = res.getString(res.getColumnIndex(saveinSQL.PETITIONS_COLUMN_HEADING));
res.moveToFirst();
return header;
}
public String getDescription(int id){
SQLiteDatabase db = this.getReadableDatabase();
res = db.rawQuery("select * from Petitions where id=" + id + "", null);
res.moveToFirst();
for(int i = 1; i < id; i++){
res.moveToNext();
}
descrip = res.getString(res.getColumnIndex(saveinSQL.PETITIONS_COLUMN_DESCRIPTION));
return descrip;
}
public String getPeople(int id){
SQLiteDatabase db = this.getReadableDatabase();
res = db.rawQuery("select * from Petitions where id=" + id + "", null);
res.moveToFirst();
for(int i = 1; i < id; i++){
res.moveToNext();
}
people = res.getString(res.getColumnIndex(saveinSQL.PETITIONS_COLUMN_PEOPLE));
return people;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, PETITIONS_TABLE_NAME);
return numRows;
}
public boolean updatePetitiont (Integer id, String heading, String description, String people)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("heading", heading);
contentValues.put("description", description);
contentValues.put("people", people);
db.update("Petitions", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deletePetition (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("Petitions",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllPetitions()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from Petitions", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(PETITIONS_COLUMN_HEADING)));
res.moveToNext();
}
return array_list;
}
}
这是我的创建班级
public class Create extends AppCompatActivity {
private EditText mHeadingView;
private EditText mDescriptionView;
saveinSQL mydb = new saveinSQL(this);
EditText headingGet;
EditText descriptionGet;
EditText peopleGet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button mEmailSignInButton = (Button) findViewById(R.id.createpetition);
mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createPetition();
}
});
}
public void createPetition(){
boolean cancel = false;
View focusView = null;
mHeadingView = (EditText)findViewById(R.id.heading);
mDescriptionView = (EditText)findViewById(R.id.description);
mHeadingView.setError(null);
mDescriptionView.setError(null);
String heading = mHeadingView.getText().toString();
String description = mDescriptionView.getText().toString();
if(heading.isEmpty()) {
mHeadingView.setError("Heading is too short");
focusView = mHeadingView;
cancel = true;
}
if(description.isEmpty()){
mDescriptionView.setError("Description is too short");
focusView = mDescriptionView;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
}
else{
headingGet =(EditText)findViewById(R.id.heading);
descriptionGet =(EditText)findViewById(R.id.description);
peopleGet =(EditText)findViewById(R.id.members);
// for(int i = 1; i < 5 ; i++){
// mydb.deletePetition(i);
// }
if(mydb.insertPetition(headingGet.getText().toString(), descriptionGet.getText().toString(), peopleGet.getText().toString())){
Toast.makeText(getApplicationContext(), "Petition Added" , Toast.LENGTH_LONG).show();
finish();
}
}
}
}
答案 0 :(得分:0)
public String getHeader(int id){
SQLiteDatabase db = this.getReadableDatabase();
String header = "";
res = db.rawQuery("select * from Petitions where id=" + id + "", null);
if (res.moveToFirst()) {
header = res.getString(res.getColumnIndex(saveinSQL.PETITIONS_COLUMN_HEADING));
}
return header;
}
答案 1 :(得分:0)
res = db.rawQuery("select * from Petitions where id=" + id + "", null);
res.moveToPosition(id);
查询只返回一行(因为WHERE过滤器),所以你不能移动到除0之外的任何位置。
将moveToPosition
替换为moveToFirst
。
并且不需要返回任何其他列,并且您还应该在没有找到具有该ID的行时处理该情况:
res = db.rawQuery("select "+saveinSQL.PETITIONS_COLUMN_HEADING+
" from Petitions"+
" where id=" + id + "", null);
if (res.moveToFirst())
header = res.getString(0);
else
header = "";
请注意,有helper function可以更轻松地从返回单行的查询中获取值:
header = DatabaseUtils.stringForQuery(db,
"select "+saveinSQL.PETITIONS_COLUMN_HEADING+
" from Petitions"+
" where id=" + id + "", null);
答案 2 :(得分:-1)
&#34;创建表格请愿书&#34; + &#34;(id整数主键,标题文本,描述文本,人物文本)&#34;
&#34;创建表格请求(id整数主键自动增量,标题文本,描述文本,人物文本)&#34;