我一直在尝试建立一个像以前一样的简单数据库。但是,只要我将onClick监听器添加到我拥有的2个按钮,这个单页面应用就会崩溃。这是一个非常简单的应用程序,可以将玩家姓名和分数添加到数据库中,然后按名称查找分数。之前我在fragment_main.xml中使用了我的布局,但是我将其更改为activity_main.xml。这是我的MainActivity,数据库适配器,Layout-xml和LogCat的代码。
public class MainActivity extends ActionBarActivity {
Button add, find;
EditText name, score;
private DBAdapter dbHelper;
private boolean isUpdate = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
dbHelper = new DBAdapter(this);
name = (EditText) findViewById(R.id.editText1);
score = (EditText) findViewById(R.id.editText2);
add = (Button) findViewById(R.id.button1);
find = (Button) findViewById(R.id.button2);
}
public void newPlayer(View view){
dbHelper = new DBAdapter(this);
String pName = name.getText().toString();
int pScore = Integer.parseInt(score.getText().toString());
Player player = new Player(pName, pScore);
dbHelper.addPlayer(player);
name.setText("D");
score.setText("1");
}
public void findPlayer(){
dbHelper = new DBAdapter(this);
Player player = dbHelper.getPlayerByName(name.getText().toString());
if (player != null){
score.setText(player.getScore());
}
else {
Toast.makeText(this, "Couldn't find in database", Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container,
false);
return rootView;
}
}
}
和 DBAdapter处理程序是:
package com.example.anotherdatabase;
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;
import android.widget.Toast;
public class DBAdapter extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "ItemDB.db";
Context context;
private static final String TABLE_ITEM = "Players";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_SCORE = "score";
private static final String[] COLUMNS = {KEY_ID,KEY_NAME,KEY_SCORE};
public DBAdapter(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEM_TABLE = "CREATE TABLE "+ TABLE_ITEM +"( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT, "+
"score INTEGER )";
db.execSQL(CREATE_ITEM_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_ITEM);
// create fresh Items table
this.onCreate(db);
}
public void addPlayer(Player player){
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_SCORE, player.getScore());
// insert
long insert = db.insert(TABLE_ITEM, null, values);
if(insert == -1){
Toast.makeText(context, "Failed to save to the database", Toast.LENGTH_LONG).show();
}
// close
db.close();
}
public Player getPlayerById(int id){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_ITEM,
COLUMNS,
" id = ?",
new String[] { String.valueOf(id) },
null,
null,
null,
null);
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build Item object
Player player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setScore(Integer.parseInt(cursor.getString(2)));
db.close();
return player;
}
public Player getPlayerByName(String name){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_ITEM,
COLUMNS,
" name = ?",
new String[]{name},
null,
null,
null,
null);
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build Item object
Player player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setScore(Integer.parseInt(cursor.getString(2)));
db.close();
return player;
}
public Player updatePlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_SCORE, player.getScore());
// insert
int i = db.update(TABLE_ITEM, values, KEY_ID + "= ?", new String[]{String.valueOf(player.getId())} );
Log.d("number of rows updated:", i+"");
// close
db.close();
return null;
}
public int deletePlayerById(String playerId) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
int result = db.delete(TABLE_ITEM,
KEY_ID+" = ?",
new String[] { playerId });
// 3. close
db.close();
return result;
}
}
activity_main.xml 是:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anotherdatabase.MainActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText2"
android:layout_marginLeft="36dp"
android:layout_marginTop="28dp"
android:text="Add"
android:onClick="newPlayer" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_alignRight="@+id/editText2"
android:text="Find"
android:onClick="findPlayer" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:ems="10" />
</RelativeLayout>
** Log-cat:**
07-10 11:29:59.423: D/AndroidRuntime(26313): Shutting down VM
07-10 11:29:59.423: W/dalvikvm(26313): threadid=1: thread exiting with uncaught exception (group=0x4174bba8)
07-10 11:29:59.423: E/AndroidRuntime(26313): FATAL EXCEPTION: main
07-10 11:29:59.423: E/AndroidRuntime(26313): Process: com.example.anotherdatabase, PID: 26313
07-10 11:29:59.423: E/AndroidRuntime(26313): java.lang.IllegalStateException: Could not execute method of the activity
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.view.View$1.onClick(View.java:3823)
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.view.View.performClick(View.java:4438)
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.view.View$PerformClick.run(View.java:18422)
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.os.Handler.handleCallback(Handler.java:733)
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.os.Handler.dispatchMessage(Handler.java:95)
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.os.Looper.loop(Looper.java:136)
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.app.ActivityThread.main(ActivityThread.java:5001)
07-10 11:29:59.423: E/AndroidRuntime(26313): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 11:29:59.423: E/AndroidRuntime(26313): at java.lang.reflect.Method.invoke(Method.java:515)
07-10 11:29:59.423: E/AndroidRuntime(26313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-10 11:29:59.423: E/AndroidRuntime(26313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-10 11:29:59.423: E/AndroidRuntime(26313): at dalvik.system.NativeStart.main(Native Method)
07-10 11:29:59.423: E/AndroidRuntime(26313): Caused by: java.lang.reflect.InvocationTargetException
07-10 11:29:59.423: E/AndroidRuntime(26313): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 11:29:59.423: E/AndroidRuntime(26313): at java.lang.reflect.Method.invoke(Method.java:515)
07-10 11:29:59.423: E/AndroidRuntime(26313): at android.view.View$1.onClick(View.java:3818)
07-10 11:29:59.423: E/AndroidRuntime(26313): ... 11 more
07-10 11:29:59.423: E/AndroidRuntime(26313): Caused by: java.lang.NullPointerException
07-10 11:29:59.423: E/AndroidRuntime(26313): at com.example.anotherdatabase.MainActivity.newPlayer(MainActivity.java:46)
07-10 11:29:59.423: E/AndroidRuntime(26313): ... 14 more
07-10 11:30:50.658: I/Adreno-EGL(27015): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
07-10 11:30:50.688: D/OpenGLRenderer(27015): Enabling debug mode 0
07-10 11:31:00.238: W/IInputConnectionWrapper(27015): showStatusIcon on inactive InputConnection
07-10 11:33:41.480: D/AndroidRuntime(28077): Shutting down VM
07-10 11:33:41.480: W/dalvikvm(28077): threadid=1: thread exiting with uncaught exception (group=0x4174bba8)
07-10 11:33:41.480: E/AndroidRuntime(28077): FATAL EXCEPTION: main
07-10 11:33:41.480: E/AndroidRuntime(28077): Process: com.example.anotherdatabase, PID: 28077
07-10 11:33:41.480: E/AndroidRuntime(28077): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anotherdatabase/com.example.anotherdatabase.MainActivity}: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.EditText
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.os.Handler.dispatchMessage(Handler.java:102)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.os.Looper.loop(Looper.java:136)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.ActivityThread.main(ActivityThread.java:5001)
07-10 11:33:41.480: E/AndroidRuntime(28077): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 11:33:41.480: E/AndroidRuntime(28077): at java.lang.reflect.Method.invoke(Method.java:515)
07-10 11:33:41.480: E/AndroidRuntime(28077): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-10 11:33:41.480: E/AndroidRuntime(28077): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-10 11:33:41.480: E/AndroidRuntime(28077): at dalvik.system.NativeStart.main(Native Method)
07-10 11:33:41.480: E/AndroidRuntime(28077): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.EditText
07-10 11:33:41.480: E/AndroidRuntime(28077): at com.example.anotherdatabase.MainActivity.onCreate(MainActivity.java:37)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.Activity.performCreate(Activity.java:5231)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-10 11:33:41.480: E/AndroidRuntime(28077): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
07-10 11:33:41.480: E/AndroidRuntime(28077): ... 11 more
07-10 11:33:43.442: I/Process(28077): Sending signal. PID: 28077 SIG: 9
07-10 11:36:58.490: I/Adreno-EGL(29284): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
07-10 11:36:58.531: D/OpenGLRenderer(29284): Enabling debug mode 0
07-10 11:37:03.906: W/IInputConnectionWrapper(29284): showStatusIcon on inactive InputConnection
07-10 11:38:13.851: I/Adreno-EGL(29892): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
07-10 11:38:13.881: D/OpenGLRenderer(29892): Enabling debug mode 0
07-10 11:38:29.908: D/AndroidRuntime(29892): Shutting down VM
07-10 11:38:29.908: W/dalvikvm(29892): threadid=1: thread exiting with uncaught exception (group=0x4174bba8)
07-10 11:38:29.908: E/AndroidRuntime(29892): FATAL EXCEPTION: main
07-10 11:38:29.908: E/AndroidRuntime(29892): Process: com.example.anotherdatabase, PID: 29892
07-10 11:38:29.908: E/AndroidRuntime(29892): java.lang.IllegalStateException: Could not execute method of the activity
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.view.View$1.onClick(View.java:3823)
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.view.View.performClick(View.java:4438)
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.view.View$PerformClick.run(View.java:18422)
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.os.Handler.handleCallback(Handler.java:733)
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.os.Handler.dispatchMessage(Handler.java:95)
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.os.Looper.loop(Looper.java:136)
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.app.ActivityThread.main(ActivityThread.java:5001)
07-10 11:38:29.908: E/AndroidRuntime(29892): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 11:38:29.908: E/AndroidRuntime(29892): at java.lang.reflect.Method.invoke(Method.java:515)
07-10 11:38:29.908: E/AndroidRuntime(29892): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-10 11:38:29.908: E/AndroidRuntime(29892): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-10 11:38:29.908: E/AndroidRuntime(29892): at dalvik.system.NativeStart.main(Native Method)
07-10 11:38:29.908: E/AndroidRuntime(29892): Caused by: java.lang.reflect.InvocationTargetException
07-10 11:38:29.908: E/AndroidRuntime(29892): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 11:38:29.908: E/AndroidRuntime(29892): at java.lang.reflect.Method.invoke(Method.java:515)
07-10 11:38:29.908: E/AndroidRuntime(29892): at android.view.View$1.onClick(View.java:3818)
07-10 11:38:29.908: E/AndroidRuntime(29892): ... 11 more
07-10 11:38:29.908: E/AndroidRuntime(29892): Caused by: java.lang.NumberFormatException: Invalid int: ""
07-10 11:38:29.908: E/AndroidRuntime(29892): at java.lang.Integer.invalidInt(Integer.java:137)
07-10 11:38:29.908: E/AndroidRuntime(29892): at java.lang.Integer.parseInt(Integer.java:358)
07-10 11:38:29.908: E/AndroidRuntime(29892): at java.lang.Integer.parseInt(Integer.java:331)
07-10 11:38:29.908: E/AndroidRuntime(29892): at com.example.anotherdatabase.MainActivity.newPlayer(MainActivity.java:47)
07-10 11:38:29.908: E/AndroidRuntime(29892): ... 14 more
答案 0 :(得分:1)
您的以下行存在问题。得分是一个edittext,它是空的,因此它在下一行给你提问。确保得分为某个int值。
int pScore = Integer.parseInt(score.getText().toString());
此外,要删除其他错误,您需要清理项目,然后重新构建它。