简体   繁体   English

如何从SQLite数据库读取并将值传递给另一个类中的textview

[英]How to read from a SQLite Database and pass the value to a textview in another Class

I'm fairly new to Android. 我刚接触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. 我还在资产文件夹中存储了一个数据库。.现在,我对如何从Ecilipse中的该数据库中读取tdo并将其传递到textview感到困惑。 also, Is It Possible to show the strings one by one. 同样,是否可以一一显示字符串。 Just like it happens in Arrays? 就像它发生在数组中一样吗?

DataBaseCreator.java 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();



        }

        }

You can go through this: Android: Accessing assets folder sqlite database file with .sqlite extension 您可以执行以下操作: Android:使用.sqlite扩展名访问资产文件夹sqlite数据库文件

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> ) 在您尝试显示数据的活动中,首先获取要显示的所有数据并将其存储在数组列表中(假设:要显示的数据仅来自单个列,否则,您需要创建一个类来存储多个列中的值,然后创建该类的arrayList例如:如果您需要创建Student {int roll_no,String name,int age}类,则需要创建Student类型的ArrayList, ArrayList<Student>

Now initialize an int var with value 1, say, int index_counter = 1; 现在初始化一个值为1的int var,例如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. 现在,您以线性方式遍历字符串,因此创建一个参数为整数的函数,在该函数中,将根据按钮或imageview单击设置文本。

Function will look like: 函数将如下所示:

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

And your onClick() events will look like: 您的onClick()事件将类似于:

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); 这样就完成了……当然,不要忘记调用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. onCreate()因为第一次进行此活动时,您需要设置要默认显示的arraylist中的第一个数据。 And before doing this, your arraylist should be filled by fetching data from database.. 在执行此操作之前,应通过从数据库中获取数据来填充您的arraylist。

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. PS:键入代码时可能会出现一些错误,因为我已经在此处直接编写了代码。 Without typing it before anywhere. 无需在任何地方键入它。 So please correct it. 因此,请更正它。 And Gud luck... 还有老天爷...

您可以通过将游标与数据库一起使用来获取对象的集合(在您的情况下为笑话),然后可以迭代您的集合,并使用意图将对象(可序列化)发送到另一个活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM