这相当简单。我正在尝试学习如何为 Android 应用程序建立 sqlite 连接。 我正在使用 Android Studio 来编写代码。当我尝试在我的测试设备(API 15 的 Android 手机)上加载该应用程序时,白屏闪烁,并弹出一个警告框,提示“LearnDB 已停止工作”。
Please tell me where I am going wrong.
IMPORTANT NOTE- Please try to explain how a sqlite connection should be exactly established and what rules should I definitely keep in mind while doing the same. Feel free to tell me any good programming practices while working with sqlite for android.
这是我的 MainActivity.java 文件。
package com.example.summer.learndb;
import android.database.sqlite.SQLiteDatabase;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db ;
public static final String DB_NAME = "scoreDb.db";
public static final int DB_VERSION = 1;
public static final String CREATE_DB_TABLE = "CREATE TABLE IF NOT EXISTS scoreTable (score1 INTEGER, score2 INTEGER);";
public static final String DB_TABLE = "scoreTable";
Button b1= (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = openOrCreateDatabase(DB_NAME, SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.close();
try{
db.execSQL(DB_TABLE);
db.close();
Toast.makeText(getBaseContext(),"Table created!!!",Toast.LENGTH_LONG).show();
}
catch(Exception e){
Toast.makeText(getBaseContext(),"ERROR!!!!", Toast.LENGTH_LONG).show();
}
b1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
}
});
b2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
}
});
}
}
这是我的activity_main.xml 文件。
<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="add"
android:id="@+id/button1" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="show"
android:id="@+id/button2" />
</LinearLayout>
最佳答案
选取一个上下文并编写以下代码。
public Context context; db = context.openOrCreateDatabase("scoreDb.db", Context.MODE_PRIVATE, null);
您需要删除在 openorCreateDatabase() 之后编写的以下行。
db.close();
写这个
db.execSQL(CREATE_DB_TABLE);
而不是
db.execSQL(DB_TABLE);
关于java - 我正在使用带有 API 15 的 Android 手机作为测试设备。我尝试运行此应用程序,但它在加载后立即停止在我的设备上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29279340/