Android数据库(离线)

时间:2018-04-15 20:55:41

标签: android

我是android的新手,我想要了解“如何在项目中调用.db文件”  从中检索数据(.db包含图像)“我想在我的应用程序中调用它  显示但没有任何访问互联网(离线)

问题是如何从我的本地数据库文件中调用图像

你能帮我找到办法吗

这是我试过这个用于Dictonary和i iwanna Retreive的应用程序用Word&意思是我尝试了单词和意义并且工作得很好但是如何检索要从同一个表中调用的图像

我希望我找到有人帮助我并感谢您提前

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 个答案:

答案 0 :(得分:0)

您应该使用类似的东西来查询数据库中的数据

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
    );
相关问题