-1

i'm new in android and i want help about " how to call a .db file in project to retrieve data from it (the .db contains Images ) "and i want call it in my app to be shown but without any access the internet (offline)

the problem is how to call images from my local database file

Could you help me to find the way to do that

and this is i tried this an App for Dictonary and i iwanna Retreive images with Word & meaning i tried word and meaning and worked fine but how to retrieve images to be called from the same table

i hope that i find someone help me and thanks for advance

CustomAdabter.java

package com.example.android.db;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class CustomAdapter extends 
RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

private ArrayList<DictObjectModel> dataSet;
Boolean check=false;
public static class MyViewHolder extends RecyclerView.ViewHolder {

    TextView word,meaning;

    RelativeLayout expandable;

    public MyViewHolder(View itemView) {
        super(itemView);
        this.expandable= (RelativeLayout)itemView.findViewById(R.id.expandableLayout);
        this.word= (TextView)itemView.findViewById(R.id.wordtext);
        this.meaning = (TextView) itemView.findViewById(R.id.meaningtext);

    }
}

public CustomAdapter(ArrayList<DictObjectModel> data) {
    this.dataSet = data;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                       int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view_row, parent, false);

    final MyViewHolder myViewHolder = new MyViewHolder(view);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!check)
            {
                myViewHolder.expandable.animate()
                        .alpha(0.0f)
                        .setDuration(1000);


                myViewHolder.expandable.setVisibility(View.GONE);
                check=true;
                //  myViewHolder.schedule.setVisibility(View.VISIBLE);

            }
            else {
                myViewHolder.expandable.setVisibility(View.VISIBLE);
                myViewHolder.expandable.animate()
                        .alpha(1.0f)
                        .setDuration(1000);

                check=false;

            }
        }
    });

    return myViewHolder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {

    TextView word1= holder.word;
    TextView meaning1 = holder.meaning;

    word1.setText(dataSet.get(listPosition).getWord());
    meaning1.setText(dataSet.get(listPosition).getMeaning());

}

@Override
public int getItemCount() {
    return dataSet.size();
}
} 

DataBaseHelper.java

package com.example.android.db;


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.util.Log;
import android.widget.Button;

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{

//The Android's default system path of your application database.
private static String DB_PATH = "";

private static String DB_NAME = "test.db";

private SQLiteDatabase myDataBase;

private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public DatabaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
    DB_PATH= myContext.getDatabasePath(DB_NAME).toString();
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * */
public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
    }else{

        //By calling this method and empty database will be created into the default system path
        //of your application so we are gonna be able to overwrite that database with our database.
        this.getWritableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }

    }

}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase(){
    //  this.getReadableDatabase();

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH ;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

        //database does't exist yet.

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH ;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException{

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

}

@Override
public synchronized void close() {

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

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.


//add your public methods for insert, get, delete and update data in database.

}

DictObjectModel.java

package com.example.android.db;


public class DictObjectModel {

String word, meaning;

public DictObjectModel(String word, String meaning) {

    this.   word = word;
    this.meaning = meaning;


}

public String getWord() {
    return word;
}

public String getMeaning() {
    return meaning;
}


}

MainActivity.java

package com.example.android.db;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;


public class MainActivity extends AppCompatActivity {

private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
public static ArrayList<DictObjectModel> data;
DatabaseHelper db ;
ArrayList<String> wordcombimelist;
ArrayList<String> meancombimelist;
LinkedHashMap<String,String> namelist;
SearchView searchView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    recyclerView.setHasFixedSize(true);
    db= new DatabaseHelper(this);
    searchView = (SearchView) findViewById(R.id.searchView);
    searchView.setQueryHint("Search Here");
    searchView.setQueryRefinementEnabled(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    data = new ArrayList<DictObjectModel>();
    fetchData();


    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {return  false; }

        @Override
        public boolean onQueryTextChange(String newText) {


            newText = newText.toLowerCase();

            final ArrayList<DictObjectModel> filteredList = new 
 ArrayList<DictObjectModel>();

            for (int i = 0; i < wordcombimelist.size(); i++) {

                final String text = wordcombimelist.get(i).toLowerCase();
                if (text.contains(newText)) {

                    filteredList.add(new 
DictObjectModel(wordcombimelist.get(i),meancombimelist.get(i)));
                }
            }
            adapter = new CustomAdapter(filteredList);
            recyclerView.setAdapter(adapter);


            return true;
        }
    });


}
public void fetchData()
{
    db =new DatabaseHelper(this);
    try {

        db.createDataBase();
        db.openDataBase();

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }


    namelist=new LinkedHashMap<>();
    int ii;
    SQLiteDatabase sd = db.getReadableDatabase();
    Cursor cursor = sd.query("places" ,null, null, null, null, null, null);
    ii=cursor.getColumnIndex("name");
    wordcombimelist=new ArrayList<String>();
    meancombimelist= new ArrayList<String>();
    while (cursor.moveToNext()){
        namelist.put(cursor.getString(ii), 
cursor.getString(cursor.getColumnIndex("bul_name")));
    }
    Iterator entries = namelist.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry thisEntry = (Map.Entry) entries.next();
        wordcombimelist.add(String.valueOf(thisEntry.getKey()));
        meancombimelist.add("- "+String.valueOf(thisEntry.getValue()));
    }

    for (int i = 0; i < wordcombimelist.size(); i++) {
        data.add(new DictObjectModel(wordcombimelist.get(i), 
meancombimelist.get(i)));
    }
    adapter = new CustomAdapter(data);
    recyclerView.setAdapter(adapter);
}
} 

1 Answers1

0

You should use something like this to query data from a database

SQLiteDatabase db = mDbHelper.getReadableDatabase();

// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
    BaseColumns._ID,
    FeedEntry.COLUMN_NAME_TITLE,
    FeedEntry.COLUMN_NAME_SUBTITLE
    };

// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };

// How you want the results sorted in the resulting Cursor
String sortOrder =
    FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";

Cursor cursor = db.query(
    FeedEntry.TABLE_NAME,   // The table to query
    projection,             // The array of columns to return (pass null to get all)
    selection,              // The columns for the WHERE clause
    selectionArgs,          // The values for the WHERE clause
    null,                   // don't group the rows
    null,                   // don't filter by row groups
    sortOrder               // The sort order
    );
Sriram R
  • 2,109
  • 3
  • 23
  • 40