M
M
Michael2015-05-05 23:44:12
Java
Michael, 2015-05-05 23:44:12

How to extract information from Sqlite DB?

Hello! I am writing an application "reference book of mushrooms". On the main activity, we have a listview , and depending on which mushroom in the list we clicked on, a new activity is launched and its description is displayed (determined by id). I filled the description of mushrooms through SqliteBrowser (fields: _id , mushroom) and in the program I connect the database as follows:

package com.example.bd;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;


public class DataBaseHelper extends SQLiteOpenHelper implements BaseColumns {
private static String DB_PATH =  "/data/data/com.example.bd/databases/";
private static final String DB_NAME = "mushrooms.db";
    private SQLiteDatabase myDataBase;
    private  static final int DATABASE_VERSION = 1;
    private final Context myContext;
    public static final String TABLE_NAME = "mushrooms_table";


    DataBaseHelper(Context context) {

        super(context, DB_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }

    public void createDatabase() throws IOException {
        boolean dbexits = checkDataBase();
        if(dbexits) {



        }else {
            this.getReadableDatabase();

            try {
                copyDatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }


    private boolean checkDataBase(){
        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }catch(SQLiteException e){

        }
        if(checkDB != null){
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }


    private void copyDatabase() throws  IOException{
        Log.i("Database",
                "Новая база данных копируется на устройство!");
        int length;
        InputStream myInput = myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];

        while ((length = myInput.read(buffer))>0) {
            myOutput.write(buffer , 0 , length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
        Log.i("Database",
                "Новая база данных скопирована на устройство");
    }


    public void openDataBase() throws SQLException {


        String myPath  = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath , null , SQLiteDatabase.OPEN_READWRITE);

    }



    public synchronized void close() {

        if (myDataBase != null) {
            myDataBase.close();

        }
        super.close();
    }


    public void getInfromation(int id) {
        Information inf = new Information();
       myDataBase = this.getReadableDatabase();

        String selection = "_id = ?";
        String[] selectionArgs = new String[]{String.valueOf(id)};
        Cursor cursor = myDataBase.query(TABLE_NAME , null , selection , selectionArgs , null , null , null);

        try {
            if (cursor.moveToFirst()) inf.textView.setText(cursor.getColumnIndex("mushroom"));


        }finally {
            cursor.close();
        }

     myDataBase.close();
    }







   /* public Cursor getInfromation(int id) {
        String selection = "_id = ?";
        String[] selectionArgs = new String[]{String.valueOf(id)};

        return myDataBase.query(TABLE_NAME , null , selection , selectionArgs , null , null , null);
    }*/

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

Here's the question: do you see the getInformation method? This method makes a selection from the database to determine which id we clicked on, but the fact is that if this method is called in the activity where the description will be displayed, then it will not display anything at all in the textView , tell me how to display the information correctly (how to fix the method ) ?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
Oleg Gamega, 2015-05-05
@gadfi

cursor.getString(cursor.getColumnIndex("mushroom")
oh, and you mixed everything to the heap ... describe the models, at least don't suffer, and most importantly void getInfromation(int id)
+ scope inf is the getInfromation method ... what and where should it output?

O
one pavel, 2015-05-06
@onepavel

What is this Information inf = new Information(); ? Where does inf.textView come from?
Where and on what thread is getInformation called?
Are you sure that getInfromation id is correct for the database?

M
Michael, 2015-05-06
@M-Misha-M

I apologize for not posting all the code. Here are my classes where I call methods: create , open - in MainActivity, getInformation - in Information
MainActivity:

package com.example.bd;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;


public class MainActivity extends Activity {
    private DataBaseHelper db;
 int id = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        db = new DataBaseHelper(this);

        try {
            db.createDatabase();
        } catch (IOException e) {
           throw new Error("Unable to create database");

        }

        try {
            db.openDataBase();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        File database=getApplicationContext().getDatabasePath("mushrooms.db");

        if (!database.exists()) {
            // Database does not exist so copy it from assets here
            Log.i("Database", "Not Found");
        } else {
            Log.i("Database", "Found");
        }


        ListView listView = (ListView) findViewById(R.id.lvChapters);
        final String[] mushrooms = {
                "1.Белый гриб" ,
                "2.Моховик",
                "3.Лисички" ,
                "4.Опята" ,
                "5.Масленок",
                "6.Подберезовик"
        };
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1 , mushrooms);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this , Information.class);
                intent.putExtra("id" , position);
                intent.putExtra("title" , adapter.getItem(position));
                startActivityForResult(intent , 0);
            }
        });


    }


    @Override
    public void onPause() {
        super.onPause();
        db.close();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            db.openDataBase();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

information:
package vodnik.ua.cursova;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import java.io.IOException;
import java.sql.SQLException;

/**
 * Created by Admin on 25.04.2015.
 */
public class Information extends Activity{
    DataBaseHelper db;
    int id = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.information);
       db = new DataBaseHelper(this);

        try {
            db.createDatabase();
        } catch (IOException e) {
            throw new Error("Unable to create database");
        }

        try {
            db.open();
        } catch (SQLException sqle) {
            throw new Error("Unable opening database");
        }


        String item = getIntent().getExtras().getString("title");
        id = getIntent().getExtras().getInt("id", 0);
        TextView textView = (TextView) findViewById(R.id.textView1);



        db.close();

    }
}

E
Eserchik, 2015-05-06
@Eserchik

Yes, you certainly mixed everything together.
Here is what you do:
startandroid.ru/ru/uroki/vse-uroki-spiskom/111-uro...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question