0

I'm fairly new to Android. I'm making an application that shows a whole lot amount of different stings on previous and forward button clicks. I also have a database stored in the assets folder.. now I'm bit confused as to how tdo I read from that database in Ecilipse and pass it onto the textview. also, Is It Possible to show the strings one by one. Just like it happens in Arrays?

DataBaseCreator.java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class DataBaseCreator extends SQLiteOpenHelper {
    private static String DB_PATH = "/GetInspiredAndHaveFun/assets/Jokes.db";
    private static String DB_NAME = "Jokes.db";
    private static int DB_VERSION = 1;
    public static String DATABASE_TABLE = "myjoke";
    public String temp = "";
    public String[] col;


    private SQLiteDatabase myDataBase;
    private final Context myContext;

    public DataBaseCreator(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.myContext = context;

    }



    public void openDatabase() throws IOException {
        boolean dbe = checkDataBase();
        if (dbe) {
            Log.i("Tag", "dbe" + dbe);

        } else {
            Log.i("Tag", "dbdoesnotexist" + dbe);
            this.getReadableDatabase();
            copyDataBase();

        }

    }

    public void copyDataBase() throws IOException {
        InputStream inp = myContext.getAssets().open(DB_NAME);
        String ofn = DB_PATH + DB_NAME;
        OutputStream oup = new FileOutputStream(ofn);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inp.read(buffer)) > 0) {
            oup.write(buffer, 0, length);
        }

        oup.flush();
        inp.close();
        oup.close();

    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;

            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        }

        catch (SQLiteException e) {

        }

        return checkDB != null ? true : false;
    }

    public void openDataBase() throws SQLException {

        // Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);
        passText();

    }

    public final String passText() {
        Cursor cursor = myDataBase.query(DATABASE_TABLE, col, null, null,
                null, null, null);
        String[] column = cursor.getColumnNames();
        column=col;


        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            temp += cursor.getString(50);
            cursor.moveToNext();

        }

        return temp;

    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

Jokes activity

    import java.io.IOException;

    import android.annotation.TargetApi;
    import android.app.Activity;
    import android.content.Context;
    import android.os.Build;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.View;
    import android.widget.ImageButton;
    import android.widget.TextView;
    import android.widget.Toast;




    public class Jokes extends Activity {

        ImageButton bck, fwd, cpy, col;

        TextView t1;

        String[] jok;
        int i, a3;
        TextView nm1;

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

..
...
...
...
..

.

 }

        {

            DataBaseCreator myDbHelper = new DataBaseCreator(this);

            try{
                myDbHelper.copyDataBase();
            } 
            catch (IOException ioe) {
                throw new Error("Unable to create database");
            }

            myDbHelper.openDataBase();



        }

        }
  • Can you show what have you done till now in your code ? so i can guide you that way. – Chintan Soni Apr 30 '13 at 14:05
  • I edited my Post. Check it out. –  Apr 30 '13 at 14:10
  • can you please elaborate more about the flow in which you want to go in. Just give me a overview of, how your code should work. – Chintan Soni Apr 30 '13 at 14:15
  • What I want it to do is read everything, all the strings that I've stored in my databse. Then when a user presses the forward button it shows the first entry from the database . On Previous button click it shows the previous entry from the database. Simple! Yet Complex. –  Apr 30 '13 at 14:21
  • If i am not wrong what i understood is, when user clicks on, say button, it should go to next activity where you show a textview(for displaying strings) and two buttons(previous and next to display previous and next string). Am i going correct ? – Chintan Soni Apr 30 '13 at 14:24
  • Yeah, right.And now I want to change the Textview's text value upon prev and forw button clicks. –  Apr 30 '13 at 14:26
  • Hey, are you done with what you were trying to achieve ?? – Chintan Soni May 01 '13 at 08:13
  • Heyy @user2320244, are you there ?? – Chintan Soni May 02 '13 at 14:19

2 Answers2

0

You can go through this: Android: Accessing assets folder sqlite database file with .sqlite extension

This will definitely help you. I am sure.

Edit:

I am out of time right nowadays. So, i'll not able to provide you full code, but the wireframe will definitely help you. This is how we go:

In the activity you are trying to display the data, first fetch all the data you want to display and store in an arraylist (Assumption: the data you want to display comes from only single column, otherwise, you need to create a class that will store the values from more than one columns, and then create an arrayList of that class For ex: if you need to create a class Student{int roll_no, String name, int age}, then you need to create ArrayList of the type student, ArrayList<Student>)

Now initialize an int var with value 1, say, int index_counter = 1;

Now, you are traversing the string in a linear fashion, so create a function with argument as integer, in which you will set text according to button or imageview click.

Function will look like:

set_data(int index) { textView.setText(arraylist.get(index)); }

And your onClick() events will look like:

fwd.setOnClickListener(new OnClickListener
public void onClick(View v)
{
index_counter = index_counter + 1;

if(index_counter == arraylist.size)
{
 fwd.setEnabled(false);
}

set_data(indexCounter);
}
);

bck.setOnClickListener(new OnClickListener
public void onClick(View v)
{
index_counter = index_counter - 1;

if(index_counter == 1)
{
 bck.setEnabled(false);
}

set_data(indexCounter);
}
);

And you are done... And ofcourse, dont forget to call set_data(1); in onCreate() because first time when you come to this activity you need to set the first data from the arraylist to be displayed by default. And before doing this, your arraylist should be filled by fetching data from database..

I think, now, it is enough for you to prepare your application. Okay... But even then if you have any query then you may ask me.

PS: there may be some errors while typing code because i've directly written the code here. Without typing it before anywhere. So please correct it. And Gud luck...

Community
  • 1
  • 1
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
  • And answers to all the subquestions you asked, is Yes, everything you asked is possible. Thing that matters the way of implementing that should be clear. – Chintan Soni Apr 30 '13 at 14:13
  • Yeah! :) Thanks. Anyways, check my other comment. –  Apr 30 '13 at 14:22
0

You can get a collection of object (in your case Joke) by using a cursor with your DB, then you can iterate on your collection and send an object (serializable) to another activity using an intent.

Romain R
  • 41
  • 4
  • Get a look at [this code](https://github.com/lukaspili/3SUN-GeekQuote-2012) it does exactly what you want. – Romain R May 01 '13 at 14:02
  • It doesn't/ It adds values to the database. what I want is to bundle the database with my application and let the app do the rest. I don't want my users to add each and every quote by themselves. I should do that for them. –  May 04 '13 at 14:28
  • Anyways, can you tell me how to use my own database rather than creating one inside the app and then use the other code (that you mentioned) same as that to display quotes in the application. –  May 04 '13 at 14:30