Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing database to another activity via intent

I am attempting to pass the contents of a database that I have created to another activity via intent using an AsyncTask where the contents of the database will be displayed. A query would be used to specify the data to be displayed using my query button. I was wondering how I could go about passing the database information to the other activity. This is what I have so far.

package com.dwolford.project9;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Main extends Activity {

Button quit;
Button query;
Button create;
String FILENAME = "";
SQLDatabase db;//possibly use asynctask
String sQuery = "";
EditText queryText;

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

    db = new SQLDatabase(this);//Use asynctask?



    create = (Button)findViewById(R.id.create);
    create.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean isInserted = db.insertDataS("S01", "Smith", "London" );
            if(isInserted == true)
                Toast.makeText(Main.this, "Data inserted", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(Main.this, "Data not inserted", Toast.LENGTH_LONG).show();

            new createTask().execute(FILENAME);
        }
    });

    queryText = (EditText)findViewById(R.id.selectQuery);

    query = (Button)findViewById(R.id.query);
    query.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Main.this,execute_query.class);
            sQuery = queryText.getText().toString();

            //intent.putExtra("database", db);
            intent.putExtra("queryChoice", sQuery);
            startActivity(intent);
        }
    });

    quit = (Button)findViewById(R.id.quit);
    quit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void AddData()//Add to asynctask?
{

}



public class createTask extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... params)
    {
        return null;
    }

}


public class SQLDatabase extends SQLiteOpenHelper{

    public static final String SPdb = "SPdb.db";
    public static final String s = "s";//First table name
    public static final String sno = "sno";
    public static final String sname = "sname";
    public static final String city = "city";
    public static final String p = "p";
    public static final String pno = "pno";
    public static final String pname = "pname";
    public static final String cost = "cost";
    public static final String sp = "sp";
    public static final String qty = "qty";


    public SQLDatabase(Context context) {
        super(context, SPdb, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + s + "(sno    TEXT     PRIMARY KEY COLLATE NOCASE,\n" +
                "   sname  TEXT     NOT NULL    COLLATE NOCASE,\n" +
                "   city   TEXT     NOT NULL    COLLATE NOCASE\n)");

        db.execSQL("CREATE TABLE " + p + "(pno    TEXT      NOT NULL COLLATE NOCASE,\n" +
                "   pname  TEXT      NOT NULL COLLATE NOCASE,\n" +
                "   cost   REAL      NOT NULL,\n" +
                "   city   TEXT      NOT NULL COLLATE NOCASE,\n" +
                "\n" +
                "   PRIMARY KEY (pno)\n)");

        db.execSQL("CREATE TABLE " + sp + "(sno     TEXT     NOT NULL REFERENCES s(sno) COLLATE NOCASE,\n" +
                "   pno     TEXT     NOT NULL COLLATE NOCASE,\n" +
                "   qty     INTEGER  NOT NULL,\n" +
                "\n" +
                "   FOREIGN KEY (pno) REFERENCES p(pno)\n)");

        //db.execSQL("create table " = );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " +s);
        db.execSQL("DROP TABLE IF EXISTS " +p);
        db.execSQL("DROP TABLE IF EXISTS " +sp);
        onCreate(db);//Create table in database
    }


    public boolean insertDataS(String sno, String sname, String city)
    {
        SQLiteDatabase db = this.getWritableDatabase();//Maybe readable
        ContentValues contentValue = new ContentValues();
        contentValue.put(this.sno, sno);
        contentValue.put(this.sname, sname);
        contentValue.put(this.city, city);
        long result = db.insert(s, null, contentValue);
        if(result == -1)
        {
            return false;
        }
        else
        {
            return true;
        }

    }


    public Cursor getData()
    {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from " + s, null);//* gets all in the query
        return res;
    }

}
}

Main xml:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Create"
    android:id="@+id/create"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="55dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Query"
    android:id="@+id/query"
    android:layout_below="@+id/sqlQuery"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="45dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quit"
    android:id="@+id/quit"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignRight="@+id/selectQuery"
    android:layout_alignEnd="@+id/selectQuery" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="sql query"
    android:id="@+id/sqlQuery"
    android:textSize="40dp"
    android:textStyle="bold"
    android:layout_below="@+id/create"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="41dp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/selectQuery"
    android:text="query"
    android:layout_below="@+id/query"
    android:layout_marginTop="56dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

Class where database information will be displayed:

package com.dwolford.project9;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class execute_query extends ActionBarActivity {

Button back;
String query = "";

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

    Bundle extras = getIntent().getExtras();
    if(extras == null)
    {
        return;
    }
    query = extras.getString("queryChoice");

    //query = getIntent().getDataString();

    back = (Button)findViewById(R.id.back);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_execute_query, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

query xml:

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back"
    android:id="@+id/back"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:height="30dp" />

<HorizontalScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/horizontalScrollView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_above="@+id/back"
    android:fillViewport="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignTop="@+id/horizontalScrollView"

        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_above="@+id/back" />
</HorizontalScrollView>

like image 673
Deus Ex Machina Avatar asked Nov 10 '22 08:11

Deus Ex Machina


1 Answers

I think it is good practice to have your database connection as a separate static class and call functions from other classes inside an AsyncTask whenever needed. Call your query function in doInBackground() and start your activity from onPostExecute() if you need to.

Here is the example:

    create.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    // initialize your database here
       db = new SQLDatabase(Main.this)        
       boolean isInserted;
     new AsyncTask(){
        @Override
        protected void onPreExecute() {
           // do things you need to do before calling db function
        }

        @Override
        protected Object doInBackground(Object[] params) {

            //call db function here
             isInserted = db.insertDataS("S01", "Smith", "London" );
            //return query resul
            return isInserted;
        }

        @Override
        protected void onPostExecute(Object o) {
            // you can get returned result here as an object and cast it
            isInserted = (boolean)o;
            // then start your activity here if you need to or make changes
            // to a view or show a toast

            Intent i = new Intent(Main.this, otherClass.class);
            i.putExtras("result",isInserted);
            startActivity(i);
        }
    }.execute();

I hope this helps you.

like image 179
Erfan GLMPR Avatar answered Nov 15 '22 11:11

Erfan GLMPR