It's fairly simple. I am trying to learn how to establish sqlite connection for an android application. I am using Android Studio to write the code. When I try to load the app on my testing device - Android Phone of API 15 - a white screen flashes and an alert box pops up saying "LearnDB has stopped working".
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.
This is my MainActivity.java file.
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){
}
});
}
}
This is my activity_main.xml file.
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
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>
Aucun commentaire:
Enregistrer un commentaire