Search code examples
androidsqliteandroid-cursoradapter

How to get data from database instead of resource in android


I am trying to get data from database instead of string resource.

Here is my code. where I want to show the data as a ListView. My ListView is now currently working with a custom list adapter.

 import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.rupomkhondaker.sonalibank.adapter.PhoneListAdapter;
import com.rupomkhondaker.sonalibank.model.ContactItem;
import java.util.ArrayList;


public class GMOFragment extends Fragment {
    public GMOFragment(){}

    private ArrayList<ContactItem> phoneItems;
    private PhoneListAdapter adapters;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_gmo, container, false);

        final ArrayList<ContactItem> listData = getListData();

        final ListView listView = (ListView) rootView.findViewById(R.id.gmolistView);
        listView.setAdapter(new PhoneListAdapter(getActivity(), listData));


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                ContactItem newsData = (ContactItem) listView.getItemAtPosition(position);

                Intent intent = new Intent(getActivity(), ContactDetail.class);
                intent.putExtra("DATA_KEY", newsData);
                startActivity(intent);
            }

        });

        return rootView;
    }
    private ArrayList<ContactItem> getListData() {

        ArrayList<ContactItem> datalist = new ArrayList<ContactItem>();
        DataBaseHelper dbHelper=new DataBaseHelper(getActivity());
        datalist = dbHelper.getAllContacts();

        return datalist;
    }
}

Here is My DataBaseHepler.java this create the database successfully !

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.rupomkhondaker.sonalibank.model.ContactItem;

public class DataBaseHelper extends SQLiteOpenHelper {

    private static final String BR_NAME = "BR_NAME";
    private static final String PHONE = "PHONE";
    private static final String MOBILE = "MOBILE";
    private static final String EMAIL = "EMAIL";
    //Set the database path
    public static String DB_PATH;

    //databse string
    public static String DB_NAME;
    public SQLiteDatabase database;
    public final Context context;



    public SQLiteDatabase getDb() {
        return database;
    }

    public DataBaseHelper(Context context, String databaseName) {
        super(context, databaseName, null, 1);
        this.context = context;

        String packageName = context.getPackageName();
        DB_PATH = String.format("//data//data//%s//databases//", packageName);
        DB_NAME = databaseName;
        openDataBase();
    }

    //Create Databse
    public void createDataBase() {
        boolean dbExist = checkDataBase();
        if (!dbExist) {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                Log.e(this.getClass().toString(), "Copying error");
                throw new Error("Error copying database!");
            }
        } else {
            Log.i(this.getClass().toString(), "Database already exists");
        }
    }
    //Check DataBase exsist or not
    private boolean checkDataBase() {
        SQLiteDatabase checkDb = null;
        try {
            String path = DB_PATH + DB_NAME;
            checkDb = SQLiteDatabase.openDatabase(path, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLException e) {
            Log.e(this.getClass().toString(), "Error while checking db");
        }
        //Close database
        if (checkDb != null) {
            checkDb.close();
        }
        return checkDb != null;
    }
    //Coping The Data bse
    private void copyDataBase() throws IOException {

        //find database from asets assets
        InputStream externalDbStream = context.getAssets().open(DB_NAME);

        // File path
        String outFileName = DB_PATH + DB_NAME;

        // setfile name
        OutputStream localDbStream = new FileOutputStream(outFileName);

        // read database
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = externalDbStream.read(buffer)) > 0) {
            localDbStream.write(buffer, 0, bytesRead);
        }

        localDbStream.close();
        externalDbStream.close();

    }

    public SQLiteDatabase openDataBase() throws SQLException {
        String path = DB_PATH + DB_NAME;
        if (database == null) {
            createDataBase();
            database = SQLiteDatabase.openDatabase(path, null,
                    SQLiteDatabase.OPEN_READWRITE);
        }
        return database;
    }
    @Override
    public synchronized void close() {
        if (database != null) {
            database.close();
        }
        super.close();
    }
    @Override
    public void onCreate(SQLiteDatabase db) {}
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}

    //Getting the data from database

    public List<ContactItem> getAllContacts()
    {

        Cursor cursor = database.rawQuery("select BR_NAME,PHONE,MOBILE,EMAIL from SBL_Contact",null);
        ArrayList<ContactItem> listMockData = null;

        if (cursor .moveToFirst()) {
            while (cursor.isAfterLast() == false) {
                ContactItem newsData = new ContactItem();

                newsData.setName(cursor.getString(cursor.getColumnIndex(BR_NAME)));
                newsData.setPhone(cursor.getString(cursor.getColumnIndex(PHONE)));
                newsData.setMobile(cursor.getString(cursor.getColumnIndex(MOBILE)));
                newsData.setEmail(cursor.getString(cursor.getColumnIndex(EMAIL)));
                listMockData.add(newsData);
                cursor.moveToNext();
            }
        }
        return listMockData;
    }
}

Please help me to set data into getListData() from my database instead of resource.

Note: My database has same columns like listarray with same data.


Solution

  • In DatabaseHelper.java Add this method

    public List<ContactItem> getAllContacts()
    {
    Cursor  cursor = db.rawQuery("select * from table",null);
    ArrayList<ContactItem> listMockData;
    
    if (cursor .moveToFirst()) {
    
                while (cursor.isAfterLast() == false) {
                    ContactItem newsData = new ContactItem();
                    newsData.setName(cursor.getString(cursor
                            .getColumnIndex(name))); /DB Column Name : name
                    newsData.setPhone(cursor.getString(cursor
                            .getColumnIndex(phone));
                    newsData.setMobile(cursor.getString(cursor
                            .getColumnIndex(mobile)));
                    newsData.setEmail(cursor.getString(cursor
                            .getColumnIndex(email)));
                    listMockData.add(newsData);
                    cursor.moveToNext();
                }
            }
             return listMockData;
        }
    

    And in your getListData()

     private ArrayList<ContactItem> getListData() {
    
         ArrayList<ContactItem> datalist = new ArrayList<ContactItem>();  
         DatabaseHelper dbHelper=new DatabaseHelper(getActivity());
         datalist=dbHelper.getAllContacts();
    
          return datalist;
    }