lundi 28 septembre 2015

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> listMockData = new ArrayList<ContactItem>();

        String[] names = getResources().getStringArray(R.array.gmo_name_list);
        String[] phones = getResources().getStringArray(R.array.gmo_ph_list);
        String[] mobiles = getResources().getStringArray(R.array.gmo_mob_list);
        String[] emails = getResources().getStringArray(R.array.gmo_email_list);

        for (int i = 0; i < names.length; i++) {
            ContactItem newsData = new ContactItem();
            newsData.setName(names[i]);
            newsData.setPhone(phones[i]);
            newsData.setMobile(mobiles[i]);
            newsData.setEmail(emails[i]);
            listMockData.add(newsData);
        }
        return listMockData;
    }
} 

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 android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {

    //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");
        }
        if (checkDb != null) {
            checkDb.close();
        }
        return checkDb != null;
    }
    //Coping The Data bse
    private void copyDataBase() throws IOException {

        InputStream externalDbStream = context.getAssets().open(DB_NAME);

        String outFileName = DB_PATH + DB_NAME;

        OutputStream localDbStream = new FileOutputStream(outFileName);
        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) {}
}

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.

Aucun commentaire:

Enregistrer un commentaire