How to convert ListActivity to ListFragment? - android

i have a database which i created in Sqlite database browser and using a library to use that database for populating my lists in ListActivity. now to i want to convert my ListActivity to ListFragment...
here is the code...
code for DataBaseHelper
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DataBaseHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "dictionary.db";
private static final int DATABASE_VERSION = 1;
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getDictionary() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"0 _id", "dream_title", "dream_meaning"};
String sqlTables = "dictionary";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
c.moveToFirst();
return c;
}
}
code for MainActivity
public class MainActivity extends ListActivity {
private Cursor dictionary;
private DataBaseHelper db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DataBaseHelper(this);
dictionary = db.getDictionary(); // you would not typically call this on the main thread
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
dictionary,
new String[] {"dream_title"},
new int[] {android.R.id.text1});
getListView().setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
dictionary.close();
db.close();
}
}
Any help will be appreciable

ListFragment uses setListAdapter. I think that's all you would need to change.

Related

Android SQLiteAssetHelper Database doesn't open

I am trying to connect SQLite database in Android Studio through SQLiteAssetHelper, I have tried everything, but it is showing ... Unable to Open Database.
I don't know what is the problem here. I am new to android development.
I have seen other question's answers, but it couldn't help me.
This is my DB Class:
public class MyDB extends SQLiteAssetHelper {
private static final String DB_NAME="Demo.db";
private static final int DB_ver=1;
//private static MyDB myDB=null;
public MyDB(Context context) {
super(context, DB_NAME, null, DB_ver);
}
}
this is DB Access Class:
public class OpenDBHelper {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static OpenDBHelper openDBHelper ;
private OpenDBHelper(Context context)
{
this.openHelper = new MyDB(context);
}
public static OpenDBHelper getInstance(Context context)
{
if(openDBHelper==null)
{
openDBHelper=new OpenDBHelper(context.getApplicationContext()) ;
}
return openDBHelper;
}
public SQLiteDatabase openwrite()
{
this.db= openHelper.getReadableDatabase();
return db;
}
}
and this is the main activity where I am trying to load the data in listview:
public class MainActivity extends AppCompatActivity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.lv_main);
loadStudents();
}
public void loadStudents()
{
ArrayList<HashMap<String, String>> userList = GetAllStudents();
ListAdapter adapter = new SimpleAdapter(this, userList, R.layout.lv_row,new String[]{"name","cast","phone"}, new int[]{R.id.tv_name, R.id.tv_cast, R.id.tv_phone});
lv.setAdapter(adapter);
}
//GEt All Students to listview
public ArrayList<HashMap<String, String>> GetAllStudents(){
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
OpenDBHelper open= OpenDBHelper.getInstance(this);
SQLiteDatabase db=open.openwrite();
String query = "SELECT * FROM tbl_bio";
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount()>0) {
while (cursor.moveToNext()) {
HashMap<String, String> user = new HashMap<>();
user.put("name", cursor.getString(1));
user.put("cast", cursor.getString(2));
user.put("phone", cursor.getString(3));
//user.put("pass", cursor.getString(4));
userList.add(user);
}
}
return userList;
}
}

Android CursorAdapter not updating all fields

I have strange problem with my android app. I have some data and I saved that data in SQLite Database. And in this fragment I try to read my data from table using SimpleCursorAdapter
public class LogFragment extends Fragment{
private static SQLiteDatabase db;
private static SQLiteOpenHelper helper;
private static Context context;
private static ListView listView;
private static String senderOrReceiver;
private static SimpleCursorAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
adapter = new SimpleCursorAdapter(context, R.layout.log_message, null,
new String[]{Constants.COMMAND, Constants.VALUE, Constants.TIME_STAMP, Constants.MESSAGE_ID, Constants.SESSION_ID, Constants.PARAMS},
new int[]{R.id.command, R.id.value, R.id.time_stamp, R.id.message_id, R.id.session_id, R.id.params}, 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_log, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
listView = (ListView) view.findViewById(R.id.listView);
}
#Override
public void onDestroy() {
super.onDestroyView();
if(db != null){
db.close();
}
}
public static void readFromDatabase(String sender){
senderOrReceiver = sender;
new DatabaseTalker().execute();
}
private static class DatabaseTalker extends AsyncTask <Void, Void, Cursor>{
#Override
protected Cursor doInBackground(Void... params) {
helper = new Database(context);
db = helper.getReadableDatabase();
return db.query(Constants.TABLE_NAME, null, null, null, null, null, null);
}
#Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
adapter.changeCursor(cursor);
listView.setAdapter(adapter);
}
}
}
and here's what I got in my ListView . I have six fields (Command, Value, Time Stamp, MessageID, SessionID, Params) and as you can see only one field is filled (for example) Command: On, Value: , Time Stamp: , MessageID: , SessionID: , Params: . and so on... Why I get this result?
EDIT:
Here how I write my data to database
public void addInfo(Information info){
SQLiteDatabase db = this.getWritableDatabase();
addToTable(db, Constants.COMMAND, info.getCommand());
addToTable(db, Constants.VALUE, info.getValue());
addToTable(db, Constants.TIME_STAMP, info.getTimeStamp());
addToTable(db, Constants.MESSAGE_ID, info.getMessageID());
addToTable(db, Constants.SESSION_ID, info.getSessionID());
addToTable(db, Constants.PARAMS, info.getParams());
db.close();
}
private static void addToTable(SQLiteDatabase db, final String TAG, String value){
ContentValues values = new ContentValues();
values.put(TAG, value);
db.insert(Constants.TABLE_NAME, null, values);
}
Your each addToTable() call inserts a new row that contains just one column value.
To insert a row with all the values, add the values to the same ContentValues and call insert() once.

The method is undefined in fragment android spinner sqlite

I have a spinner. I want to load data from sqlite. I have try to load data with Activity class, it work but i want to load it in Fragment class and i got the method is undefined. There is any wrong ? What should i do ??
Sorry for my bad english..
This is Fragment class
public class InfoJadwal extends Fragment {
private DatabaseHandler dbhelper;
private SQLiteDatabase db = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbhelper = new DatabaseHandler(getActivity());
db = dbhelper.getWritableDatabase();
dbhelper.delAllData(db);
dbhelper.generateData(db);
View rootView = inflater.inflate(R.layout.info_jadwal, container,
false);
loadDataSpinner();
return rootView;
}
private void loadDataSpinner() {
Cursor wisataCursor;
Spinner colourSpinner = (Spinner) getView().findViewById(
R.id.spin_tujuan);
wisataCursor = dbhelper.fetchAllWisata(db);
startManagingCursor(wisataCursor);
String[] from = new String[] { dbhelper.TUJUAN };
int[] to = new int[] { R.id.tvDBViewRow };
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(this,
R.layout.db_view_row, wisataCursor, from, to);
colourSpinner.setAdapter(wisataAdapter);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
db.close();
} catch (Exception e) {
}
}
}
And this is class for DatabaseHandler.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "medantrain";
public static final String TUJUAN = "tujuan";
public static final String KEY_ID = "_id";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS KOTA");
db.execSQL("CREATE TABLE if not exists KOTA (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "TUJUAN TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(TUJUAN, "Binjai");
db.insert("KOTA", TUJUAN, cv);
cv.put(TUJUAN, "Rantau Prapat");
db.insert("KOTA", TUJUAN, cv);
cv.put(TUJUAN, "Tebing Tinggi");
db.insert("KOTA", TUJUAN, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete("KOTA", null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query("KOTA", new String[] { KEY_ID, TUJUAN }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
replace
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(this,R.layout.db_view_row, wisataCursor, from, to);
with
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(getActivity(),R.layout.db_view_row, wisataCursor, from, to);
and replace
startManagingCursor(wisataCursor);
with
getActivity().startManagingCursor(wisataCursor);
but startManagingCursor(Cursor) in Activity is deprecated. see docs for more info http://developer.android.com/reference/android/app/Activity.html#startManagingCursor%28android.database.Cursor%29
SimpleCursorAdapter requires a Context reference but you are passing this which means a Fragment reference.

Having an error connecting to my SQLite database

The user is looking at a list LibraryFragment and clicks one of the options (Item1 or Item2), from there I wanted to show another list (GFragment) that is created dynamically from the items received from the database. In the logCat I get this error:
08-30 13:56:54.087: E/SqliteDatabaseCpp(22622): sqlite3_open_v2("/data/data/j.j.l.library.v11/databases/library_dev.db", &handle, 1, NULL) failed
Failed to open the database. Closing it.
Does anyone know what is wrong with the code or why it is doing this?
The code I am using for the database is:
public class DatabaseHelper {
private static String DB_PATH = "/data/data/j.j.l.library.v11/databases/";
private static String DB_NAME = "library_dev.db";
private SQLiteDatabase myDataBase;
public DatabaseHelper(){
}
//Open the database.
public void openDatabase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
//Return the columns we want.
public List<String> getQueryColumn(String tableName, String[] columns){
Cursor cursor;
List<String> info = new ArrayList<String>();
cursor = myDataBase.query(tableName, columns, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
info.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return info;
}
//Close the Database.
public void closeDatabase() throws SQLException{
myDataBase.close();
}
}
Another List I am trying to create dynamically from the database:
public class GFragment extends ListFragment {
private DatabaseHelper gList;
public static final String GROLE = "role";
public static final String[] ROLENAME = {"name"};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
gList = new DatabaseHelper();
gList.openDatabase();
List<String> values = gList.getQueryColumn(GROLE, ROLENAME);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values));
gList.closeDatabase();
}
}
This is the list the user is looking at right before there is a call to retrieve the dynamic list from the database:
public class LibraryFragment extends ListFragment{
String[] libraryList = {"Item1", "Item2"};
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, libraryList));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
//Get the position the user clicked.
Fragment newFragment = null;
String listPosition = libraryList[position];
getListView().setItemChecked(position, true);
if(listPosition.equals("Item1")){
newFragment = new GFragment();
}else if (listPosition.equals("Item2")){
newFragment = new ITFragment();
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.myFragments, newFragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
}
It's because you don't create this database library_dev.db, so it's empty, resulting in a NULL reference; a closing operation is taken afterward.
You need to handle the creation/upgrade/remove of the database in a class which should extends from SQLiteOpenHelper first. Then use this class to get your database:
public class MyDatabaseHelper extends SQLiteOpenHelper { // blah...database create/upgrade handling }
MyDatabaseHelper myHelper = new MyDatabaseHelper(yourContext);
SQLiteDatabase myDatabase = myHelper.getReadableDatabase(); // now you can use `myDatabase` freely
You can refer to a proper guideline for this at: http://www.vogella.com/articles/AndroidSQLite/article.html

Unable to bind data by query from DB to spinner

Hey guys I already have a data in my database but I want to show it into spinner I'm really new to this problem, so would you guys help me to solve this problem,or I would prefer if you write the correct code for me :) Thanks in advance.
First this is my DB class
public class DBAdapter
{
public static final String UPDATEDATE = "UpdateDate";
//Declare fields in PersonInfo
public static final String ROWID = "_id";
public static final String PT_FNAME = "Username";
public static final String PT_COLORDEF = "ColorDeficiency";
private static final String DATABASE_CREATE =
"create table PersonInfo (_id integer primary key autoincrement, "
+ "Username text not null, ColorDeficiency text);";
private static final String DATABASE_NAME = "CAS_DB";
private static final String tbPerson = "PersonInfo";
private static final int DATABASE_VERSION = 1;
private final Context databaseContext;
private final Context context;
private DatabaseHelper DBHelper;
public SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
databaseContext = ctx;
}
//start database helper
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor all(Activity activity){
String[] from ={ROWID,PT_FNAME,PT_COLORDEF};
String order = PT_FNAME;
Cursor cursor =db.query(tbPerson, from, null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
In another class
private DBAdapter db;
private Spinner spinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.greeting);
initComponent();
db = new DBAdapter(this);
Cursor c = db.all(this);
SimpleCursorAdapter CursorAdapter = new SimpleCursorAdapter(
this,android.R.layout.simple_spinner_item,c,
new String[]{DBAdapter.PT_FNAME},new int[]{android.R.id.list});
CursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(CursorAdapter);
try changing
new int[]{android.R.id.list}
to
new int[]{android.R.layout.simple_spinner_item}

Categories

Resources