i hope you guys can help to solve my problem.
my problem is cant retrieve the multiple value of column. In my database contain 4 columns (id, namaStation, ticket, masa). right now the program only displayed value of namaStation. It mybe because of the toString() method in Comment class because its only return 1 value (namaStation). can help me??
This is my program. ##
1. Call the query.
`public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.add:
List<Comment> values = datasource.query("Kelana Jaya");
adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
break;`
2. The query.
#SuppressWarnings("static-access")
public List<Comment> query(String namaStation){
//List<Comment> comments = new ArrayList<Comment>();
database = dbHelper.getReadableDatabase();
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, MySQLiteHelper.COLUMN_namaStation+"=?",new String[]{namaStation}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// Comment comment = cursorToComment(cursor);
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setNamaStation(cursor.getString(1));
comments.add(comment);
comment.setTicket(cursor.getString(2));
comments.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
3. The Comment class
public class Comment {
private long id;
public String namaStation;
public String ticket;
public String masa;
public String comment;
public int x;
public Comment(){
}
public Comment(long id, String namaStation, String ticket, String masa){
this.id=id;
this.namaStation=namaStation;
this.ticket=ticket;
this.masa=masa;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNamaStation() {
return namaStation;
}
public void setNamaStation(String comment) {
this.namaStation = comment;
}
public String getTicket() {
return ticket;
}
public void setTicket(String comment) {
this.ticket = comment;
}
public String getMasa() {
return masa;
}
public void setMasa(String comment) {
this.masa= comment;
}
// Will be used by the ArrayAdapter in the ListView
public String toString() {
return ticket;
}
}
The display (the layout is not in proper way because im not setup its yet.. :) )
the display
You should do your own ArrayAdapter. You could supply an own layout for your items.
So you could place any column where you want.
Just to join all fields in toString is not "high tech".
It may be sufficient in simple cases
May the following link is helpful
http://www.vogella.de/articles/AndroidListView/article.html#listview_adapterintro
You add the comment twice to the list
comments.add(comment);
comment.setTicket(cursor.getString(1));
comments.add(comment);
sidenote: you can simplify
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// do stuff
cursor.moveToNext();
}
to this
while (cursor.moveToNext()) {
// do stuff
}
And the actual Problem that you see only the name is that you use the wrong Adapter. You need to create your own. Either based on ArrayAdapter if there is a reason to convert your query result into an array - or directly by using a CursorAdapter.
here is an example you can use.
Related
How can I save a query result in a String array?
The query is simple, it's got only one column i.e.:
SELECT NAME FROM MYTABLE
What I want is to store the ids in a String array so I can show them as clickable items in a ListView
Try this
String selectQuery = "SELECT * FROM table";
try {
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<String> ids = new ArrayList<>();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(KEY_ID));
ids.add(id);
} while (cursor.moveToNext());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
Assuming you've already executed your query against a SQLiteDatabase object, and received a Cursor in return, you can iterate through the cursor and save the value of each row to a String[] array like so:
String[] names;
if (cursor.moveToFirst()) {
names = new String[cursor.getCount()];
int colIndex = cursor.getColumnIndex("NAME");
do {
names[cursor.getPosition()] = cursor.getString(colIndex);
} while (cursor.moveToNext());
}
Keep in mind that names will be null if no rows are returned, so make sure you do a null check.
create following method in SQLiteOpenHelper class
public List<String> getAllNames() {
List<String> retData = new ArrayList<String>();
String selectQuery = "SELECT NAME FROM MYTABLE";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
retData.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return retData;
}
then assign this returned list to adapter
The issue with listing id's is that they tend to be meaningless to an end user. Really you want to display user meaningful data, e.g. a name, but to then be able to access the respective id to then efficiently act on a selection from the list presented to a user.
Using an ArrayList is frequently the cause of much frustration, as the list shows what is required but it's then found to be of little use when attempting to use the list beyond displaying data e.g. selecting an item to then do something such as delete or update (if the value is unique within the database it can be used).
As such an ArrayList<your_object> rather then an ArrayList<String> is generally more viable as the source of the List; a Cursor Adapter can also be used as data from the underlying row is easily obtained.
However, there is an issue, unless a Custom Array Adapter is utilised, when using an ArrayList in that the ArrayAdapter class uses the toString method of the object to retrieve the data that is displayed. The simple fix is to provide a suitable toString method in the object, if you don't you will get something long the lines of “SomeType#2f92e0f4”.
Example showing all 3
In the following working example :-
the database (mydb) has 1 table named mytable which has two columns _id (Note must be _id for a CursorAdapter)
There are 3 methods to get the 3 types of list (named accordingly) :-
getAllAsStringArrayList (gets ArrayList)
getAllAsMyTableObjectArrayList (gets ArrayList). Note uses the MyTableObject class (see note in class re overriding the default toString method)
getAllAsCursor
The App, when run, will have 3 lists, the left based upon the first ArrayList, the middle based upon the ArrayList and the last based upon the Cursor.
Clicking an item in any of the lists displays the respective name along with attempts to get the id.
The ArrayList, Left List, fails in this aspect as it can only get the position (i.e. the 4th parameter passed to the listener is the same value as the position).
The ArrayList, middle List, when getting the id from the object (which is retrieved via the getItem(position) method of the Adapter) successfully retrieves the correct id, the 4th parameter is the same as the position, and should not be used.
The Cursor, Right List, retrieves the correct id both via the Cursor and the 4th parameter.
The Code
MyTableObject.java :-
public class MyTableObject {
private long id;
private String name;
public MyTableObject(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
NOTE toString method returns just the name
*/
#Override
public String toString() {
return name;
}
}
DatabaseHelper.java :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_MYTABLE = "mytable";
public static final String COl_MYTABLE_ID = BaseColumns._ID; //<<<< use standard android id column name
public static final String COL_MYTABLE_NAME = "_name";
private static final String mytable_crtsql =
"CREATE TABLE IF NOT EXISTS " + TB_MYTABLE +
"(" +
COl_MYTABLE_ID + " INTEGER PRIMARY KEY, " +
COL_MYTABLE_NAME + " TEXT " +
")";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(mytable_crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addRow(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_MYTABLE_NAME,name);
return mDB.insert(TB_MYTABLE,null,cv);
}
public ArrayList<String> getAllAsStringArrayList() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME)));
}
csr.close();
return rv;
}
public ArrayList<MyTableObject> getAllAsMyTableObjectArrayList() {
ArrayList<MyTableObject> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(new MyTableObject(
csr.getLong(csr.getColumnIndex(COl_MYTABLE_ID)),
csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME))
)
);
}
csr.close();
return rv;
}
public Cursor getAllAsCursor() {
return mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
ListView mListView01,mListVeiw02,mListView03;
ArrayAdapter<String> mAdapterStringArrayList;
ArrayAdapter<MyTableObject> mAdapterMyTableObjectArrayList;
SimpleCursorAdapter mAdapterCursor;
ArrayList<String> mMyTableListAsStrings;
ArrayList<MyTableObject> mMyTableAsObjects;
Cursor mMyTableListAsCursor;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView01 = this.findViewById(R.id.listview01);
mListVeiw02 = this.findViewById(R.id.listview02);
mListView03 = this.findViewById(R.id.listview03);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.addRow("Fred");
mDBHlpr.addRow("Bert");
mDBHlpr.addRow("Harry");
mDBHlpr.addRow("Fred");
//String Array List
mMyTableListAsStrings = mDBHlpr.getAllAsStringArrayList();
mAdapterStringArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsStrings
);
mListView01.setAdapter(mAdapterStringArrayList);
//Object Array List
mMyTableAsObjects = mDBHlpr.getAllAsMyTableObjectArrayList();
mAdapterMyTableObjectArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableAsObjects
);
mListVeiw02.setAdapter(mAdapterMyTableObjectArrayList);
// Cursor
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsCursor,
new String[]{DatabaseHelper.COL_MYTABLE_NAME},
new int[]{android.R.id.text1},
0
);
mListView03.setAdapter(mAdapterCursor);
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = mAdapterStringArrayList.getItem(position);
Toast.makeText(
mContext,
"Name is " + name +
". ID is " + String.valueOf(id) +
" (note may not match)",
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MyTableObject mytable = mAdapterMyTableObjectArrayList.getItem(position);
String name = mytable.getName();
long id_in_object = mytable.getId();
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_object) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListView03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Cursor csr = mAdapterCursor.getCursor(); // already positioned
String name = csr.getString(csr.getColumnIndex(DatabaseHelper.COL_MYTABLE_NAME));
long id_in_cursor = csr.getLong(csr.getColumnIndex(DatabaseHelper.COl_MYTABLE_ID));
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_cursor) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
}
}
I am trying to assign one variable to an ArrayList item inside a cursor but it always returns me last value. Here is the code below.
Getting value from DB
public ArrayList<Bean> getPendingData(String s) {
SQLiteDatabase db = getWritableDatabase();
String[] columns = {name};
String[] selectionArgs = {s};
Cursor cursor = db.query(TABLE_NAME, columns, " pending= ? ", selectionArgs, null, null, null, null);
cursor.moveToFirst();
ArrayList<Bean> pending = new ArrayList<>();
String index0 = null;
Bean bean;
bean = new Bean();
while(!cursor.isAfterLast()) {
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
cursor.close();
return pending;
}
Bean.java
public class Bean {
public static int id; // ans
public static String score;
public static String logo;
public static String image;
public static String getQuestion() {
return question;
}
public static void setQuestion(String question) {
Bean.question = question;
}
public static String question;
public static String description;
public static String option_three;
public static String OptionFour;
}
You should initialize your bean inside the while block:
while(!cursor.isAfterLast()) {
Bean bean = new Bean();
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
The reason is that Java uses objects by reference, so you're always adding the same object to the array "pending", but in following iterations you're changing the value of this object, so finally you have the value of the last iteration.
cursor.isAfterLast() returns true when cursor is at last row position. Adding a ! (not) means perform till it is not at the end of cursor.
so while(!cursor.isAfterLast()){} means while loop will traverse till last record of cursor.
Use this method to fetch all rows returning from cursor.
if (cursor != null) {
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
homeClassesArrayList = new ArrayList<>();
do {
// fetching data
} while (cursor.moveToNext());
}
}
}
What is the best way to save data read from SQLiteDatabase Android, and access them using row number or column name?
Hi Below is my code that I am using to fetch the data but I want to store the rows in some kind of dataset so that i can fetch the data using column number or name . I want to dynamically show these data in a grid in android.
MyDatabaseSQLHelper myDatabaseSQLHelper = new MyDatabaseSQLHelper(this);
SQLiteDatabase mySQLiteDatabase = myDatabaseSQLHelper.getReadableDatabase();
String[] projection = {
Items._ID,
Items.COL_ITEM_NAME,
Items.COL_ITEM_PRICE,
Items.COL_ITEM_QUANTITY,
Items.COL_ITEM_AMOUNT
};
Cursor cursor = mySQLiteDatabase.query(Items.TABLE_NAME,projection,null,null,null,null,null);
To store all rows fetch from database you can store it in Array list of type modal class. for you your modal class could be like this
ItemBeen.java
public class ItemBeen {
String id,itemName,itemPrice,itemQty,itemAmount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getItemQty() {
return itemQty;
}
public void setItemQty(String itemQty) {
this.itemQty = itemQty;
}
public String getItemAmount() {
return itemAmount;
}
public void setItemAmount(String itemAmount) {
this.itemAmount = itemAmount;
}
}
then now in your class make method for get data from database and it store all record to array list and return that array list , like this.
public ArrayList<ItemBeen> getItemList() {
Cursor cur;
ArrayList<itemBeen> itemList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
cur = db.query(Items.TABLE_NAME.TBL_ITEM, projection, null, null, null, null, null);
if (cur != null) {
if (cur.moveToFirst()) {
do {
ItemBeen bean = new ItemBeen();
bean.setId(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ID)));
bean.setItemName(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_NAME)));
bean.setItemPrice(cur.getBlob(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_PRICE)));
bean.setItemQty(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_TQY)));
bean.setItemAmount(cur.getInt(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_AMT)));
itemList.add(bean);
} while (cur.moveToNext());
}
}
return itemList;
}
Now in that class in which you want all item list in that class call this method.declare array list and fetch data.
ArrayList<ItemBeen> itemList = new ArrayList<ItemBeen>();
itemList = DBConstant.dbHelper.getItemList();
and this way in itemList contains all records.
I am trying to make simple android app where the user enter his information and then save it in the database and display the user info using listview. I have three java files: DBHelper.java, MainActivity.java and userInfo.java.
(MainActivity.java) is where the user enters his name and email.
(DBHelper.java) is where the database is created to save the user info.
(userInfo.java) is where the user info can be displayed.
in my app I successfully displayed the data from database using textview, and my question is how I can display the data from database using listview.
updated:
this is the getData() method from DBHelper.java file:
public List<Person> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_EMAIL};
Cursor c = ourDbase.query(TABLE_SCORE, columns, null, null, null, null, null + " DESC");
List<Person> people = new ArrayList<Person>();
int iRow = c.getColumnIndex(KEY_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iEmail= c.getColumnIndex(KEY_EMAIL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
Person p = new Person();
p.setEmail(c.getString(iEmail));
//set other info, like id, name
people.add(person);
}
return people;
}
here is the Person class:
public class Person {
private int ID;
private String NAME;
private String EMAIL;
public Person()
{
ID=0;
NAME="";
EMAIL="";
}
public Person(String qNAME, int qEMAIL) {
NAME = qNAME;
EMAIL= qEMAIL;
}
public int getID()
{
return ID;
}
public String getNAME() {
return NAME;
}
public int getEMAIL() {
return EMAIL;
}
public void setID(int id)
{
ID=id;
}
public void setNAME(String qNAME) {
NAME = qNAME;
}
public void setSCORE(int qEMAIL) {
EMAIL= qEMAIL;
}
}
and this is the code where I get the data from database and set it in textview from userInfo.java:
DbHelper userInfo = new DbHelper(this);
userInfo .open();
String data = userInfo .getData();
userInfo .close();
tv.setText(data);
how I can display the data from database using listview.
Since you dont provide any code about the listview and its adapter, i assume you dont know where to start.
You should create a listview, either with custom-created adapter or basic adapter (from android). After that, add the data from the database to your listview's adapter and use notifyDataSetChanged() to make sure the data is refreshed on the listview.
Simple tutorial : http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
In-depth (recommended) tutorial : http://www.vogella.com/tutorials/AndroidListView/article.html
Alright... I've had enough.
I'm thoroughly frustrated.
So I'd rather ask for help instead of a new monitor.
...And those are VERY expensive here.
Long story short... I have a database. And a table.
private String DEFINE_PROP_TYPES = "CREATE TABLE " + TABLE_PROP_TYPES + "("
+ TABLE_ID + " INTEGER PRIMARY KEY, "
+ TABLE_PROP_TYPE_NAME + " TEXT NOT NULL"
+ ")";
With an 'Adapter' class thrown in for good measure to manage it.
public abstract class DBAdapter
{
static public final String C_COLUMN_ID = "_id";
protected Context context;
protected DBHelper dbHelper;
protected SQLiteDatabase db;
protected String managedTable;
protected String[] columns;
public String getTableManaged()
{
return managedTable;
}
public void setTableManaged(String managedTable)
{
this.managedTable = managedTable;
}
public void setColumns(String[] columns)
{
this.columns = columns;
}
public DBAdapter(Context context)
{
this.context = context;
}
public void close()
{
dbHelper.close();
}
public DBAdapter open() throws SQLException
{
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
public Cursor getList()
{
Cursor c = db.query(true, managedTable, columns, null, null, null, null, null, null);
return c;
}
public long insert(ContentValues reg)
{
return 0;
}
}
public class PropTypesDBAdapter extends DBAdapter
{
static public final String C_TABLE_PROP_TYPES = "PROP_TYPES";
static public final String C_COLUMN_ID = "_id",
C_COLUMN_PROP_TYPES_NAME = "re_prop_type";
public PropTypesDBAdapter(Context context)
{
super(context);
this.setTableManaged(C_TABLE_PROP_TYPES);
this.setColumns(new String[] { C_COLUMN_ID,
C_COLUMN_PROP_TYPES_NAME });
}
public long insert(ContentValues reg)
{
if (db == null)
{
open();
}
return db.insert(C_TABLE_PROP_TYPES, null, reg);
}
}
And besides this pile of cute I have an activity class.
With spinners.
public class PropDetailActivity extends Activity implements LocationListener
{
// insert here some blah-blah constants not needed by spinners
private PropDBAdapter mHouses;
private RatingsDBAdapter mRatings;
private PropTypesDBAdapter mPropTypes;
private Cursor mCursorHouses,
mCursorRatings,
mCursorPropTypes;
long mPropType;
private long mPropId;
private Spinner spinnerRating, spinnerType;
AdapterView.OnItemSelectedListener spnLstPropType, spnLstRating;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_house_detail);
Intent intent = getIntent();
Bundle extra = intent.getExtras();
if (extra == null)
{
return;
}
// Figure all view widgets being retrieved here, including...
spinnerRating = (Spinner) findViewById(R.id.spinnerRating);
spinnerType = (Spinner) findViewById(R.id.spinnerType);
// Create adapter and cursor-y things here
mHouses = new PropDBAdapter(this);
mHouses.open();
// And now, for the juicy, deliciously irritating stuff:
String[] from = new String[] { PropTypesDBAdapter.C_COLUMN_PROP_TYPES_NAME };
int[] to = new int[] { android.R.id.text1 };
mPropTypes = new PropTypesDBAdapter(this);
mPropTypes.open();
mCursorPropTypes = mPropTypes.getList();
#SuppressWarnings("deprecation")
SimpleCursorAdapter adapterPropTypes = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
mCursorPropTypes,
from, /*new String[] { RatingsDBAdapter.C_COLUMN_RATING_NAME }, */
to); /*new int[] { android.R.id.text1 } */
adapterPropTypes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterPropTypes);
spinnerRating.setSelection(pos);
spnLstPropType = new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id)
{
mPropType = id;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) { }
};
spinnerType.setOnItemSelectedListener(spnLstPropType);
private int getItemPositionById(Cursor c, long id, DBAdapter adapter)
{
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
if (c.getLong(c.getColumnIndex(DBAdapter.C_COLUMN_ID)) == id)
{
return c.getPosition();
}
}
return 0;
}
private void query(long id)
{
mCursorHouses = mHouses.getRecord(id);
// Figure values being retrieved and set on their widgets instead of this comment... and now...
mPropType = mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID));
spinnerType.setSelection(
getItemPositionById(
mCursorRatings,
mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID),
mPropTypes
)
);
private void save()
{
ContentValues reg = new ContentValues();
// Read: values being put into 'reg'... eventually it should reach this:
reg.put(PropDBAdapter.C_PROP_TYPE_ID, mPropType);
try
{
if (mFormMode == PropListActivity.C_CREATE)
{
mHouses.insert(reg);
Toast.makeText(PropDetailActivity.this, R.string.house_create_notice, Toast.LENGTH_LONG).show();
}
else if (mFormMode == PropListActivity.C_EDIT)
{
Toast.makeText(PropDetailActivity.this, R.string.house_edit_notice, Toast.LENGTH_LONG).show();
reg.put(PropDBAdapter.C_COLUMN_ID, mPropId);
long resultCode = mHouses.update(reg);
Log.i(this.getClass().toString(), "Database operation result code: " + resultCode);
}
}
catch(SQLException e)
{
Log.i(this.getClass().toString(), e.getMessage());
}
setResult(RESULT_OK);
finish();
}
}
Spinners are being bad boys. Lazy bad boys on top of that.
They do load up the data -a list of real estate property types- they are meant to display.
After some spanking, that is.
But, hoping them to save THE VALUE YOU SELECT to SQLite? And to show THAT EXACT VALUE when fetching stuff back from the database?
Oh, no, no way no how.
They stubbornly stick to displaying always the same value upon activity startup.
So... please... I must draw upon your collective wisdom to save my sorry excuse for a project...
Pleasepleaseplease? :)
(IF you feel like diving into the whole uncut code, here's a GIT repository for you: https://github.com/CruxMDQ/Quoterv3)
Checking your code, I think I found the problem, change the following lines in your query method in PopDetailActivity.java.
For spinnerRating do:
spinnerRating.setSelection(
getItemPositionById(
mCursorRatings,
mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_RATING_ID)),
mRatings
)
);
and for spinnerType do:
spinnerType.setSelection(
getItemPositionById(
mCursorPropTypes,
mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID)),
mPropTypes
)
);
EDIT:
In your query method, you initialize mPropTypeId, with the call to getItemPositionById() but in that call the first parameter should be mCursorPropTypes instead of mCursorHouses
A few things:
(1) I don't really see anywhere above where you actually create a SQLite database or use the SQLiteOpenHelper class to access that data. Take a look at this tutorial. It uses a simple single table set up to store data. Once you create the database it should be easy to read and write from it. Verify that you actually have a database created.
(2) Where are your SQL queries to return the data you're looking for? Even if data is being added you need to make sure you are getting the right data with your Cursor when you're done. If you're getting the same values each time is it possible that you are simply adding new data every time and retrieving the same value with your cursor - i.e. you're not telling the cursor to get the newly added data becuase you keep grabing the same index?
If you need to replace the data that's there you should be using update queries and not inserts.