简体   繁体   English

Android应用程序不断崩溃,严重异常

[英]Android Application keeps on crashing, Fatal Exception Main

I am making a note taking application where I make notes it gets stored in a Database and I can edit and delete it so, I was just about to go on with my edit and delete adventure I thought I would run the app and see if its okay and it has just crashed. 我正在做一个笔记应用程序,将笔记存储在Database ,我可以对其进行编辑和删除,因此,我将继续进行编辑和删除冒险,我想我可以运行该应用程序,看看它是否可以运行好吧,它刚刚崩溃了。

Database Handler 数据库处理程序

  package com.example.quicknotetaker;

  import java.util.ArrayList;

  import android.content.ContentValues;
  import android.content.Context;
  import android.database.Cursor;
  import android.database.sqlite.SQLiteDatabase;
  import android.database.sqlite.SQLiteOpenHelper;
  import android.util.Log;

 public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "Qdatabase";

// Contacts table name
private static final String DATABASE_TABLE = "qtable";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_NOTE = "note";
private final ArrayList<Editablegetset> titlenoteslist = new ArrayList<Editablegetset>();

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DATABASE_TABLE = "CREATE TABLE " + DATABASE_TABLE + "("
    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
    + KEY_NOTE + " TEXT,)";
db.execSQL(CREATE_DATABASE_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

// Create tables again
onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
public void Add_titlenotes(Editablegetset editablegetset) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, editablegetset.getTitle()); // Contact Name
values.put(KEY_NOTE, editablegetset.getNote()); // Contact Phone

// Inserting Row
db.insert(DATABASE_TABLE, null, values);
db.close(); // Closing database connection
}

// Getting single data
Editablegetset Get_Set(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(DATABASE_TABLE, new String[] { KEY_ID,
    KEY_TITLE, KEY_NOTE}, KEY_ID + "=?",
    new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
    cursor.moveToFirst();

Editablegetset editablegetset = new Editablegetset(Integer.parseInt(cursor.getString(0)),
    cursor.getString(1), cursor.getString(2));
// return contact
cursor.close();
db.close();

return editablegetset;
}

// Getting All Contacts
public ArrayList<Editablegetset> Get_Set() {
try {
    titlenoteslist.clear();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + DATABASE_TABLE;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
    do {
        Editablegetset editablegetset = new Editablegetset();
        editablegetset.setID(Integer.parseInt(cursor.getString(0)));
        editablegetset.setTitle(cursor.getString(1));
        editablegetset.setNote(cursor.getString(2));

        // Adding to list
        titlenoteslist.add(editablegetset);
    } while (cursor.moveToNext());
    }

    // return list
    cursor.close();
    db.close();
    return titlenoteslist;
} catch (Exception e) {
    // TODO: handle exception
    Log.e("all title and notes", "" + e);
}

return titlenoteslist;
}

// Updating individual notes
public int Update_Contact(Editablegetset editablegetset) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_TITLE, editablegetset.getTitle());
values.put(KEY_NOTE, editablegetset.getNote());


// updating row
return db.update(DATABASE_TABLE, values, KEY_ID + " = ?",
    new String[] { String.valueOf(editablegetset.getID()) });
}

// Deleting single notes
public void Delete_Contact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DATABASE_TABLE, KEY_ID + " = ?",
    new String[] { String.valueOf(id) });
db.close();
}

// Getting notes Count
public int totalnotes() {
String countQuery = "SELECT  * FROM " + DATABASE_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

}

This is my main activity 这是我的主要活动

package com.example.quicknotetaker;

import android.os.Bundle;
import android.app.Activity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Mainnote extends Activity   {

DatabaseHandler db = new DatabaseHandler(this);

EditText edtitle, enotes;
Button ab;
int noteid;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainnote);


    edtitle = (EditText) findViewById(R.id.title);
    enotes = (EditText)  findViewById(R.id.notes);

    ab = (Button)findViewById(R.id.addnote);

    ab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Editablegetset ed = db.Get_Set(noteid);
            edtitle.setText(ed.getTitle());
            enotes.setText(ed.getNote());


            Toast.makeText(getApplicationContext(), 
                    "Note has been Added", Toast.LENGTH_LONG).show();

            Clear_Text();


        }

        public void Clear_Text() {
            // TODO Auto-generated method stub

            edtitle.getText().clear();
            enotes.getText().clear();


        }
    });
}
}

This is my get set methods 这是我的设置方法

package com.example.quicknotetaker;

public class Editablegetset {

// private variables
public int _id;
public String _title;
public String _note;


public Editablegetset() {
}

// constructor
public Editablegetset(int id, String title, String note) {
this._id = id;
this._title = title;
this._note = note;


}

// constructor
public Editablegetset(String title, String note) {
this._title = title;
this._note = note;

}

// getting ID
public int getID() {
return this._id;
}

// setting id
public void setID(int id) {
this._id = id;
}

// getting title
public String getTitle() {
return this._title;
}

// setting title
public void setTitle(String title) {
this._title = title;
}

// getting note
public String getNote() {
return this._note;
}

// setting note
public void setNote(String note) {
this._note = note;
}



}

Logcat logcat的

03-20 07:48:37.458: D/AndroidRuntime(23951): Shutting down VM
03-20 07:48:37.458: W/dalvikvm(23951): threadid=1: thread exiting with uncaught       exception (group=0x4170ad40)  
03-20 07:48:37.460: E/AndroidRuntime(23951): FATAL EXCEPTION: main 
03-20 07:48:37.460: E/AndroidRuntime(23951): Process: com.example.quicknotetaker, PID: 23951 
03-20 07:48:37.460: E/AndroidRuntime(23951): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quicknotetaker/com.example.quicknotetaker.Mainnote}: java.lang.NullPointerException 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.ActivityThread.access$800(ActivityThread.java:139) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.os.Handler.dispatchMessage(Handler.java:102) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.os.Looper.loop(Looper.java:136)
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.ActivityThread.main(ActivityThread.java:5102) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at java.lang.reflect.Method.invokeNative(Native Method) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at java.lang.reflect.Method.invoke(Method.java:515) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at dalvik.system.NativeStart.main(Native Method) 
03-20 07:48:37.460: E/AndroidRuntime(23951): Caused by: java.lang.NullPointerException 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at com.example.quicknotetaker.Mainnote.onCreate(Mainnote.java:30) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.Activity.performCreate(Activity.java:5248) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173) 
03-20 07:48:37.460: E/AndroidRuntime(23951):    ... 11 more

Please i really need help i have spent a lot of time on this thanks 请我真的需要帮助,我已经花了很多时间在此感谢

From the logcat: 从logcat:

Caused by: java.lang.NullPointerException
  at com.example.quicknotetaker.Mainnote.onCreate(Mainnote.java:30)

Your onCreate() can really NPE only in here: 您的onCreate()实际上只能在这里进行NPE:

ab.setOnClickListener(...);

when ab is null. ab为null时。 You initialize it with findViewById() which returns null in case the view was not found. 您可以使用findViewById()初始化它,如果找不到该视图,则返回null

Make sure your activity_mainnote layout really has a Button with id addnote . 确保您的activity_mainnote布局确实具有ID为addnoteButton

The Value of "noteid" is 0, and you may not have a KEY_ID with value 0. The db query may returning no rows. “ noteid”的值是0,并且您可能没有值为0的KEY_ID。db查询可能不返回任何行。 So Editablegetset class is set null. 因此将Editablegetset类设置为null。 so when u call edtitle.setText(ed.getTitle()); 所以当你调用edtitle.setText(ed.getTitle()); you will get NullPointerException because ed is null. 您将获得NullPointerException,因为ed为null。 Add a null check before getting values from Editablegetset class like below code 在从Editablegetset类获取值之前添加空检查,如下面的代码

  if(ed!=null)
  {
  edtitle.setText(ed.getTitle());
  enotes.setText(ed.getNote());         
  }

Also set "noteid" correctly to match your db values. 还要正确设置“ noteid”以匹配您的数据库值。

Base on my view in your code. 根据我对您代码的看法。 You get the null pointer in your int variable noteid in your main. 您可以在main的int变量noteid中获得空指针。

try to use this 尝试使用这个

int noteid = 0;

hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM