next button for listview - android

My first activity contains a ListView that's getting a list of items from a database.
And in the OnClickListener, there is a new activity that's open getting all information related to the question from the database, I'm putting them in Intent extras and getting them in the next activity:
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
String quest = (String) parent.getAdapter().getItem(i);
int pos = lst.getCheckedItemPosition();
Intent inte = new Intent(view.getContext(),Reponse.class);
cursor = db.rawQuery("SELECT * FROM "+ ModelHelper.TABLE_QUESTION + " WHERE " + ModelHelper.KEY_QUESTION + " = ? ",new String[] {quest});
if (cursor != null)
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String repA = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_WAITEDANSWER));
String cible = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_CIBLE));
String plan = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PLANACT));
int ID = cursor.getColumnIndex(ModelHelper.KEY_ID_QUESTION);
inte.putExtra("question", quest);
inte.putExtra("repo", repA);
inte.putExtra("cible", cible);
inte.putExtra("plan", plan);
// inte.putExtra("id", ID);
// inte.putExtra("pos", pos);
startActivity(inte);
finish();
In the info activity, it's simple and I could get the information from the database, here's the code
Intent intent = getIntent();
String question = intent.getStringExtra("question");
String repo = intent.getStringExtra("repo");
String cible = intent.getStringExtra("cible");
String plan = intent.getStringExtra("plan");
final int[] ID = {0};
ID[0] = intent.getIntExtra("ID", ID[0]);
int pos = 0;
pos = intent.getIntExtra("pos",pos);
txtq.setText(question);
txtr.setText(repo);
txtc.setText(cible);
txtp.setText(plan);
I want to add a button NEXT that makes appear the next item in the list by refreshing the same page without going back to the list and click again.
I tried to get the position too with the intent and tried to set a new OnClickListener in the button to set the position = position +1, but it doesn't work.
Any ideas?

First solution
for that, you have to pass the entire list to next activity so you can directly do next item in the list by refreshing the same page without going back.
Second solution.
You have to separately apply query for next info page click on the next/previous button.

You just need to go through the sql Queries
select * from table where key=primaryKey limit Page_Limit offset Start_From
You need to change limit and offset on select of list limit.

Related

SQLite- button adds value to db.query

I've got a database with the following columns:
Book_name, book_id, chapter_number, chapter_id, line_number, line_id
I'm doing this app to read books, select a chapter to read, and then display all the lines.
First listview displays all the books, when the user selects on a book name, it passes the book_id to display all the chapters under that book, when selecting a chapter, it passes the chapter_id to display all the lines under that chapter.
My question is, when a user is busy reading they must press the back button to display all the chapters again and then select the next chapter. I want to put a button on the listview displaying all the lines (after the chapter has been selected) for the user to press and then it should basically re-query the db to display the next available chapter.
Each listview is in it's own activity and id's gets passed with Intents.
I don't know what code you guys want to see so please just ask.
This is the list in DBHandler2 for the chapters:
public List<defineBybeldbAlles> getListHoofstuk(String boek_id_na_hoofstuk){
defineBybeldbAlles defineBybeldbHoofstuk = null;
List<defineBybeldbAlles> defineBybeldbAllesList = new ArrayList<>();
opendatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM PWLBybel WHERE " + COLUMN_BOEK_ID + " = '" + boek_id_na_hoofstuk + "'GROUP BY hoofstuk_id ORDER BY hoofstuk_id * 1 ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
defineBybeldbHoofstuk = new defineBybeldbAlles(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getInt(5),cursor.getString(6),cursor.getString(7),cursor.getInt(8),cursor.getString(9),cursor.getString(10));
defineBybeldbAllesList.add(defineBybeldbHoofstuk);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return defineBybeldbAllesList;
}
This is where I pass the chapter_id in my chapter activity to diplay the lines in the lines activity:
public void onItemClick (AdapterView<?> arg0, View view, int arg2, long arg3){
//on selecting a hoofstk
//BybelActivityVers will be launched to show verse inside
Intent hoofstukIntent = new Intent(BybelActivityHoofstuk.this,BybelActivityVers.class);
//send hoofstuk_id to VersActivity to get verse under that book
String hoofstuk_id_na_vers = ((TextView)view.findViewById(R.id.hoofstuk_id)).getText().toString();
hoofstukIntent.putExtra("hoofstuk_id", hoofstuk_id_na_vers);
String hoofstuk_nommer_na_vers = ((TextView)view.findViewById(R.id.custom_row_hoofstuktext)).getText().toString();
hoofstukIntent.putExtra("custom_row_hoofstuktext", hoofstuk_nommer_na_vers);
startActivity(hoofstukIntent);
}
});
Now this is the list in DBHandler3 for the lines:
public List<defineBybeldbAlles> getListVers(String hoofstuk_id_na_vers){
defineBybeldbAlles defineBybeldbVers = null;
List<defineBybeldbAlles> defineBybeldbVersList = new ArrayList<>();
opendatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM PWLBybel WHERE " + COLUMN_HOOFSTUK_ID + " = '" + hoofstuk_id_na_vers + "'GROUP BY vers_id ORDER BY vers_id * 1 ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
defineBybeldbVers = new defineBybeldbAlles(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getInt(5),cursor.getString(6),cursor.getString(7),cursor.getInt(8),cursor.getString(9),cursor.getString(10));
defineBybeldbVersList.add(defineBybeldbVers);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return defineBybeldbVersList;
}
Set variable chapterid + 1 in current chapter to be passed in intent
Then Intent i = new intent(PARAMETERS);
finish();
startactivity(i);
Then run the query with db to get details of new chapter in new intent
Its working thanks
In your ques add a button .
check if list is scrolled to last
'
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mListView.getAdapter() == null)
return ;
if (mListView.getAdapter().getCount() == 0)
return ;
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !isLoading) {
// It is time to add new data. We call the listener
isLoading = true;
}
}
});
'
when is loading is true dat means ur list is at its last
and then make nextbutton.setvisibility(View.Visible);
and on click of button
get ur chapter id and add 1 to it i.e.. next chapter id
and start intent and pass chapter and page id with dat intent like
Intent i = new Intent(this,Currentclass.java);
finish();
start activity(i);
// your page will be changed now
please tick the answer as correct thanks:)

Let user add/remove favorites from drawer/listview from position and save it to SQLite db

I have a sqlite database prepopulated with some data and I would like to have method/function that enables the user to "save" the info in his favorites and display it. The only problem is i have problems with the queries to work properly. I don't understand how to get the position from the current displayed data (from the db) in the activity and save it to the database. I have a column called "Favorites" in db with the default value set to "no" and when the user click a button the value should change to "yes".
The user click a row in listview populated from the DB and it starts a new activity with intent.putExtra(data from db). The new activity displays the data in a single textview. In this new activity i've made a navigation drawer/listview(shows by sliding or "hamburger meny"). In this nav drawer I have a "button" that i would like to get the id from the db according to the current displayed data and change the value of the column "Favorite". In a another class i used
Cursor c = dbHelper.showBook(Integer.toString(position + 1));
Got this help from another recent thread of mine and it worked fine but my new problem is that i have if statements as below. The start of intent works fine. But I want to call a method from my dbHelper to update rows in db. And the code above dont work(but no errors) when i try to use it. The toast shows but nothing is happening in the DB.
myDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
Intent iHome = new Intent(DisplayBook.this, MyAccont.class);
startActivity(iHome);
else if (position == 3){
dbHelper.addFavorites(Integer.toString(position+ 1));
Toast.makeText(getApplicationContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
the dbHelper.addFavorites: (the addFavs param is supposed to be the id/pos of the db row as in the working code above)
public void addFavorites(String addFavs){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FAV, "yes");
String whereClause = COL_ID + " = ?" ;
String[] whereArgs = new String[] { addFavs};
db.update(
TABLE_NAME,
values,
whereClause,
whereArgs);
}
I've tried a fair amount of versions och different codes and stuff but nothing works and now I'm asking for som advice on this. How can i do it in a good an efficient way? Thank you so much for any help at all!
EDIT: Solved it by using arrays instead of stringbuilder. I save the id from the database in [0] and used it in dbHelper.addFavorites(myStringArray[0]);
and in
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = dbHelper.aClass(Integer.toString(position + 1));
StringBuilder sb = new StringBuilder();
while (c.moveToNext()) {
myStringArray[0] = c.getString(0);
myStringArray[1] = c.getString(4);
Intent i = new Intent(classA.this, classB.class);
i.putExtra(null, myStringArray);
startActivity(i);
I'm not shure, but your problem may be this line
ContentValues values = new ContentValues();
try to change it to:
ContentValues values = new ContentValues(1);
From my experience u should write amount of variables u want to send to your db.

Set onclick to item that isn't visible

So I have been looking around for about 4 hours now and maybe I just don't know how to word my search, but I am not finding out what I need.
I am using a custom adapter to setup my listview from items I have stored into an sqlite database. My cursor sends id, name, product_id, data, datetime to my adapter. But my adapter is set to only display the name, data & datetime.
I need to be able to click on the name, but have it go to my next activity and display the information from the product_id that was sent to the adapter. Example I click on Apples, but it would actually be product_id 505 in my database. Unless I set the product_id to a textview, when I click on my item, it does not bring up the correct listing and searches for Apples.
If this is not clear, please let me know and I will to explain it better.
** EDIT **
So my database is like this
_ID | PRODUCT_NAME | PRODUCT_ID | PRODUCT_DATA | DATE
1 Apples 505 Fresh Apples 123456
2 Oranges 506 Fresh Orange 123456
3 Kiwi 507 Fresh kiwi 123456
4 Nuts 508 Fresh Nuts 123456
My ListView shows this:
Apples- FRESH APPLES - DATE
Oranges - FRESH ORANGE - DATE
Kiwi- FRESH KIWI - DATE
Nuts - FRESH NUTS - DATE
When I click on Apples, I want it to return PRODUCT_ID to me, not _ID, so I can pass that product_id onto my next intent.
My Display listing
public void displayListView()
{
DatabaseOperations db = new DatabaseOperations(this);
Cursor cursor = db.getProducts();
dataAdapter = new MainActivityAdapter(
this,
cursor,
0);
ListView listView = (ListView) findViewById(R.id.product_list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
// listening to single list item on click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long ID)
{
TextView listText = (TextView) view.findViewById(R.id.name);
String product_name = listText.getText().toString();
Intent i = new Intent(MainActivity.this, product_detail.class);
i.putExtra("productName", product_name);
MainActivity.this.startActivity(i);
}
});
db.close();
}
My Adapter
public class MainActivityAdapter extends CursorAdapter
{
private LayoutInflater cursorInflater;
private Context c;
// Default constructor
public MainActivityAdapter(Context context, Cursor cursor, int flags)
{
super(context, cursor, flags);
cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
c = context;
// Log.i("Custom-Adapter", "Starting up");
}
public void bindView(View view, Context context, Cursor list)
{
TextView PN = (TextView) view.findViewById(R.id.product_name);
TextView PI = (TextView) view.findViewById(R.id.product_data);
TextView date = (TextView) view.findViewById(R.id.date);
// SET OUR DATA FROM OUR CURSOR
String pn = list.getString( list.getColumnIndex("pn"));
String pi = list.getString( list.getColumnIndex("pi"));;
// NEED TO RECONVERT DATE THEN SHOW IT
Long millidate = list.getLong(list.getColumnIndex("dateTime"));
Date myDateNew = new Date(millidate);
String Sdate = getDate(millidate);
PN.setText(pn);
PI.setText(pi);
date.setText(Sdate);
}
public static String getDate(long milliSeconds)
{
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliSeconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
return date;
}
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
//Log.i("Custom-Adapter", "newView Started");
// R.layout.list_row is your xml layout for each row
return cursorInflater.inflate(R.layout.activity_list, parent, false);
}
I want to get the product_id when I click on the name Apples.
We can achieve it in multiple ways but most common ways are :
Option 1:
Use setTag method for saving id of product with name in TextView :
PN.setText(pn);
PN.setTag((list.getInt(list.getColumnIndex("product_id"))).toString());
Now use getTag method to get clicked product product_id in onItemClick :
String product_name = listText.getText().toString();
int product_id = Integer.parseInt(listText.getTag().toString());
Option 2:
Instead of getting product name from TextView, get clicked row cursor using Adapter in onItemClick :
Cursor cursor = (Cursor) dataAdapter.getItem(position);
String product_name = cursor.getString(cursor.getColumnIndex("pn"));
int product_id = cursor.getInt(cursor.getColumnIndex("product_id"));
....
A good option is to create an array and store product_ids for all the names.
Goto Res->Strings create an array of strings .
then fetch from the array the relevant product_id for the name.

String value is null

I have a ListView with each row containing a TextView. On user click, I'm getting the value of the TextView and storing it in a String variable, and the user is navigated to another activity where he / she needs to input some data on said TextView. In order to not lose the information state of the first activity, I had to use startActivityForResult() and later get the information from the second activity with the method onActivityResult().
The problem is this: I need to compare a value with that of the TextView in question, however the String variable which supposedly contains the TextView's value is null.
Before starting up the second activity I toasted the String value and it returned the correct string, however not in the onActivityResult(), where it returns null.
Why is this happening? Isn't the Intent I used suppose to retain all information of the opened activity?
ListView's onItemClick
#Override
public void onItemClick(AdapterView<?> listView, View itemView, int itemPosition, long itemID)
{
clickedError = ((TextView)itemView).getText().toString();
String errorIDQuery = "SELECT _id FROM " + TABLE_ERROR + " WHERE error_description LIKE '" + clickedError + "';";
Cursor getErrorID = db.rawQuery(errorIDQuery, null);
getErrorID.moveToFirst();
errorID = getErrorID.getInt(0);
Intent intent = new Intent(Repair.this, Material.class);
intent.putStringArrayListExtra("materialList", materialList);
startActivityForResult(intent, 1);
Toast.makeText(getApplicationContext(), clickedError, Toast.LENGTH_LONG).show();
}
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK)
{
#SuppressWarnings("unchecked")
HashMap <String, String> materialDetails = (HashMap <String, String>)data.getSerializableExtra("map");
Set<?> set = materialDetails.entrySet();
Iterator<?> i = set.iterator();
ArrayList<String> materialNames = new ArrayList<String>();
ArrayList<String> materialAmounts = new ArrayList<String>();
do
{
#SuppressWarnings("rawtypes")
Map.Entry me = (Map.Entry)i.next();
materialNames.add(me.getKey().toString());
materialAmounts.add(me.getValue().toString());
}
while (i.hasNext());
for(Error e : errorList)
{
// ----- COMPARING THE VALUES -----
// here clickedError is null
if(e.description.equals(clickedError))
{
for(int j = 0; j < materialNames.size(); j++)
{
MaterialClass mc = new MaterialClass();
mc.setName(materialNames.get(j));
mc.setAmount(Integer.parseInt(materialAmounts.get(j)));
e.materialList.add(mc);
}
if (e.materialList.size() != 0)
e.checked = true;
else
e.checked = false;
}
}
My guess: the activity is destroyed and restarted while moving to the second activity. This is easy to confirm with log messages in the activity life cycle methods(onCreate/onRestart/etc).
The following link might be of use to persist data during activity switching: http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Make your String value as static so that it will retain its value. or you can use shared preference to save value and use it later.
This is working if its not ask me
TextView textviewDate=(TextView)findViewById(R.id.yourtextviewid);
clickedError=textviewDate.getText().toString();

Get data from SQLite database to intent through "onItemClick" on item in ListView Android

I really need your help.
I have a database with latitude and longitude data, here the example:
id_____name_____lat_________long
1_____hotel one___6.1234______-106.12345
2____hotel two____6.54321_____-107.23456
3___hotel three___7.12345_____-106.98765
The data display in ListView on Android. And i use onItemClick, so if i click one of the item in ListView it will go to
Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&saddr=&daddr="+lat_var+","+long_var))
But the problem is if i click one of the item in ListView the data in lat_var and long_var on intent above won't give me the lat and long data from my database...
Here my code, can you edit it, so if i click one of the item in ListView it will give me the lat and long data from my database. For example if i click hotel two the lat_var will change to 6.54321 and the long_var will change to -107.23456 on that intent.
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
String get_lat = "SELECT lat FROM hoteltbl";
Cursor result_lat = dbs.rawQuery(get_lat, null);
double lat_var = result_lat.getColumnIndex("lat");
String get_long = "SELECT lat FROM hoteltbl";
Cursor result_long = dbs.rawQuery(get_long, null);
double long_var = result_long.getColumnIndex("long");
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&saddr=&daddr="+lat_var+","+long_var));
startActivity(intent);
}
I don't know if the problem is my syntax or what. Please fix my code. I really thanks for anyone who answer this...
First, only one query is necessary. No need to query your table twice.
Second, you need to adapt your query with parameters from your selection:
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {id) {
String selectedItem = (String) getListAdapter().getItem(position);
String query = "SELECT lat, long FROM hoteltbl WHERE name = '" + selectedItem + "'";
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
Cursor result = dbs.rawQuery(query, null);
result.moveToFirst();
double lat = result.getDouble(result.getColumnIndex("lat"));
double long = result.getDouble(result.getColumnIndex("long"));
....
This code was written in the StackOverflow editor, it might not work as such, but will give you an idea.
(Also, don't add suffixes "_var", or "_long" to your variables, it's not necessary in a strongly-typed language like Java)

Categories

Resources