dimanche 1 mai 2016

How to create SQLite database in android

I have created a Databasehelper.java class and in that class I have called SQLite database class and implemented all its methods and in the main class when I am calling this class instance and when I am running the app It is showing "Unfortunately your app has stopped"

this is code

package com.example.android.viewpager1;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Vikas on 5/1/2016.
 */
public class Databasehelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME="Answers.db";
    public static final String TABLE_NAME="answers_table";
    public static final String COL_1="QUESTION_NO";
    public static final String COL_2="QUESTION_ANS";



    public Databasehelper(Context context)
    {
        super(context,DATABASE_NAME,null,1);
        SQLiteDatabase db= this.getWritableDatabase();
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
    db.execSQL("create table" + TABLE_NAME+"(QUESTION_NO INTEGER PRIMARY KEY AUTOINCREMENT,QUESTION_ANS VARCHAR);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
      db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
      onCreate(db);
    }
}

and this is mainactivity.java

package com.example.android.viewpager1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RadioButton;

import java.util.List;
import java.util.Vector;

public class MainActivity extends FragmentActivity
{
    Databasehelper mydb;

    private PagerAdapter mPagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewpager_layout);
        initialisePaging();
        mydb=new Databasehelper(this);//here I am making DB 

    }

here I am making database but it is not running and I also know that on the main thread or UI thread we should not create database or networking object and fro that we should use AsynTask class but can anyone tell how to use it or any other solution

Aucun commentaire:

Enregistrer un commentaire