2016-03-30 23 views
-1

Ich habe den folgenden Code mit SupervisorActivity.java und activity_supervisor.xml Dateien. Das Formular wird wie erwartet angezeigt. Wenn ich jedoch auf die Schaltfläche klicke, erhalte ich den folgenden Fehler. Ich bin ziemlich neu und habe versucht, das Problem zu finden, indem ich durch den Code gehe, obwohl ich nicht in der Lage bin, durch zu gehen, weil das Klicken auf den Knopf nicht sogar zum SaveSupervisor Code geht.Android - Klicken Sie auf einen Button Fehler sofort ohne die onClick-Aktivität

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(); 
    } 
} 

Fehlermeldung

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 

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> 
+2

können Sie den Code für Ihre 'getSupervisor add()' Methode in Ihrer 'DBHandler' Klasse bitte? Das Fehlerprotokoll schlägt vor, dass Sie versuchen, Daten aus einem "Cursor" zu entnehmen, der leer ist. – PPartisan

+0

Ich habe die Einreichung mit dem DBHandler.java vollständig aktualisiert. – oaksu

Antwort

0

Der Stack-Trace zeigt auf eine CursorIndexOutOfBounds Ausnahme, was in diesem Fall bedeutet, dass die Cursor innerhalb Ihrer getSupervisor() Methode leer ist. Sie können, indem sie die folgende Anpassung an Ihre Methode für diesen Test:

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

Wenn Sie es haben wollen, so dass die supervisor_id kein Eintrag in der Datenbank bereitgestellt, die gültig ist, dann können Sie die throw new CursorIndexOutOfBoundsException() mit einem ersetzen Supervisor blank:

if (!cursor.moveToFirst()) { 
    return new Supervisor("","","","",""); 
} 

Andernfalls wird das Problem liegt entweder in der supverisor_id Sie auf das Verfahren vorbei sind oder in Ihrem query()

+1

Das ist der Cursor-Index aus Bounds Problem gelöst und ich bin jetzt in der Lage, die Verarbeitung zu stoppen und durch den Code zu gehen. Es gibt weitere Probleme, z. B. dass getColumnIndex für einen Eintrag aufgerufen wird, bei dem der Spaltenwert nicht definiert ist. Ich werde diese durcharbeiten und zurückschreiben, wenn ich weiterhin Probleme habe. Schätzen Sie Ihre Hilfe !!! – oaksu