Android-单击按钮时立即出错,而不输入onClick活动

Android-单击按钮时立即出错,而不输入onClick活动,android,button,invocationtargetexception,Android,Button,Invocationtargetexception,我有以下带有SupervisorActivity.java和activity_supervisor.xml文件的代码。表单按预期显示,但是当我单击按钮时,出现以下错误。我是一个新手,尝试通过单步查看代码来发现问题,但我无法单步查看,因为单击按钮甚至无法进入SaveSupervisor代码 DBHandler.java package com.smith.john.learnerlog; import android.content.ContentValues; import android.

我有以下带有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();
    }
}
SupervisorActivity.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>

堆栈跟踪指向一个
游标IndexOutOfBounds
异常,在这种情况下,这意味着
getSupervisor()方法中的
游标
为空。您可以通过对方法进行以下调整来对此进行测试:

/*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;
    }

否则,问题要么在于传递给该方法的
supverisor\u id
中,要么在于您的
查询()

中,是否可以将
getSupervisor()
方法的代码添加到
DBHandler
类中?错误日志表明您试图从空的
游标中提取数据。我已使用DBHandler.java完整更新了提交。这解决了游标索引越界问题,现在我可以停止处理并逐步完成代码。还有其他问题,例如在未定义列值的条目上调用getColumnIndex。如果我继续有问题,我会解决这些问题并发回。感谢你的帮助!!!
/*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;
    }
if (!cursor.moveToFirst()) {
    return new Supervisor("","","","","");
}