我有以下带有SupervisorActivity.java和activity_supervisor.xml文件的代码。表单按预期显示,但是当我单击按钮时,会出现以下错误。我是一个相当新的人,试图通过遍历代码来找到问题,尽管我无法遍历,因为点击按钮甚至不会进入SaveSupervisor代码。
DBHandler.java
package com.smith.john.learnerlog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by d402966 on 24/03/2016.
*/
public class DBHandler extends SQLiteOpenHelper {
// Static Variables
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "LearnerLog";
private static final String TABLE_SUPERVISOR = "supervisors";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_PHONE = "phone";
private static final String KEY_LICENCE_NO = "licence_no";
private static final String KEY_CREATE_DATE = "create_date";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/*Override this function to create a new table*/
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_SUPERVISOR_TABLE = "CREATE TABLE " + TABLE_SUPERVISOR + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT,"
+ KEY_PHONE + " TEXT,"
+ KEY_LICENCE_NO + " TEXT,"
+ KEY_CREATE_DATE + " TEXT" + ")";
db.execSQL(CREATE_SUPERVISOR_TABLE);
}
/*Override this function to upgrade your table design / structure*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop the old table if exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SUPERVISOR);
// Create tables again
onCreate(db);
}
/*addSupervisor() will add a new Supervisor to database*/
public long addSupervisor(Supervisor supervisor) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, supervisor.getName());
values.put(KEY_EMAIL, supervisor.getEmail());
values.put(KEY_PHONE, supervisor.getPhone());
values.put(KEY_LICENCE_NO, supervisor.getLicenceNo());
values.put(KEY_CREATE_DATE, supervisor.getCreateDate());
return db.insert(TABLE_SUPERVISOR, null, values); //Insert query to store the record in the database
}
/*getSupervisor() will return he supervisor's object if id matches*/
public Supervisor getSupervisor(int supervisor_id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SUPERVISOR, new String[]{KEY_ID,
KEY_NAME, KEY_EMAIL, KEY_PHONE, KEY_LICENCE_NO, KEY_CREATE_DATE}, KEY_ID + "=?",
new String[]{String.valueOf(supervisor_id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Supervisor supervisor = new Supervisor(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return supervisor;
}
/*getAllSupervisors() will return the list of all supervisors*/
public ArrayList<Supervisor> getAllSupervisors() {
ArrayList<Supervisor> supervisorsList = new ArrayList<Supervisor>();
String selectQuery = "SELECT * FROM " + TABLE_SUPERVISOR;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String cursor_name = cursor.getString(cursor.getColumnIndex(KEY_NAME));
String cursor_email = cursor.getString(cursor.getColumnIndex(KEY_EMAIL));
String cursor_phone = cursor.getString(cursor.getColumnIndex(KEY_PHONE));
String cursor_licence_no = cursor.getString(cursor.getColumnIndex(KEY_LICENCE_NO));
String cursor_create_date = cursor.getString(cursor.getColumnIndex(KEY_CREATE_DATE));
Supervisor supervisor = new Supervisor(cursor_name, cursor_email, cursor_phone, cursor_licence_no, cursor_create_date);
supervisorsList.add(supervisor);
} while (cursor.moveToNext());
}
return supervisorsList;
}
/*getSupervisorsCount() will give the total number of records in the table*/
public int getSupervisorsCount() {
String countQuery = "SELECT * FROM " + TABLE_SUPERVISOR;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
/*updateSupervisor() will be used to update the existing supervisor record*/
public int updateSupervisor(Supervisor supervisor) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, supervisor.getName());
values.put(KEY_EMAIL, supervisor.getEmail());
values.put(KEY_PHONE, supervisor.getPhone());
values.put(KEY_LICENCE_NO, supervisor.getLicenceNo());
values.put(KEY_CREATE_DATE, supervisor.getCreateDate());
// updating record
return db.update(TABLE_SUPERVISOR, values, KEY_ID + " = ?", // update query to make changes to the existing record
new String[]{String.valueOf(supervisor.getId())});
}
/*deleteContact() to delete the record from the table*/
public void deleteContact(Supervisor supervisor) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_SUPERVISOR, KEY_ID + " = ?",
new String[]{String.valueOf(supervisor.getId())});
db.close();
}
public void deleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete FROM " + TABLE_SUPERVISOR);
db.close();
}
}
错误消息
03-30 23:47:57.079 2140-2140/com.smith.john.learnerlog E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.smith.john.learnerlog, PID: 2140
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:275)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.smith.john.learnerlog.DBHandler.getSupervisor(DBHandler.java:79)
at com.smith.john.learnerlog.SupervisorActivity.SaveSupervisor(SupervisorActivity.java:174)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-30 23:48:01.647 2140-2146/com.smith.john.learnerlog W/art: Suspending all threads took: 5.223ms
监督者活动.java
package com.smith.john.learnerlog;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by d402966 on 24/03/2016.
*/
public class SupervisorActivity extends AppCompatActivity {
int from_Where_I_Am_Coming = 0;
public DBHandler mydb;
Supervisor supervisor;
Cursor rs;
TextView name;
TextView email;
TextView phone;
TextView licence_no;
int id_To_Update = 0;
int id_value;
String name_value;
String email_value;
String licence_no_value;
String phone_value;
String create_date_value;
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private SupervisorsAdapter adapter;
private DBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_supervisor);
name = (TextView) findViewById(R.id.editTextName);
email = (TextView) findViewById(R.id.editTextEmail);
phone = (TextView) findViewById(R.id.editTextPhone);
licence_no = (TextView) findViewById(R.id.editTextLicenceNo);
mydb = new DBHandler(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.
supervisor = mydb.getSupervisor(Value);
id_To_Update = Value;
rs.moveToFirst();
name_value = rs.getString(rs.getColumnIndex(supervisor.getName()));
email_value = rs.getString(rs.getColumnIndex(supervisor.getEmail()));
phone_value = rs.getString(rs.getColumnIndex(supervisor.getPhone()));
licence_no_value = rs.getString(rs.getColumnIndex(supervisor.getLicenceNo()));
if (!rs.isClosed()) {
rs.close();
}
name.setText((CharSequence) name_value);
name.setFocusable(true);
name.setClickable(true);
email.setText((CharSequence) email_value);
email.setFocusable(true);
email.setClickable(true);
phone.setText((CharSequence) phone_value);
phone.setFocusable(true);
phone.setClickable(true);
licence_no.setText((CharSequence) licence_no_value);
licence_no.setFocusable(true);
licence_no.setClickable(true);
}
}
}
@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_supervisor, menu);
} else {
getMenuInflater().inflate(R.menu.menu_main, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.Edit_Supervisor:
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
licence_no.setEnabled(true);
licence_no.setFocusableInTouchMode(true);
licence_no.setClickable(true);
return true;
case R.id.Delete_Supervisor:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
/* builder.setMessage(R.string.deleteSupervisor)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteSupervisor(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);
}
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
public void SaveSupervisor(View view) {
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
SupervisorsAdapter adapter;
DBHandler dbHandler = new DBHandler(this);
Supervisor supervisor;
Bundle extras = getIntent().getExtras();
int Value = extras.getInt("id");
if (extras != null) {
supervisor = mydb.getSupervisor(Value);
create_date_value = rs.getString(rs.getColumnIndex(supervisor.getCreateDate()));
if (create_date_value.matches("")) {
create_date_value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
if (Value > 0) {
if (mydb.updateSupervisor(supervisor) == 1) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else {
ContentValues values = new ContentValues();
supervisor.setName(name.getText().toString());
supervisor.setEmail(email.getText().toString());
supervisor.setPhone(phone.getText().toString());
supervisor.setLicenceNo(licence_no.getText().toString());
supervisor.setCreateDate(create_date_value.toString());
if (mydb.addSupervisor(supervisor) == 1) {
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
activity_supervisor.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.aksu.ozgur.learnerlog.SupervisorActivity" >
<android.support.design.widget.TextInputLayout
android:id="@+id/Name"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/editTextName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/name" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/Email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/Name">
<EditText
android:id="@+id/editTextEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:inputType="textWebEmailAddress"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/Phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/Email">
<EditText
android:id="@+id/editTextPhone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/phone"
android:inputType="number"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/LicenceNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/Phone">
<EditText
android:id="@+id/editTextLicenceNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/licence_no"
android:inputType="time"/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/SaveSupervisorButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="SaveSupervisor"
android:text="@string/save_supervisor"
android:layout_below="@+id/LicenceNo"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
堆栈跟踪指向一个CursorIndexOutOfBounds
异常,在这种情况下,这意味着getSupervisor()
方法中的Cursor
为空。你可以通过对你的方法进行以下调整来测试这一点:
/*getSupervisor() will return he supervisor's object if id matches*/
public Supervisor getSupervisor(int supervisor_id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SUPERVISOR, new String[]{KEY_ID,
KEY_NAME, KEY_EMAIL, KEY_PHONE, KEY_LICENCE_NO, KEY_CREATE_DATE}, KEY_ID + "=?",
new String[]{String.valueOf(supervisor_id)}, null, null, null, null);
//if (cursor != null) <--Replace this. The query() method never returns a null Cursor
if (!cursor.moveToFirst()) {
//Cursor is empty...
throw new CursorIndexOutOfBoundsException("Cursor should not be empty");
}
Supervisor supervisor = new Supervisor(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return supervisor;
}
如果你想让supervisor_id
在你的数据库中没有条目是有效的,那么你可以用空白的Supervisor
:代替throw new CursorIndexOutOfBoundsException()
if (!cursor.moveToFirst()) {
return new Supervisor("","","","","");
}
否则,问题要么出现在传递给方法的supverisor_id
中,要么出现在query()
中