-1

this is the main activity

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;



public class MainActivity extends AppCompatActivity {

    EditText myinput;
    TextView mytext;
    MyDBHandler dbhandler;




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




        myinput =(EditText) findViewById(R.id.myinput);
        mytext =(TextView) findViewById(R.id.mytext);
        dbhandler= new MyDBHandler(this, null, null, 1);
        printDatabase();


    }

    //add product to database

    public void addstuff(View view)
    {
        products product = new products(myinput.getText().toString());
        dbhandler.addProduct(product);
        printDatabase();

    }

    //delete items from database

    public void deletestuff(View view)
    {
        String inputtext= myinput.getText().toString();
        dbhandler.deleteProduct(inputtext);
        printDatabase();


    }

    public void printDatabase()
    {
        String dbString= dbhandler.databaseToString();
        mytext.setText(dbString);
        myinput.setText("");
    }

}

the products class, to get and set products

public class products {

    private int _id;
    private String _productname;

    public products()
    {

    }

    public products(String productname) {
        this._productname = productname;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public void set_productname(String _productname) {
        this._productname = _productname;
    }

    public int get_id() {
        return _id;
    }

    public String get_productname() {
        return _productname;
    }
}

the database handler class,

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


public class MyDBHandler extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "products.db";
    public static final String TABLE_PRODUCTS = "products";
    public static final String COLUMN_ID ="_id";
    public static final String COLUMN_PRODUCTNAME ="productname";


    public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {

        String query= "CREATE TABLE " + TABLE_PRODUCTS + "(" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
                COLUMN_PRODUCTNAME + " TEXT " +
                ");";
        db.execSQL(query);

    }

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

    //add a new row to the database
    public void addProduct(products product)
    {
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        SQLiteDatabase db= getWritableDatabase();
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }

    //delete product from the database
    public void deleteProduct(String productname)
    {
        SQLiteDatabase db= getWritableDatabase();
        db.execSQL("DELETE FROM "+ TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + " =\"" + productname + "\";" );
    }

    //printing out the database as a string

    public String databaseToString()
    {
        String dbString ="";
        SQLiteDatabase db= getWritableDatabase();
        String query = "SELECT * FROM "+ TABLE_PRODUCTS + " WHERE 1";

        //CURSOR POINTS TO A LOCATION IN THE DATABASE RESULTS
        Cursor c= db.rawQuery(query,null);
        //go to 1st row in your results
        c.moveToFirst();

        while(!c.isAfterLast())
        {
            if(c.getString(c.getColumnIndex("productname"))!=null)
            {
                dbString += c.getString(c.getColumnIndex("productname"));
                dbString += "\n";

            }

        }
        db.close();
        return dbString;

    }



}

I tried putting the getwritabledatabase() codes in runnables, but coud'nt do it for the databasetostring() method.

how do I call the getWritableDatabase() from an Intent Service??

I want to use this intent service to getWritableDatabase()

import android.app.IntentService;
import android.content.Intent;

public class myintent extends IntentService{

    public myintent(String name) {
        super("myintent");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }
}

I don't know how to do it through INTENT SERVICE

this is the logcat after the app starts

8-19 17:56:08.848  15523-15523/? I/art﹕ Late-enabling -Xcheck:jni
08-19 17:56:08.848  15523-15523/? I/art﹕ VMHOOK: rlim_cur : 0 pid:15523
08-19 17:56:09.218  15523-15523/com.example.vashisht.sqliteapp D/Atlas﹕ Validating map...
08-19 17:56:09.278  15523-15554/com.example.vashisht.sqliteapp I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: TEST SBA LA.BF.1.1.1_RB1 AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.012 + c1105519 + c_apilogging ()
    OpenGL ES Shader Compiler Version: E031.25.03.00
    Build Date: 01/23/15 Fri
    Local Branch:
    Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.012
    Local Patches: NONE
    Reconstruct Branch: NOTHING
08-19 17:56:09.478  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=android.view.ViewRootImpl$W@1287b4e7, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F....I. 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@18863f3d

when i enter a text in the textfield and tap the addbutton(to add entries to datbase table) the app freezes and the logcat goes like this:

8-19 17:56:09.478  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=android.view.ViewRootImpl$W@1287b4e7, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F....I. 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@18863f3d
08-19 17:57:30.878  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=null, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F...... 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@2072768a
08-19 17:57:30.888  15523-15523/com.example.vashisht.sqliteapp W/IInputConnectionWrapper﹕ performPrivateCommand on inactive InputConnection
08-19 17:57:30.918  15523-15523/com.example.vashisht.sqliteapp W/IInputConnectionWrapper﹕ performPrivateCommand on inactive InputConnection
08-19 17:57:35.338  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=android.view.ViewRootImpl$W@1287b4e7, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F....I. 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@2996b4fb
08-19 17:57:42.158  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.091ms
08-19 17:57:42.608  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.910ms
08-19 17:57:55.408  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 180(6KB) AllocSpace objects, 108(15MB) LOS objects, 43% free, 5MB/9MB, paused 9.448ms total 36.167ms
08-19 17:57:59.468  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 43(1488B) AllocSpace objects, 24(4MB) LOS objects, 40% free, 6MB/10MB, paused 10.028ms total 18.813ms
08-19 17:58:00.478  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.383ms
08-19 17:58:11.218  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.913ms
08-19 17:58:14.328  15523-15537/com.example.vashisht.sqliteapp I/art﹕ WaitForGcToComplete blocked for 5.482ms for cause HeapTrim
08-19 17:58:15.628  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 60(2064B) AllocSpace objects, 32(7MB) LOS objects, 39% free, 6MB/10MB, paused 11.181ms total 21.280ms
08-19 17:58:16.248  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 10.318ms
08-19 17:58:26.088  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background sticky concurrent mark sweep GC freed 19(688B) AllocSpace objects, 9(2MB) LOS objects, 24% free, 5MB/7MB, paused 5.279ms total 10.035ms
08-19 17:58:28.778  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.467ms
08-19 17:58:31.278  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.368ms
08-19 17:58:34.298  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.308ms
08-19 17:58:34.348  15523-15537/com.example.vashisht.sqliteapp I/art﹕ WaitForGcToComplete blocked for 10.169ms for cause HeapTrim
08-19 17:58:36.798  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.915ms
08-19 17:58:38.918  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 16.815ms
08-19 17:58:44.538  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 8.032ms
08-19 17:58:44.878  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.364ms
08-19 17:58:44.878  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 35(1184B) AllocSpace objects, 22(7MB) LOS objects, 54% free, 3MB/7MB, paused 5.855ms total 17.791ms
08-19 17:58:46.248  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.053ms
08-19 17:58:46.268  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.842ms
08-19 17:58:46.268  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background sticky concurrent mark sweep GC freed 26(928B) AllocSpace objects, 12(4MB) LOS objects, 21% free, 6MB/7MB, paused 10.751ms total 18.381ms
08-19 17:58:48.828  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.178ms
08-19 17:58:48.868  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.268ms
08-19 17:58:49.538  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.654ms
08-19 17:58:50.838  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.434ms
08-19 17:58:54.758  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 8.813ms
08-19 17:58:54.758  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background sticky concurrent mark sweep GC freed 24(864B) AllocSpace objects, 11(3MB) LOS objects, 27% free, 6MB/8MB, paused 9.415ms total 14.852ms
08-19 17:58:56.798  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.198ms
08-19 17:58:56.808  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 39(1328B) AllocSpace objects, 23(8MB) LOS objects, 39% free, 6MB/10MB, paused 10.067ms total 19.829ms
08-19 17:59:03.098  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.042ms
08-19 17:59:03.108  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 23(784B) AllocSpace objects, 14(5MB) LOS objects, 54% free, 3MB/7MB, paused 7.720ms total 22.105ms
08-19 17:59:04.368  15523-15537/com.example.vashisht.sqliteapp I/art﹕ WaitForGcToComplete blocked for 8.374ms for cause HeapTrim
08-19 17:59:18.878  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 8.496ms
08-19 17:59:21.378  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.302ms
08-19 17:59:21.658  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 35(1184B) AllocSpace objects, 21(8MB) LOS objects, 39% free, 6MB/11MB, paused 5.077ms total 23.084ms
08-19 17:59:24.078  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 27(928B) AllocSpace objects, 15(6MB) LOS objects, 52% free, 3MB/7MB, paused 9.533ms total 23.103ms

and then I manually need to kill the App, or after some time it says not responding!!

I modified the databasetostring() method to return a string array so that i can display results in a listview.

 public String[] databaseToString()
    {


        String[] dbString;
        dbString = new String[]{};

        SQLiteDatabase db= getReadableDatabase();
        String query = "SELECT * FROM "+ TABLE_PRODUCTS + " WHERE 1";

        //CURSOR POINTS TO A LOCATION IN THE DATABASE RESULTS
        Cursor c= db.rawQuery(query,null);
        //go to 1st row in your results
        c.moveToFirst();
        int i=0;
        while(!c.isAfterLast())
        {
            if(c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME))!=null)
                dbString[i] = c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME));

            i++;

        }
        db.close();

        return dbString;


    }

but here , dbString[i] = c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME)); is throwing an array out of bounds exception???

iaaphpd13
  • 29
  • 1
  • 2
  • 9

2 Answers2

1

To call it from IntentService just call this

sqLiteDatabase = getApplicationContext().getWritableDatabase();

You need the getApplicationContext() since IntentService extends Context

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • and what package do I import to get the getApplicationContext() method?? – iaaphpd13 Aug 19 '15 at 12:00
  • I haven't written any code in the intent service class, I wanna call getWritableDatabase() in the background. – iaaphpd13 Aug 19 '15 at 12:09
  • How can I call it from IntentService and then used it in my database handler class. – iaaphpd13 Aug 19 '15 at 12:11
  • @iaaphpd13 whats on the logcat when you call `MyDBHandler#getWritableDatabase()`? – pskink Aug 19 '15 at 12:25
  • @pskink I'v posted the logcat of, when the launcher activity starts and when I enter text and click ADD button on my interface (that's when the getWritableDatabase() is called and an insert query is executed) , getWritableDatabase() is also called when the mainactivity is created, but the app goes good at that time. – iaaphpd13 Aug 19 '15 at 12:39
-1
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;


public class MyDBHandler extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "products.db";
    public static final String TABLE_PRODUCTS = "products";
    public static final String COLUMN_ID ="_id";
    public static final String COLUMN_PRODUCTNAME ="productname";


    public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {


        String query= "CREATE TABLE " + TABLE_PRODUCTS + "(" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
                COLUMN_PRODUCTNAME + " TEXT " +
                ");";
        db.execSQL(query);


    }



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

    //add a new row to the database
    public void addProduct(products product)
    {
        final ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());

        SQLiteDatabase db= getWritableDatabase();
                db.insert(TABLE_PRODUCTS, null, values);
                db.close();





    }

    //delete product from the database
    public void deleteProduct(final String productname)
    {



                SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + " =\"" + productname + "\";");





    }

    //printing out the database as a string

    public String databaseToString()
    {
        String dbString ="";
        SQLiteDatabase db= getWritableDatabase();
        String query = "SELECT * FROM "+ TABLE_PRODUCTS + " WHERE 1";

        //CURSOR POINTS TO A LOCATION IN THE DATABASE RESULTS
        Cursor c= db.rawQuery(query,null);
        //go to 1st row in your results
        c.moveToFirst();

        while(!c.isAfterLast())
        {
            if(c.getString(c.getColumnIndex("productname"))!=null)
            {
                dbString += c.getString(c.getColumnIndex("productname"));
                dbString += "\n";

            }
            c.moveToNext();

The problem was here, I forgot to move the cursor to the next result and that caused an infinite while loop! oooops!

        }
        db.close();
        return dbString;

    }



}
iaaphpd13
  • 29
  • 1
  • 2
  • 9