No data appearing in ListView, using SimpleCursorAdapter - android

With the below code, nothing appears in the ListActivity as I would expect.
No errors are shown in logcat.
Arrival.java
package one.two;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Arrival extends ListActivity
{
private ListView listView;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
ArrayList<String> retList = new ArrayList<String>();
System.out.println("Start onCreate Function\n");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("In onCreate Function\n");
System.out.println("In of GetData\n");
DBAdapter db = new DBAdapter(this);
System.out.println("DB Open\n");
db.open();
System.out.println("DB Opened\n");
retList = getData();
System.out.println("Out of GetData\n");
// force count no. of records in table
// dump to check index
int cnt = 2;
int i=0;
for (i = 0; i<cnt; i++)
System.out.println(retList.toString());
System.out.println("Array 2 String\n");
Cursor c = db.getCursor();
String[] from = new String[] {DBAdapter.status};
int[] to = new int[] {R.id.txt1};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.listtext, c, from, to);
this.setListAdapter(mAdapter);
System.out.println("Show List\n");
db.close();
}
public static ArrayList<String> getData()
{
ArrayList<String> items = DBAdapter.getAllTitles();
System.out.println("Return a LIST titles\n");
return items;
}
}
DBAdapter.java
package one.two;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.util.ArrayList;
public class DBAdapter
{
public static String status = "status";
public String id = "id";
public String arrival = "arrival";
public String destination = "destination";
public String ferry = "ferry";
private static String DB_PATH = "/data/data/one.two/databases/";
private static final String DATABASE_NAME = "ferry.db";
private static final String DATABASE_TABLE = "port";
public static Context context;
public Cursor c;
public static SQLiteDatabase DbLib;
//overloaded non-null constructor
public DBAdapter(Context context)
{
DbLib = context.openOrCreateDatabase(DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY,null);
System.out.println("OpenOrCreateDB Done");
}
public class DatabaseHelper extends SQLiteOpenHelper
{
Context context;
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}//end constructor DatabaseHelper
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
}//end onUpgrade()
#Override
public void onCreate(SQLiteDatabase db)
{
}//end onCreate()
}// end class DatabaseHelper
private static DatabaseHelper DBHelper;
//private static SQLiteDatabase DbLib;
private static final int DATABASE_VERSION = 1;
public static ArrayList<String> getAllTitles()
{
ArrayList<String> port = new ArrayList<String>();
Cursor c=null;
c = DbLib.query("port",
new String[] { "status", "id", "arrival",
"destination", "ferry" }, null, null,
null, null, null);
try {
if (c!=null) { // start - when there is at least 1 record
System.out.println("Cursor is NOT NULL");
int i =0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
// Debug Stm
System.out.println("Record No. "+i);
System.out.println(c.getString(0));
System.out.println(c.getString(1));
System.out.println(c.getString(2));
System.out.println(c.getString(3));
System.out.println(c.getString(4));
// Assign database cursor.records to arraylist
port.add(i,c.getString(0));
port.add(i,c.getString(1));
port.add(i,c.getString(2));
port.add(i,c.getString(3));
port.add(i,c.getString(4));
i = i + 1;
}
} // end - where there is at least 1 record
} finally {
if (c!=null) {
c.close();
}
}
return port;
}//end getAllTitles()
public void open() {
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
DbLib = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public Cursor getCursor(){
return c;
}
public void close()
{
DbLib.close();
}
}//end class DBAdapter
main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- snip... -->
<ListView
android:layout_width="wrap_content"
android:layout_y="132dip"
android:layout_x="150dip"
android:id="#android:id/list"
android:layout_height="wrap_content">
</ListView>

At a quick guess, I'd say it's because you're closing the database connection in your onCreate method, before the list adapter has a chance to read any data from it. The Cursor itself doesn't contain all the data as soon as you run a query.
If you want your Activity to handle closing the database connection, you should do so in the onPause or onDestroy method.

Related

getContext().getContentResolver().notifyChange(uri, null) didn't notify cursor

i'm trying to undestand Content Provider,but i stuck in one thing,
notification of cursor didn't work,if i update cursor in query method everything works fine.Where i get wrong.Thank you! This is full source code
https://github.com/denmariupol/StartAndroid/tree/master/lesson101_contentprovider_creation_h/src/main
MainActivity
package com.example.lesson101_contentprovider_creation_h;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.lesson101_contentprovider_creation_h.databinding.ActivityMainBinding;
import com.example.lesson101_contentprovider_creation_h.interfaces.IUpdateCursor;
import com.example.lesson101_contentprovider_creation_h.fragments.Insert;
import com.facebook.stetho.Stetho;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity implements IUpdateCursor {
public final static Uri PROVIDER_URI = Uri.parse("com.example.lesson101_contentprovider_creation_h");
private Cursor cursor;
private MyAdapter scAdapter;
private ActivityMainBinding mainActivity;
private OnClickListener clickListener;
private int colId;
private int colText;
private ArrayList<Integer> chekedItems = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stethoInit();
mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
cursor = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null, null);
}
colId = cursor.getColumnIndex(MyProvider.ID);
colText = cursor.getColumnIndex(MyProvider.TEXT);
String[] from = new String[]{MyProvider.ID, MyProvider.TEXT};
int[] to = new int[]{R.id.itemId, R.id.itemText};
scAdapter = new MyAdapter(this, R.layout.item, cursor, from, to, 0);
mainActivity.listItem.setAdapter(scAdapter);
scAdapter.notifyDataSetChanged();
mainActivity.listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final View v = view;
final LinearLayout itemUpdateLayout = (LinearLayout)view.findViewById(R.id.itemUpdateLayout);
final LinearLayout itemViewLayout = (LinearLayout)view.findViewById(R.id.itemViewLayout);
TextView idView = (TextView)view.findViewById(R.id.itemId);
TextView textView = (TextView)view.findViewById(R.id.itemText);
final EditText editText = (EditText)view.findViewById(R.id.updateTextField);
Button updateButton = (Button)view.findViewById(R.id.updateRecButton);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("!!!","onTextChanged -> "+s.toString());
// ed
}
#Override
public void afterTextChanged(Editable s) {
}
});
final String updId = idView.getText().toString();
updateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
String text = editText.getText().toString();
Log.d("!!!","clicked text -> "+editText.getText().toString());
if(text.length() > 0) {
cv.put(MyProvider.TEXT, text);
Uri newUri = ContentUris.withAppendedId(MyProvider.CONTENT_URI,Long.valueOf(updId));
getContentResolver().update(newUri, cv,null,null);
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// updateCursor(cursor);
}
itemUpdateLayout.setVisibility(View.GONE);
itemViewLayout.setVisibility(View.VISIBLE);
}
});
editText.setText(textView.getText());
itemUpdateLayout.setVisibility(View.VISIBLE);
itemViewLayout.setVisibility(View.INVISIBLE);
}
});
mainActivity.insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment insertFragment = new Insert();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, insertFragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
mainActivity.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(chekedItems.size() > 0){
for (int i = 0; i < chekedItems.size(); i++) {
Uri newUri = ContentUris.withAppendedId(MyProvider.CONTENT_URI,chekedItems.get(i));
getContentResolver().delete(newUri,null,null);
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// updateCursor(cursor);
}
chekedItems.clear();
}else{
Toast.makeText(MainActivity.this,"Nothing selected",Toast.LENGTH_SHORT).show();
}
}
});
}
private void stethoInit() {
// Create an InitializerBuilder
Stetho.InitializerBuilder initializerBuilder =
Stetho.newInitializerBuilder(this);
// Enable Chrome DevTools
initializerBuilder.enableWebKitInspector(
Stetho.defaultInspectorModulesProvider(this)
);
// Enable command line interface
initializerBuilder.enableDumpapp(
Stetho.defaultDumperPluginsProvider(this)
);
// Use the InitializerBuilder to generate an Initializer
Stetho.Initializer initializer = initializerBuilder.build();
// Initialize Stetho with the Initializer
Stetho.initialize(initializer);
}
#Override
public void updateCursor(Cursor newCusor) {
scAdapter.changeCursor(newCusor);
scAdapter.notifyDataSetChanged();
//hide keyboard
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
private class MyAdapter extends SimpleCursorAdapter{
private int layout;
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
final String id = cursor.getString(colId);
String title = cursor.getString(colText);
TextView idView = (TextView)view.findViewById(R.id.itemId);
idView.setText(id);
TextView textView = (TextView)view.findViewById(R.id.itemText);
textView.setText(title);
CheckBox checkBox = (CheckBox)view.findViewById(R.id.itemCheckBox);
checkBox.setChecked(false);
checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!chekedItems.contains(Integer.valueOf(id))){
chekedItems.add(Integer.valueOf(id));
}else{
chekedItems.remove(chekedItems.indexOf(Integer.valueOf(id)));
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = getLayoutInflater().inflate(layout,parent,false);
return view;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
}
}
Insert Fragment
package com.example.lesson101_contentprovider_creation_h.fragments;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.lesson101_contentprovider_creation_h.MainActivity;
import com.example.lesson101_contentprovider_creation_h.MyProvider;
import com.example.lesson101_contentprovider_creation_h.R;
import com.example.lesson101_contentprovider_creation_h.databinding.FragmentInsertBinding;
import com.example.lesson101_contentprovider_creation_h.interfaces.IUpdateCursor;
/**
* A simple {#link Fragment} subclass.
*/
public class Insert extends Fragment{
Activity activity;
public Insert() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.activity = (Activity)context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FragmentInsertBinding insertBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_insert,container,false);
View v = insertBinding.getRoot();
insertBinding.insertRecButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
String text = insertBinding.insertTextField.getText().toString();
if(text.length() > 0) {
cv.put(MyProvider.TEXT, text);
getContext().getContentResolver().insert(MyProvider.CONTENT_URI, cv);
getActivity().getSupportFragmentManager().beginTransaction().remove(Insert.this).commit();
insertBinding.insertTextField.clearFocus();
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContext().getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// ((IUpdateCursor)activity).updateCursor(cursor);
}
}
});
// Inflate the layout for this fragment
return v;
}
// public interface IUpdateCursor{
// void updateCursor(Cursor newCursor);
// }
}
MyProvider
package com.example.lesson101_contentprovider_creation_h;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by den on 2017-03-31.
*/
public class MyProvider extends ContentProvider{
private final String DB_NAME = "my";
private int DB_VERSION = 1;
private static final String AUTHORITY = "com.example.lesson101_contentprovider_creation_h";
private static final String PATH = "table";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH);
public static final String DB_TABLE = "MYTABLE";
public static final String ID = "_id";
public static final String TEXT = "text";
private final String CREATE_DB = "CREATE TABLE " + DB_TABLE + " ("
+ ID + " integer primary key autoincrement, "
+ TEXT + " text);";
private DBHelper dbHelper;
private SQLiteDatabase database;
private static final int TABLE = 1;
private static final int TABLE_ID = 2;
static final String CONTACT_CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd."
+ AUTHORITY + "." + PATH;
private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, PATH, TABLE);
uriMatcher.addURI(AUTHORITY, PATH + "/#", TABLE_ID);
}
#Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection,
#Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
sortOrder = ID;
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
sortOrder = TEXT;
break;
}
Cursor cursor = database.query(DB_TABLE,projection,selection,selectionArgs,null,null,sortOrder);
Log.d("!!!","query -> "+uri.toString());
cursor.setNotificationUri(getContext().getContentResolver(),CONTENT_URI);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
return CONTACT_CONTENT_ITEM_TYPE;
}
return null;
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues values) {
database = dbHelper.getWritableDatabase();
Log.d("!!!","insert -> "+uri.toString());
if(uriMatcher.match(uri) != TABLE)
throw new IllegalArgumentException("Wrong URI: "+uri);
long id = database.insert(DB_TABLE,null,values);
Uri resultUri = ContentUris.withAppendedId(CONTENT_URI,id);
Log.d("!!!","insert after -> "+resultUri.toString());
getContext().getContentResolver().notifyChange(resultUri,null);
return resultUri;
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, #Nullable String[] selectionArgs) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
selection = ID + " = " + id;
break;
}
int c = database.delete(DB_TABLE,selection,selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return c;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues values, #Nullable String selection, #Nullable String[] selectionArgs) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
selection = ID + " = " +id;
Log.d("!!!",id);
break;
}
int c = database.update(DB_TABLE,values,selection,null);
getContext().getContentResolver().notifyChange(uri, null);
return c;
}
private class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
updateDB(db,0,DB_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private void updateDB(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion < 1)
db.execSQL(CREATE_DB);
}
}
}
Did you check if the uri used in setNotificationUri is matching the ones used in the getContext().getContentResolver().notifyChange()?
Cursor.setNotificationUri()
will register for the underline uri for the
getContext().getContentResolver().notifyChange(uri, null);
which is called when such as at ContentProvider's insert(), update() and delete() calls, so the Cursor (has setNotificationUri()) will be notified.
If you are using CursorAdapter, by default, CursorAdapter objects will get this notification issued by getContext().getContentResolver().notifyChange.
Another thing to make sure not to do cursor.close(), the close() will cause unregister the content observer which was registered by CursorLoader. And the cursor closing is managed by CursorLoader.

(Android) What have I done wrong in my code while trying to populate a spinner with database info

I am make data show that up in a spinner that consists of food objects (name, calories) that gets created in my main, and then make these objects (just the name for now) show up in a spinner that is on the activity. This activity will actually become a part of a larger program, and eventually I want to be able to allow the user the ability to "count" the total amount of calories that they have eaten by added up all the foods selected. For now, I just want to be able to make the foods appear so I can move further along. However, whenever I go to run it, my app just crashes with no error message stated the problem. If anyone knows what I need to do, please help. My code below:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends ActionBarActivity implements
OnItemSelectedListener {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Foods food1 = new Foods("Apple", "80");
Foods food2 = new Foods("Bagel", "200");
Foods food3 = new Foods("Biscuit", "65" );
Foods food4 = new Foods("Banana", "105");
Foods food5 = new Foods("Beef Roast", "205");
Foods food6 = new Foods("Corn", "60");
Foods food7 = new Foods("Cereal", "120");
Foods food8 = new Foods("Chicken", "240");
Foods food9 = new Foods("Eggs", "105");
Foods food10 = new Foods("Cabbage", "30");
Foods food11 = new Foods("Oatmeal", "160");
Foods food12 = new Foods("Pancake", "60");
Foods food13 = new Foods("Pears", "100");
Foods food14 = new Foods("Pizza", "290");
Foods food15 = new Foods("Ice Cream", "270");
Foods food16 = new Foods("Pork Chop", "335");
Foods food17 = new Foods("Ham", "250");
Foods food18 = new Foods("Ribs", "270");
Foods food19 = new Foods("Popcorn", "55");
Foods food20 = new Foods("Baked Potato", "220");
Foods food21 = new Foods("Rice", "225");
Foods food22 = new Foods("Salad", "85");
Foods food23 = new Foods("Spaghetti", "360");
Foods food24 = new Foods("Bread", "65");
Foods food25 = new Foods("Fish", "175");
dbHandler.addFood(food1);
dbHandler.addFood(food2);
dbHandler.addFood(food3);
dbHandler.addFood(food4);
dbHandler.addFood(food5);
dbHandler.addFood(food6);
dbHandler.addFood(food7);
dbHandler.addFood(food8);
dbHandler.addFood(food9);
dbHandler.addFood(food10);
dbHandler.addFood(food11);
dbHandler.addFood(food12);
dbHandler.addFood(food13);
dbHandler.addFood(food14);
dbHandler.addFood(food15);
dbHandler.addFood(food16);
dbHandler.addFood(food17);
dbHandler.addFood(food18);
dbHandler.addFood(food19);
dbHandler.addFood(food20);
dbHandler.addFood(food21);
dbHandler.addFood(food22);
dbHandler.addFood(food23);
dbHandler.addFood(food24);
dbHandler.addFood(food25);
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
}
private void loadSpinnerData()
{
List<String> foodnames = dbHandler.getFoodNames();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, foodnames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String food = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + food,
Toast.LENGTH_LONG).show();
}
}
public class Foods {
private int _id;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
private String name;
private String calories;
public Foods(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCalories() {
return calories;
}
public void setCalories(String calories) {
this.calories = calories;
}
public Foods(String foodname, String foodcalories){
this.name = foodname;
this.calories = foodcalories;
}
}
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
import java.util.ArrayList;
import java.util.List;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "BroncoWellness.db";
public static final String TABLE_FOODS = "food";
public static final String COLUMN_FOOD_ID = "_id";
public static final String COLUMN_FOOD_NAME = "foodname";
public static final String COLUMN_FOOD_CALORIES = "foodcalories";
#Override
public void onCreate(SQLiteDatabase db) {
String Foodquery = "CREATE TABLE " + TABLE_FOODS + "(" +
COLUMN_FOOD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FOOD_NAME + " TEXT " +
COLUMN_FOOD_CALORIES + " TEXT " +
");";
db.execSQL(Foodquery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOODS);
onCreate(db);
}
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context,DATABASE_NAME ,factory, DATABASE_VERSION);}
public void addFood(Foods food){
ContentValues values = new ContentValues();
values.put(COLUMN_FOOD_NAME, food.getName());
values.put(COLUMN_FOOD_CALORIES, food.getCalories());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FOODS,null,values);
db.close();
}
public List<String> getFoodNames(){
List<String> foodnames = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_FOODS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
foodnames.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return foodnames;
}
}
In your code, you are initializing the spinner outside the onCreate() method. It should be like this-
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
//your code
}
This will solve your issue.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// **Spinner element here**
spinner = (Spinner) findViewById(R.id.spinner);

LoadMoreListView Fragment implementation using sqlite database

I need to load a large dataset from a sqlite database. This will take too much of time to load the data. Therefore I used LoadMorelistView library to load with pagination.
I followed below link and successfully load the data from hard coded list.
pull to refresh and loadmore listview like facebook
But when I tried to load from sqlite database I got the following error.
// The constructor ArrayAdapter(Activity, int, ArrayList) is Undefined
I searched the google as well as stackoverflow. But unable to find a solution.
Please find the code snippet which I used to load the data,
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<Customer> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the database helper class. (DatabaseHelper)
package com.load.more.list.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//database information
private static final String DATABASE_NAME = "fmcgDB.db";
private static final int DATABASE_VERSION = 1;
//TABLES
//Customer table
public static final String TABLE_CUSTOMER = "customer";
public static final String CUSTOMER_ID = "customer_id";
public static final String CUSTOMER_NO = "customer_no";
public static final String CUSTOMER_NAME = "customer_name";
public static final String CUSTOMER_CONTACT_PERSON = "customer_contact_person";
public static final String CUSTOMER_TELEPHONE_NO = "customer_telephone_no";
public static final String CUSTOMER_ADDRESS = "customer_address";
public static final String CUSTOMER_LONGITUDE = "customer_longitude";
public static final String CUSTOMER_LATITUDE = "customer_latitude";
public static final String CUSTOMER_TLP = "customer_tlp";
public static final String CUSTOMER_REP_ID = "customer_rep_id";
public static final String CUSTOMER_CATEGORY_ID = "cc_id";
public static final String CUSTOMER_OUTLET_TYPE_ID = "ot_id";
public static final String CUSTOMER_PERIPHERY_TYPE_ID = "pt_id";
public static final String CUSTOMER_VOLUME_ID = "volume_id";
public static final String CUSTOMER_MARKET_ID = "market_id";
private static final String CREATE_CUSTOMER_TABLE = "CREATE TABLE " + TABLE_CUSTOMER + " ("
+ CUSTOMER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CUSTOMER_NO + " TEXT, "
+ CUSTOMER_NAME + " TEXT, "
+ CUSTOMER_CONTACT_PERSON + " TEXT, "
+ CUSTOMER_TELEPHONE_NO + " TEXT, "
+ CUSTOMER_ADDRESS + " TEXT, "
+ CUSTOMER_LONGITUDE + " REAL, "
+ CUSTOMER_LATITUDE + " REAL, "
+ CUSTOMER_TLP + " INTEGER, "
+ CUSTOMER_REP_ID + " INTEGER, "
+ CUSTOMER_CATEGORY_ID + " INTEGER, "
+ CUSTOMER_OUTLET_TYPE_ID + " INTEGER, "
+ CUSTOMER_PERIPHERY_TYPE_ID + " INTEGER, "
+ CUSTOMER_VOLUME_ID + " INTEGER, "
+ CUSTOMER_MARKET_ID + " INTEGER "
+");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase arg0) { // this order must be followed when creating tables
arg0.execSQL(CREATE_CUSTOMER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
arg0.execSQL("DROP TABLE IF EXISTS " + CREATE_CUSTOMER_TABLE);
onCreate(arg0);
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<Customer> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<Customer> customersList = new ArrayList<Customer>();
// Newly Added
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
/*cursor = fmcgDB.query(dbHelper.TABLE_CUSTOMER, null, null, null,
null, null, null);
*/
while (cursor.moveToNext()) {
Customer customer = new Customer();
customer.setCustomer_id(cursor.getInt(cursor.getColumnIndex(dbHelper.CUSTOMER_ID)));
customer.setCustomer_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NO))));
customer.setCustomer_name(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
customer.setCustomer_contact_person(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_CONTACT_PERSON))));
customer.setCustomer_telephone_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_TELEPHONE_NO))));
customer.setCustomer_address(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_ADDRESS))));
customer.setCustomer_longitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LONGITUDE))));
customer.setCustomer_latitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LATITUDE))));
int TLP = cursor.getInt((cursor.getColumnIndex(dbHelper.CUSTOMER_TLP)));
if(TLP == 0){
customer.setCustomer_TLP_member(true);
}else{
customer.setCustomer_TLP_member(false);
}
customersList.add(customer);
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}
Code for the Adapter Class. (CustomerAdapter.java)
package com.load.more.list.control;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.load.more.list.model.Customer;
import com.load.more.list.view.R;
public class CustomerAdapter extends ArrayAdapter<Customer> {
Context context;
ArrayList<Customer> customerList;
public CustomerAdapter(Context context, ArrayList<Customer> customerList){
super(context, R.layout.item_customer, customerList);
this.context = context;
this.customerList = customerList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.item_customer, parent, false);
TextView tvName = (TextView) row.findViewById(R.id.tvRouteCustomerListName);
TextView tvMarket = (TextView) row.findViewById(R.id.tvRouteCustomerListMarket);
TextView tvVolume = (TextView) row.findViewById(R.id.tvRouteCustomerListVolume);
tvName.setText(customerList.get(position).getCustomer_name());
return row;
}
}
Code for the Customer Object. (Customer.java)
package com.load.more.list.model;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class Customer {
private static final String TAG_CUSTOMER = "customers";
private static final String TAG_CUSTOMER_ID = "customer_id";
private static final String TAG_CUSTOMER_NO = "CustomerCode";
private static final String TAG_CUSTOMER_NAME = "CustomerName";
private static final String TAG_CUSTOMER_ADDRESS = "Address1";
private static final String TAG_CUSTOMER_CONTACT_PERSON = "ContactPersonName";
private static final String TAG_CUSTOMER_TELEPHONE_NO = "PhoneNo";
private static final String TAG_CUSTOMER_LATITUDE = "CustomerLatitude";
private static final String TAG_CUSTOMER_LONGITUDE = "CustomerLongitude";
private static final String TAG_CUSTOMER_IS_TLP = "Istlp";
private static final String TAG_CUSTOMER_REP_ID = "";
private static final String TAG_CUSTOMER_PT_ID = "PheriheryId";
private static final String TAG_CUSTOMER_CATEGORY_ID = "CatrgoryId";
private static final String TAG_CUSTOMER_OUTLETTYPE_ID = "OutletTypeId";
private static final String TAG_CUSTOMER_VOLUME_ID = "VolumeId";
private static final String TAG_CUSTOMER_MARKET_ID = "MarketId";
private int customer_id;
private String customer_no;
private String customer_name;
private String customer_contact_person;
private String customer_telephone_no;
private String customer_address;
private double customer_longitude;
private double customer_latitude;
private boolean customer_TLP_member;
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getCustomer_contact_person() {
return customer_contact_person;
}
public void setCustomer_contact_person(String customer_contact_person) {
this.customer_contact_person = customer_contact_person;
}
public String getCustomer_telephone_no() {
return customer_telephone_no;
}
public void setCustomer_telephone_no(String customer_telephone_no) {
this.customer_telephone_no = customer_telephone_no;
}
public String getCustomer_address() {
return customer_address;
}
public void setCustomer_address(String customer_address) {
this.customer_address = customer_address;
}
public double getCustomer_longitude() {
return customer_longitude;
}
public void setCustomer_longitude(double customer_longitude) {
this.customer_longitude = customer_longitude;
}
public double getCustomer_latitude() {
return customer_latitude;
}
public void setCustomer_latitude(double customer_latitude) {
this.customer_latitude = customer_latitude;
}
public boolean isCustomer_TLP_member() {
return customer_TLP_member;
}
public void setCustomer_TLP_member(boolean customer_TLP_member) {
this.customer_TLP_member = customer_TLP_member;
}
public String getCustomer_no() {
return customer_no;
}
public void setCustomer_no(String customer_no) {
this.customer_no = customer_no;
}
}
Can anyone know how to solve this problem? If yes, please help me to solve this problem.
Thanks in advance.
Finally I solved the issue,.
I have changed the type of mListItems to
ArrayList<String> mListItems;
and the return type of getAllCustomersFromTo() to String array.
It solved my issue.
Final source code of the updated classes are shown below.
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<String> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<String> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<String> customersList = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
while (cursor.moveToNext()) {
customersList.add(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}

android: SQLite Db error

hello i am building a SQLite Db for my android application . this is the code :
package com.example.pap_e;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class FeedsDbAdapter {
private final Context mCtx;
private static final String DEBUG_TAG = "RSSDatabase";
private static final int DB_VERSION = 1;
private static final String DB_NAME = "rss_data";
public static String TABLE = "list";
public static final String ID = "_id";
public static final String RSS = "_rss";
public static final String TITLE = "_title";
public static final String PUBDATE = "_pubdate";
public static final String DESCRIPTION = "_description";
public static final String LINK = "_link";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE_TABLE"+TABLE+"("+ID+ "integer PRIMARY KEY AUTOINCREMENT,"+RSS+"text NOT NULL,"
+TITLE+"text NOT NULL,"+PUBDATE+"text NOT NULL,"+DESCRIPTION+"text NOT NULL,"+LINK+"text NOT NULL"+")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);}
}
public FeedsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean updateAnakoinosi(long rowId, String rss, String title,
String pubdate, String description, String link) {
ContentValues args = new ContentValues();
args.put(RSS, rss);
args.put(TITLE, title);
args.put(PUBDATE, pubdate);
args.put(DESCRIPTION, description);
args.put(LINK, link);
return mDb.update(TABLE, args, ID + "=" + rowId, null) > 0;}
public Cursor fetchAllAnakoinoseis() {
return mDb.query(TABLE, new String[] { ID, RSS, TITLE, PUBDATE,
DESCRIPTION,LINK }, null, null, null, null, null); }
}
The thing is that i get an error at public class FeedsDbAdapter that says:"The blank final field mCtx may not have been initialized" but i had it initialized using private final Context mCtx; Am i missing something here ? Thanks a lot in advance!
You didn't initialize the context yet. You have to initialize it inside FeedsDbAdapter constructor like :
public FeedsDbAdapter (Context context){
mCtx = context;
}
first declare FeedsDbAdapter constructor, because you use FeedsDbAdapter class through its constructor in other classes ans the other activity context will assign to this current context.
Change your code to :
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mCtx = context;
}
This question of yours relates to java. This line private final Context mCtx; is just a declaration of field mCtx of type context. And as this field has been declared as final, It has to be iniliazed inside the constructor mCtx = context;. Even if mCtx is not declared as final, it has still to be initialized before being used.
Thats because your class is static... Remove static from your class and change your code to
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mCtx = context;
}

Android SQLiteDatabase returning null (blank) rows

been pulling my hair out with an app I am trying to build. I have tried so many different things, books, ways, youtube tutorials I have lost count! I am building a simple app which shows pictures of aircraft then the user clicks to add it to a learnt list (verified that is working by using toast instead of listview) then clicks another button to view this list.
I have the app returning the correct number of rows but they are all blank! From what I have read this means the rows are null but I can't for the life of me figure what is wrong! I would be forever in the debt of whoever can help :)
Thanks! Here's the code...
(database helper/adapter)
package com.atcapp;
import android.content.ContentValues;
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;
public class DatabaseAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
private static final String TAG = "DatabaseAdapter";
private static final String DATABASE_NAME = "LearntListdb";
private static final String DATABASE_TABLE = "AircraftTable";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table AircraftTable (_id integer primary key autoincrement, "
+ "name text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DatabaseAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public 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) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + "which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS AircraftNames");
onCreate(db);
}
}
// ---opens the database---
public DatabaseAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
// ---insert an aircraft into the database---
public long insertAircraft(String name) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
return db.insert(DATABASE_TABLE, null, initialValues);
}
// ---retrieves all the list---
public Cursor getAllAircraft() {
Cursor c = db.query(DATABASE_TABLE, new String[] {"_id", "name"}, null, null, null, null, null);
return c;
}
}
(List Activity)
package com.atcapp;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class DataView extends ListActivity {
private DatabaseAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aircraftlist);
mDbHelper = new DatabaseAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData(){
Cursor c = mDbHelper.getAllAircraft();
startManagingCursor(c);
String[] from = new String[] {DatabaseAdapter.KEY_ROWID, DatabaseAdapter.KEY_NAME};
int[] to = new int[] {android.R.id.list};
SimpleCursorAdapter myList =
new SimpleCursorAdapter(this, R.layout.list_row, c, from, to);
setListAdapter(myList);
}
}
You need to supply textview ids in your to array. You need to be mapping data from the cursor to views in the adapter.
Look in your list_row layout and use the textview id from there.

Categories

Resources