Cursor query returning 0 - java

I am building an application with database but a problem arises when I am retrieving the values from the database it returns empty (i.e. returned cursor has 0 tuples) and I am sure that database contains some information into it.
I am providing my code please help if you noticed any error.
Fragment where user inputs data to database:
public class FCar extends Fragment implements AdapterView.OnItemSelectedListener {
public FCar() {
}
CarDataBaseAdapter carDataBaseAdapter;
SessionManagement session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflating the view
final View rootView = inflater.inflate(R.layout.fragment_car, container, false);
// declaring stuff, not sure why it has to be final
final Spinner carSpinner;
final EditText editTextDistance, editTextMin;
Button btnSubmitCar;
// create new car database
carDataBaseAdapter = new CarDataBaseAdapter(getActivity());
carDataBaseAdapter = carDataBaseAdapter.open();
SQLiteDatabase x = carDataBaseAdapter.getDatabaseInstance();
session = new SessionManagement(getActivity().getApplicationContext());
// display existing tables
/*
Cursor hi = x.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
hi.moveToFirst();
int f = hi.getCount();
String g = Integer.toString(f);
Toast.makeText(getActivity().getApplicationContext(), g, Toast.LENGTH_LONG).show();
while ( !hi.isAfterLast() ) {
String h = (hi.getString( hi.getColumnIndex("name")) );
hi.moveToNext();
Toast.makeText(getActivity().getApplicationContext(), h, Toast.LENGTH_LONG).show();
}
*/
// Get References of Views
carSpinner = (Spinner) rootView.findViewById(R.id.spinner_car_type);
editTextDistance = (EditText) rootView.findViewById(R.id.editTextcarDistance);
editTextMin = (EditText) rootView.findViewById(R.id.editTextcarMin);
// Spinner click listener
carSpinner.setOnItemSelectedListener(this);
// set default spinner selection
carSpinner.setSelection(0);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Standard");
categories.add("Truck");
categories.add("Electric/Hybrid");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
carSpinner.setAdapter(dataAdapter);
// identifying the button
btnSubmitCar = (Button) rootView.findViewById(R.id.button_car_submit);
btnSubmitCar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// take username entry from login / sign up form via method in FProfile
// String currentUser = getSingleEntry();
String username = session.getUsername();
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy", Locale.CANADA);
String date = formata.format(new Date());
String type = carSpinner.getSelectedItem().toString();
// convert distance to integer
int distance = 0;
try {
distance = Integer.parseInt(editTextDistance.getText().toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse distance " + nfe);
}
// convert minutes to integer
int time = 0;
try {
time = Integer.parseInt(editTextMin.getText().toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse minutes" + nfe);
}
// Save the Data in Database
carDataBaseAdapter.insertEntry(username, date, type, distance, time);
// link back to input menu
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("caller", "Input");
startActivity(intent);
}
}
);
return rootView;
}
This is my query:
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", new String[]{"distance, time"}, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
carCursor.close();
}
carCursor.moveToFirst();
for (int i = 0; i < carCursor.getCount(); i++) {
int distance = carCursor.getInt(carCursor.getColumnIndex("DISTANCE"));
int time = carCursor.getInt(carCursor.getColumnIndex("TIME"));
}
return carCursor;
Then I retrieve it in a fragment
carStandardCursors[i] = carDataBaseAdapter.getCarEntry(currentUsername, searchDate, "Standard");
Then I made a loop to perform math on the cursors
for (int i = 0; i < 7; i++) {
Cursor ccursor = carStandardCursors[i];
carStandardTotal = CalculateCarStandard(ccursor);
carStandard[dex] = carStandardTotal;
And I found that the values in carStandardCursors[i] were all zero.

Use Facebook Stetho Library to check whether the database contains Values or not.Then only you can get an idea.
stetho library

the problem is here,
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", **new String[]{"distance, time"}**, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
carCursor.close();
}
carCursor.moveToFirst();
for (int i = 0; i < carCursor.getCount(); i++) {
int distance = carCursor.getInt(carCursor.getColumnIndex("DISTANCE"));
int time = carCursor.getInt(carCursor.getColumnIndex("TIME"));
}
return carCursor;
change it to
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", new String[]{"DISTANCE", "TIME"}, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
return carCursor;
}else{
if (carCursor!= null) {
carCursor.moveToNext();
}
return carCursor;
}
and then get this cursor at your method call and then at their
Cursor call = classObject.getCarEntry(username, Day, Type);
int distance = call .getInt(carCursor.getColumnIndex("DISTANCE"));
int time = call .getInt(carCursor.getColumnIndex("TIME"));
if more than one data then use while loop and ArrayAdapter

Related

How do i get and use information from a Sqlite database in android

This is my code and my CarsDbHelper, CarsContract for my CarsEntry.
It has no problems, but I am unsure from here on how to use information I have put in a Sqlite database.
String current_car_name = "TOYOTA YARIS";
String current_car_colour = "GREY";
int current_car_age = 3;
CarsDbHelper mDbHelper = new CarsDbHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CarsEntry.COLUMN_NAME,current_car_name);
values.put(CarsEntry.COLUMN_COLOUR,current_car_colour);
values.put(CarsEntry.COLUMN_AGE,current_car_age);
long newRowId = db.insert(CarsEntry.TABLE_NAME, null, values);
}
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
CarsEntry.COLUMN_NAME,
CarsEntry.COLUMN_COLOUR,
CarsEntry.COLUMN_AGE
};
public void button (View view) {
String selection = CarsEntry.COLUMN_NAME + " = ?";
String[] selectionArgs = {current_car_name};
TextView car_name = (TextView) findViewById(R.id.name);
car_name.setText();
TextView car_colour = (TextView) findViewById(R.id.colour);
car_colour.setText();
TextView car_age = (TextView) findViewById(R.id.age);
car_age.setText();
}
I am still a bit confused on how to input this data into my TextViews.
You type in them... Did you mean get values out of them?
First off, the purpose of the "helper" object is to help you not expose a SQLiteDatabase object.
Make a Car class and an addCar(Car car) method in your helper.
public long addCar(Car car) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CarsEntry.COLUMN_NAME,car.getName());
values.put(CarsEntry.COLUMN_COLOUR,car.getColour());
values.put(CarsEntry.COLUMN_AGE,car.getAge());
long newRowId = db.insert(CarsEntry.TABLE_NAME, null, values);
return newRowId;
}
Then, in the Activity, you need to set the helper in onCreate, not outside
CarsDbHelper mDbHelper;
TextView mCarName, mCarColour, mCarAge;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCarName = (TextView) findViewById(R.id.name);
mCarColour = (TextView) findViewById(R.id.colour);
mCarAge = (TextView) findViewById(R.id.age);
mDbHelper = new CarsDbHelper(this); // Moved in here
}
public void button (View view) {
String name = mCarName.getText().toString();
String colour = mCarColour.getText().toString();
String age = mCarAge.getText().toString();
Car c = new Car(name, colour, Integer.parseInt(age));
mDbHelper.addCar(c); // This is the helper method
}
If you want to get data out of the database, you need a ListView and an Adapter (such as CursorAdapter)
If you would like to not mess with the details of raw SQLite, see the Room Persistence library
First, you should create db instance in onCreate Function.
Cursor cursor = db.query(
TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Copied from Android Dev Site.
You will get cursor, iterate through it as follows:
if(!cursor.moveToFirst())
//No Data
//cache columns indexes in integers
int idIndex = cursor.getColumnIndex("id");
...
while(cursor.moveToNext()){
String id = cursor.getString(id); //Same for boolean, Int, long, etc.
...
}
//Never forget to close cursor
cursor.close();

Strange behavior of custom listview with sqlite

I am trying to create a shopping cart app and everything was going great but now i am stuck for last three day did search lot in stackoverflow but could not get a answer.I am populating listview from server and there is two buttons in each row plus(for adding quantity) and minus for (decrements it). This is the screen where i am adding quantity to cart.
I am trying to insert row to sqlite database upon clicking either of two buttons and i have achieved this and i am show these data in next activity inside a listview. Here my problem starts when i insert data it shows it properly but during updation it is showing strange behavior. If i click on first three rows the insertion and updation working fine but if i scroll down and click on any item then instead of updating each time its inserting.. I know this question is quite big and lengthy but i could not find a good way to summarize it sorry.. Please help me thanks ..
This is the screen which i am getting as output.
Here is my ListView class.
public class MyFragment extends Fragment implements View.OnClickListener{
int mCurrentPage;
private ListView listView;
RecyclerView recyclerView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private List<FeedItem> productsInCart = new ArrayList<FeedItem>();
private RelativeLayout content;
private SharedPreferences preference;
TextView badge,prices;
int totalCount=0,newCount = 0;
int lastCount;
int totalPrice;
SQLiteDatabase dataBase;
public static final String TOTAL_COUNT = "count";
DBHelper mHelper;
boolean isUpdate;
String userId,price,pname,position;
private Button checkOut;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
recyclerView= (RecyclerView) v.findViewById(R.id.my_recycler_view);
content = (RelativeLayout)v.findViewById(R.id.content);
badge = (TextView)v.findViewById(R.id.all_comments);
checkOut = (Button)v.findViewById(R.id.checkOut);
prices = (TextView)v.findViewById(R.id.price);
feedItems = new ArrayList<FeedItem>();
new JSONAsyncTask()
.execute("http://api.androidhive.info/feed/feed.json");
listAdapter = new FeedListAdapter(getActivity(), feedItems);
recyclerView.setAdapter(listAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
listAdapter.setOnAddNum(this);
listAdapter.setOnSubNum(this);
mHelper=new DBHelper(getActivity());
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(),CheckOutFooter.class);
startActivity(i);
getActivity().overridePendingTransition
(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
}
});
checkOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (userId != null){
Intent i = new Intent(getActivity(),CheckOut.class);
startActivity(i);
}
else{
Toast.makeText(getActivity(), "Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
// TODO Auto-generated method stub
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("feed");
for (int i = 0; i < jarray.length(); i++) {
JSONObject feedObj = jarray.getJSONObject(i);
// Actors actor = new Actors();
FeedItem item = new FeedItem();
item.setObservation(feedObj.optString("name"));
item.setSummary(feedObj.optString("timeStamp"));
item.setName(feedObj.optString("name"));
feedItems.add(item);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result == false){
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else{
listAdapter.notifyDataSetChanged();
}
pDialog.dismiss();
}
}
#Override
public void onClick(View view) {
Object tag = (Integer) view.getTag();
switch (view.getId()){
case R.id.btnAddToCart1:
// FeedItem item = feedItems.get(tag);
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
String pName = feedItems.get(position).getName();
String product_name = feedItems.get(position).getName();
num++;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
Toast.makeText(getActivity(),
product_name+ " is added to cart!", Toast.LENGTH_SHORT).show();
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("PNAME",product_name).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
break;
case R.id.btnAddToCart5:
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
if (num>0) {
num--;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
else{
num= 0;
dataBase.delete(
DBHelper.TABLE_NAME,
DBHelper.KEY_ID + "="
+ (position+1), null);
listAdapter.notifyDataSetChanged();
}
}
break;
}
}
public void onResume(){
super.onResume();
}
private void updateData() {
preference =
getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
userId = preference.getString("QUANTITY", null);
price = preference.getString("PRICE", null);
pname = preference.getString("PNAME", null);
position = preference.getString("POSITION", null);
int counts = Integer.parseInt(position);
if(userId == null){
badge.setText("0");
}
else{
checkOut.setEnabled(true);
badge.setText(String.valueOf(userId));
dataBase = mHelper.getReadableDatabase();
/*Cursor curs = dataBase.rawQuery("SELECT SUM(price) FROM cart", null);
if(curs.moveToFirst())
{
int total = curs.getInt(0);
System.out.println("Total Sum of Price : "+total);
prices.setText(String.valueOf(total)+" Rs/-");
}
*/
Cursor cur = null;
String query = "SELECT * FROM " + DBHelper.TABLE_NAME +
" WHERE " +DBHelper.KEY_ID+"=?;" ;
cur = dataBase.rawQuery(query,new String[] {String.valueOf(counts+1)});
if((cur != null) && (cur.getCount() > 0)){
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.update(DBHelper.TABLE_NAME, cv, DBHelper.KEY_ID+" = '" +
String.valueOf(counts+1) + "'", null);
cur.close();
}
else{
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.insert(DBHelper.TABLE_NAME, null, cv);
cur.close();
}
}
}
}
My checkout page where i am showing data from sqlite.
public class CheckOut extends AppCompatActivity{
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> product_Name = new ArrayList<String>();
private ArrayList<String> product_Quantity = new ArrayList<String>();
private ArrayList<String> product_Price = new ArrayList<String>();
private ArrayList<Integer> quantityList = new ArrayList<Integer>();
private ArrayList<Integer> amountList = new ArrayList<Integer>();
ListView recyclerView;
TextView quantity;
TextView amount;
Button pay;
DBHelper mHelper;
SQLiteDatabase dataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkout);
recyclerView= (ListView) findViewById(R.id.my_recycler_view);
amount = (TextView) findViewById(R.id.amount);
quantity = (TextView) findViewById(R.id.quantity);
pay = (Button) findViewById(R.id.pay);
mHelper = new DBHelper(this);
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DBHelper.TABLE_NAME, null);
int sum = 0;
int qty = 0;
userId.clear();
product_Name.clear();
product_Quantity.clear();
quantityList.clear();
amountList.clear();
product_Price.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_ID)));
product_Name.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PNAME)));
product_Quantity.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_COUNT)));
product_Price.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PRICE)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(CheckOut.this,userId, product_Name, product_Price,product_Quantity);
recyclerView.setAdapter(disadpt);
mCursor.close();
quantityList = convertInteger(product_Quantity);
amountList = converAmountInteger(product_Price);
for (int i : quantityList){
qty = qty+i;
}
for (int s : amountList){
sum = sum +s;
}
amount.setText(String.valueOf(sum));
quantity.setText(String.valueOf(qty));
disadpt.notifyDataSetChanged();
}
private ArrayList<Integer> converAmountInteger(
ArrayList<String> product_Price2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String amount : product_Price2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(amount));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + amount + " can not be an integer");
}
}
return result;
}
private ArrayList<Integer> convertInteger(
ArrayList<String> product_Quantity2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String quantity : product_Quantity2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(quantity));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + quantity + " can not be an integer");
}
}
return result;
}
Database class:
public class DBHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="user.db";
public static final String TABLE_NAME="cart";
public static final String KEY_COUNT="cartItem";
public static final String KEY_PNAME="product_name";
public static final String KEY_ID="id";
public static final String KEY_PRICE="price";
public static final String KEY_CREATED_AT="created_at";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_COUNT+" INTEGER,"
+KEY_PNAME+" TEXT,"+KEY_PRICE+" INTEGER,"+ KEY_CREATED_AT
+ " DATETIME" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
UPDATE :
There was a little mistake i changed the column name instead of i created a unique key and its working fine..

Android/Java - Defining variables at different "places"

Okay this title might sound strange but I don't really know how to explain it.
What I'm trying to do: query a database, use the #of results to define a string array length and use the results to fill a view. All of this works, theoretically, but when I try to move my code from onCreate "up", I get syntax errors I can't fix. It might make more sense to just read my comments in the code below!
public class A_customlist extends ListActivity {
Integer runme = 5;
int[] imgb = new int[runme];
{
for (int number = 0; number < imgb.length; number++) {
imgb[number] = R.drawable.spatz_adult;
}
;
};
SQLiteDatabase TPBDB;
String[] myString2 = new String[5];
// what I want to do: new String[count]
// basically do all the TPBDB stuff (see below) first, so I can access the
// count variable
// defining myString in onCreate makes it inaccessible in onListItemClick
String[] myString = new String[5];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// "TPBDB stuff"
TPBDB = openOrCreateDatabase("TPBDB1", MODE_PRIVATE, null);
Cursor cur = TPBDB.rawQuery("SELECT * from Vogel", null);
String mycur = cur.toString();
int count = cur.getCount();
cur.moveToFirst();
// String[] myString = new String[count+1]; // 4 entries, runme = 5!
for (Integer j = 0; j < count; j++) {
myString[j] = Long.toString(cur.getLong(cur.getColumnIndex("uid")));
myString2[j] = cur.getString(cur.getColumnIndex("datum"));
cur.moveToNext();
}
;
TPBDB.close();
// --- "TPBDB stuff"
getListView().setDividerHeight(2);
getListView().setAdapter(
new BindDataAdapter(this, imgb, myString, myString2));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(myString[position] + " is clicked.");
builder.setPositiveButton("OK", null);
builder.show();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.activity_list, menu);
// return true;
// }
}
Like this you can access your array in the onClickListener, in case thats what you wanted to achieve
String[] myString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// "TPBDB stuff"
TPBDB = openOrCreateDatabase("TPBDB1", MODE_PRIVATE, null);
Cursor cur = TPBDB.rawQuery("SELECT * from Vogel", null);
String mycur = cur.toString();
int count = cur.getCount();
myString = new String[count]; // init array here
...
}
you just have to declare a field "above" oncreate, you dont have to initialize it at the same time.

Android ExpandableList: getting group instead of child in onChildClick method

I have a problem:
I implemented a method for call the groups and childs from databases, after put all in a expandablelist, until then, everything was fine all data came out as expected.
But when I call a Toast message with clicked child into onChildClick method, the Toast show me the group instead of the child (the group is wrong too)
Can anyone help me find where I went wrong?
Remembering: the output of the expandable list came out correctly
This my active with expandable list:
public class ShowDeckActivity extends ExpandableListActivity {
/** Called when the activity is first created. */
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carddeck);
try{
SimpleExpandableListAdapter expListAdapter =
new SimpleExpandableListAdapter(
this,
createGroupList(),
R.layout.group_row,
new String[] { "Group Item" },
new int[] { R.id.row_name },
createChildList(),
R.layout.child_row,
new String[] {"Sub Item"},
new int[] { R.id.grp_child}
);
setListAdapter( expListAdapter );
}catch(Exception e){
System.out.println("Errrr +++ " + e.getMessage());
}
}
#SuppressWarnings("rawtypes")
private List createGroupList(){
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
return db.getGroupList();
}
#SuppressWarnings("rawtypes")
private List createChildList(){
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
return db.getChildList();
}
public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
String nameLable = parent.getItemAtPosition(childPosition).toString();
// Debug
// System.out.println("Inside onChildClick at groupPosition = " + (groupPosition + 1) +" Child clicked at position " + (childPosition + 1));
Toast.makeText(getApplicationContext(), nameLable, Toast.LENGTH_SHORT).show();
return true;
}
}
This my DatabaseHandler methods:
public List getGroupList() {
String SQL = "SELECT * FROM assunto";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(SQL, null);
int numeroColunas = cursor.getCount();
ArrayList result = new ArrayList();
if(cursor.moveToFirst()){
do{
HashMap m = new HashMap();
m.put( "Group Item", cursor.getString(2) );
result.add( m );
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return (List)result;
}
//#SuppressWarnings({ "unchecked", "rawtypes" })
public List getChildList(){
String sqlAssunto = "SELECT * FROM assunto";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursorAssunto = db.rawQuery(sqlAssunto, null);
ArrayList result = new ArrayList();
if(cursorAssunto.moveToFirst()){
do { // Loop begin 1
String assuntoID = cursorAssunto.getString(0);
String sqlDeck = "SELECT * FROM deck WHERE table_assuntos_id=" + assuntoID;
Cursor cursorDeck = db.rawQuery(sqlDeck, null);
ArrayList secList = new ArrayList();
if(cursorDeck.moveToFirst()){ // Move-se nos decks
do {
// Loop Begin 2
HashMap child = new HashMap();
child.put( "Sub Item", cursorDeck.getString(2) );
secList.add( child );
} while (cursorDeck.moveToNext()); // Loop end 2
}
result.add( secList );
} while (cursorAssunto.moveToNext()); // Loop end 1
}
cursorAssunto.close();
db.close();
return result;
}
The expandable list output(It's as expected):
GROUP1
- SUB ITEM1_1
- SUB ITEM1_2
- SUB ITEM1_3
GROUP2
- SUB ITEM2_1
- SUB ITEM2_2
GROUP3
- SUB ITEM3_1
GROUP4
[..]
Example:
When I click in (GROUP3 x SUB ITEM3_1)
The wrong Toast message is:
{Group Item= GROUP1}
... instead of the expected:
{Sub Item=SUB ITEM3_1}
Anyone have idea what's happened?
Thanks in advance!
==================[EDITED, I FOUND THE SOLUTION]=========================
To fix the problem you have to instantiate a ExpandableListAdapter, some like this:
ExpandableListAdapter adap = parent.getExpandableListAdapter();
String adaptar = adap.getChild(groupPosition, childPosition).toString(); // This get the correct child name
Thanks for help!

Sorting a ListView with ArrayAdapter<String>

I have a custom ListView, each list item has four TextViews showing bank name, amount, date and time. This data is stored in a database. The idea is that on the Activity there is a quick action dialog which opens on clicking the sort button. The Dialog has three options as "Sort by bank name" ascending order, "Sort by Date" newest first and "Sort by amount" larger amount in the top of the list. I don't have any idea of how to proceed with the sorting task to be written in onItemClick(int pos). Can anyone please help me on this?
public class TransactionMenu extends Activity implements OnItemClickListener, OnActionItemClickListener {
String[] TransId ;
String[] mBankName;
String[] mAmount;
String[] mDate;
String[] mTime;
Button SortButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction_screen);
SortButton = (Button)findViewById(R.id.sortKey);
//Bank Name action item
ActionItem bName = new ActionItem();
bName.setTitle("Bank Name");
bName.setIcon(getResources().getDrawable(R.drawable.bank_256));
//Amount action item
ActionItem amt = new ActionItem();
amt.setTitle("Amount");
amt.setIcon(getResources().getDrawable(R.drawable.cash));
//date action item
ActionItem date = new ActionItem();
date.setTitle("Date");
date.setIcon(getResources().getDrawable(R.drawable.calender));
//create quickaction
final QuickAction quickAction = new QuickAction(this);
quickAction.addActionItem(bName);
quickAction.addActionItem(amt);
quickAction.addActionItem(date);
quickAction.setOnActionItemClickListener(this);
SortButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
//quickAction.setAnimStyle(QuickAction.ANIM_REFLECT);
}
});
DBAdapter lDBAdapter = new DBAdapter(this);
lDBAdapter.open();
/* getTransDetails() returns all the detials stored in the transaction table*/
Cursor mCursor =lDBAdapter.getAllTransDetails();
System.out.println("cur..........."+mCursor);
lDBAdapter.close();
if (mCursor != null) {
int size = mCursor.getCount();
if (mCursor.moveToFirst()) {
TransId = new String[size];
mAmount = new String[size];
mBankName = new String[size];
mDate = new String[size];
mTime = new String[size];
for (int i = 0; i < size; i++, mCursor.moveToNext()) {
TransId[i] = mCursor.getString(0);
mAmount[i] = mCursor.getString(1);
mBankName[i] = mCursor.getString(3);
mDate[i] = mCursor.getString(2);
mTime[i] = mCursor.getString(4);
}
}
}
for (int i = 0; i < mCursor.getCount(); i++) {
System.out.println("TransId is+++++++++++++++ "+TransId[i]);
System.out.println("amount is+++++++++++++++ "+mAmount[i]);
System.out.println("bankName is+++++++++++++++ "+mBankName[i]);
System.out.println("date is+++++++++++++++ "+mDate[i]);
System.out.println("time is+++++++++++++++ "+mTime[i]);
}
ListView myListView = (ListView) findViewById(R.id.transactionListView);
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
myListView.setAdapter(myAdapterObj);
myListView.setOnItemClickListener((OnItemClickListener) this);
}
private class MyBaseAdapter extends ArrayAdapter<String> {
public MyBaseAdapter(Context context, int textViewResourceId, String[] transId) {
super(context, textViewResourceId, transId);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_item, parent, false);
TextView label = (TextView)row.findViewById(R.id.textview1);
label.setText("Amount: "+mAmount[position]);
TextView label1 = (TextView) row.findViewById(R.id.textview2);
label1.setText("Bank Name: "+mBankName[position]);
TextView label2 = (TextView) row.findViewById(R.id.textview3);
label2.setText("Date: "+mDate[position]);
TextView label3 = (TextView) row.findViewById(R.id.textview4);
label3.setText("Time: "+mTime[position]);
return row;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("arg2 is++++++++++++++"+arg2);
int lRowId = Integer.parseInt(TransId[arg2]);
}
public void onItemClick(int pos) {
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
if (pos == 0) {
Toast.makeText(TransactionMenu.this, "Bank name item selected", Toast.LENGTH_SHORT).show();
}
else if (pos ==1) {
Toast.makeText(TransactionMenu.this, "amount item selected", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TransactionMenu.this, "Date item selected", Toast.LENGTH_SHORT).show();
}
}
}
I will give you the way i would do this, not the best probably but it will work fine.
Fisrt of all as user7777777777 said it's better to keep related infos into the same object so i'd define BankInfo class as shown below:
private class BankInfo{
String TransId ;
String mBankName;
String mAmount;
String mDate;
String mTime;
public BankInfo(String TransId,String mBankName,String mAmount,String mDate,String mTime)
{
//fields init
}
}
once you have this you will define an Array of this object BankInfo[] trans. In the adapter you can use this array to bind values into views.
then to manage to implement the sorting function the thing i would do is to put a static variable into the BankInfo class and override the CompareTo() method to use that field:
static int AMMOUNT = 0;
static int DATE = 1;
static int NAME = 2;
static public int sort_by;
public int compareTo(BankInfo info){
switch (sorty_by){
case(AMMOUNT):
return //compare by ammount
case(DATE):
return //compare by date
case(NAME):
return //compare by name
}
}
with this inside of BankInfo you will have only to add your array to a TreeSet<BankInfo> and all your item will be sortet using the compareTo() method.
Inside the adapter put this method to sort elements in the adapter
public void sort_datas(int sort_by);
{
//set the type of sort you want
BankInfo.sortBy = sort_by;
//build a Sorted treeSet by the BankInfo array
TreeSet<BankInfo> sorted_info = new TreeSet<BankInfo>();
list.addAll(Arrays.asList(trans));
//replace the BankInfo array with the new sorted one
trans = (BankInfo[])sorted_info.toArray();
//notify to the adapter that the data set changed
notifyDataSetChanged();
}
You can use the following code. You need to maintain the bank info in a BankInfo object. Create an ArrayList of BankInfo objects and then you can use this code. Its not a good practice to keep related info into separate arrays.
Collections.sort(mBankInfoArrayList, new Comparator<BankInfo>() {
int compare(BankInfo obj1, BankInfo obj2) {
return obj1.getBankName().compareToIgnoreCase(obj2.getBankName());
}
});

Categories