I have in my application a listview displaying elements from a database. Every elements of the listview displays some content from my database elements, as well as a button.
Later, I will make this button open the dial menu of the phone and call a number when clicked. What I want now is to display this button only when the length of an element from my database associated to the listview is equal to 7. My problem is to get the length of this string as it's called from my database using the id of the object.
Here is my code, the element I would like to check the length is "telephone" with R.id.telephone, it is called from the database and then sent to another activity :
private void displayListView() {
// getExtra
Bundle bundle = getIntent().getExtras();
String title = bundle.getString("title", "Choose here :");
String inInterval = bundle.getString("inInterval");
Log.d(TAG, "inInterval = " + inInterval);
poititle.setText(title);
// put the results of the method in a cursor
Cursor c = dbHelper.findPoiInTable(inInterval);
String[] columns = new String[] { DatabaseAdapter.COL_NAME,
DatabaseAdapter.COL_STREET, DatabaseAdapter.COL_WEBSITE,
DatabaseAdapter.COL_TELEPHONE, DatabaseAdapter.COL_REMARKS,
DatabaseAdapter.COL_PRICE };
int[] to = new int[] { R.id.name, R.id.street, R.id.website,
R.id.telephone, R.id.remarks, R.id.price };
cursorAdapter = new SimpleCursorAdapter(this, R.layout.poi_info, c,
columns, to, 0);
ListView listView = (ListView) findViewById(R.id.poilistview);
// Assign adapter to ListView
listView.setAdapter(cursorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// Comportement des éléments de la listview
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(),
POIActivity.class);
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String website = ((TextView) view.findViewById(R.id.website))
.getText().toString();
String telephone = ((TextView) view
.findViewById(R.id.telephone)).getText().toString();
String remarks = ((TextView) view.findViewById(R.id.remarks))
.getText().toString();
String price = ((TextView) view.findViewById(R.id.price))
.getText().toString();
// i.putExtra(ID_EXTRA, name) ;
i.putExtra(ID_NAME, name);
i.putExtra(ID_WEBSITE, website);
i.putExtra(ID_TELEPHONE, telephone);
i.putExtra(ID_REMARKS, remarks);
i.putExtra(ID_PRICE, price);
startActivity(i);
}
}); }
Here is what I tried : I created a method callbuttonManagement() in the same activity that I called from my diplsayListView() method whose code is above, and that I define this way :
public void callbuttonManagement() {
int countTelephone = ID_TELEPHONE.length();
if (countTelephone == 7)
{
callButton.setVisibility(View.VISIBLE);
}
else
{
callButton.setVisibility(View.GONE);
}
}
It crashes my app and logcat indicates a nullpointerexception. Any suggestions ? Thanks !
class member boolean mShowButton;
String telephone = ((TextView) view
.findViewById(R.id.telephone)).getText().toString();
if (telephone.length() == 7)
{
mShowButton = true:
}
public void callbuttonManagement() {
if (mShowButton)
{
callButton.setVisibility(View.VISIBLE);
}
else
{
callButton.setVisibility(View.GONE);
}
}
Related
hope you could help me with this problem. i want to get the rowId of a selected item in a listview from sqlite so that i can pass the value to another activity.
i already fed the listview with info from my sqlite table and use onClickedItem in the listview and use pos + 1 to get the id, but i dont want this solution because whenever i delete an item from the listview i wont be able to get the correct rowId from the database itself... this is my code :
in my DBhelper:
public List<String> getSYAList() {
List<String> List = new ArrayList<String>();
try {
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SYA ;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(0)) + " " +(c.getString(1)) + " "+ (c.getString(2)));
} while (c.moveToNext());
}
} catch (Exception e) {
Toast.makeText(ourContext, "Error encountered.",
Toast.LENGTH_LONG).show();
}
return List;
}
in my activity:
private void loadSYA() {
// TODO Auto-generated method stub
final DBhelper entry = new DBhelper(this);
entry.open();
final List<String> sya = entry.getSYAList();
if(sya.size()>0) // check if list contains items.
{
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SYA.this,android.R.layout.simple_dropdown_item_1line, sya);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sqlSYA.setAdapter(arrayAdapter);
sqlSYA.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(SYA.this,SYAInfo.class);
Bundle b = new Bundle();
b.putInt("id", (int)position + 1);
i.putExtras(b);
startActivity(i);
}
}); }
else
{
Toast.makeText(SYA.this,"No items to display",1000).show();
}
entry.close();
}
i really hope you anyone could help me to find a solution for this one. thanks in advance guys !!!
I have read some topics here about how to order listviews alphabetically using for example collections.sort or sortOrder but I can't make it work in my case, as I am not using an arraylist.
My listview is populate with elements from a database first put into a cursor, this way :
private void displayListView() {
// getExtra
Bundle bundle = getIntent().getExtras();
String title = bundle.getString("title", "Choose here :");
String inInterval = bundle.getString("inInterval");
Log.d(TAG, "inInterval = " + inInterval);
poititle.setText(title);
// put the results of the method in a cursor
c = dbHelper.findPoiInTable(inInterval);
displayCursor();
}
private void displayCursor() {
String[] columns = new String[] { DatabaseAdapter.COL_NAME,
DatabaseAdapter.COL_STREET, DatabaseAdapter.COL_WEBSITE,
DatabaseAdapter.COL_TELEPHONE, DatabaseAdapter.COL_REMARKS,
DatabaseAdapter.COL_PRICE, DatabaseAdapter.COL_MOBILE };
int[] to = new int[] { R.id.name, R.id.street, R.id.website,
R.id.telephone, R.id.remarks, R.id.price, R.id.mobile };
cursorAdapter = new SimpleCursorAdapter(this, R.layout.poi_info, c,
columns, to, 0);
ListView listView = (ListView) findViewById(R.id.poilistview);
// Assign adapter to ListView
listView.setAdapter(cursorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// Comportement des éléments de la listview
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(),
POIActivity.class);
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String street = ((TextView) view.findViewById(R.id.street))
.getText().toString();
String website = ((TextView) view.findViewById(R.id.website))
.getText().toString();
String telephone = ((TextView) view
.findViewById(R.id.telephone)).getText().toString();
String remarks = ((TextView) view.findViewById(R.id.remarks))
.getText().toString();
String price = ((TextView) view.findViewById(R.id.price))
.getText().toString();
String mobile = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// i.putExtra(ID_EXTRA, name) ;
i.putExtra(ID_NAME, name);
i.putExtra(ID_STREET, street);
i.putExtra(ID_WEBSITE, website);
i.putExtra(ID_TELEPHONE, telephone);
i.putExtra(ID_REMARKS, remarks);
i.putExtra(ID_PRICE, price);
i.putExtra(ID_MOBILE, mobile);
startActivity(i);
}
});
int numberResults = listView.getCount();
listviewCount.setText("( " + numberResults + " results ) : ");
}
I am looking for the easiest way to specify I want the results to be displayed alphabetically with the word (name / ID_NAME). So my question is, is there a way to add a line like :
sortOrder(name, byAlph)
When you query the database, just add in "ORDER BY ID_NAME".
Or if you want to use the query builder
to sort the data alphabetically do this:
Cursor cursor = getContentResolver.query(Phone.CONTENT_URI, null, null, null, Phone.DISPLAY_NAME + " ASC");
works like a charm
I am having items in a gridview which where displayed from sqlite ..Now using another thread i am fetching data from json webservice and storing the data in sqlite now i want to display the updated items in the same grid view along with the existing items..
private void displayUpdate(String Bid) {
Log.w("Update cALL","Executing Update");
System.out.println("aeqw cursor that in display table value"+getid(Bid).getCount());
Cursor cursorx =getid(Bid);
int p=Integer.parseInt(Bid);
System.err.println("Recieving Bid to displayUpdate method"+p);
if (getid(Bid) != null)
{
while(cursorx.moveToFirst())
{
Log.e("Entering Loop", "WHILE EXECUTING");
String temp_id1 = cursorx.getString(0);
System.err.println("Name related to Bid to displayUpdate method"+temp_id1);
final String temp_name1 = cursorx.getString(1);
System.err.println("Name related to Bid to displayUpdate method"+temp_name1);
String temp_author1=cursorx.getString(2);
String temp_desc1=cursorx.getString(3);
byte[] temp_image1 = cursorx.getBlob(4);
String temp_rating1 = cursorx.getString(5);
String temp_price1 = cursorx.getString(6);
String temp_update1=cursorx.getString(7);
System.err.println("Name related to Bid to displayUpdate method"+temp_name1);
mapIdUp.add(temp_id1);
mapNameUp.add(temp_name1);
mapAuthorUp.add(temp_author1);
mapDescUp.add(temp_desc1);
mapRatingUp.add(temp_rating1);
mapPriceUp.add(temp_price1);
mapUp.add(temp_image1);
mapUpdatedUp.add(temp_update1);
Log.e("temp_id from the sqlite", temp_id1);
Log.i(temp_name1, temp_name1);
Log.i(temp_desc1, temp_desc1);
Log.i(temp_rating1, temp_rating1);
Log.e(temp_update1,temp_update1);
String[] captionArray1 = (String[]) mapNameUp.toArray(new String[mapNameUp.size()]);
ItemsAdapter itemsAdapter1 = new ItemsAdapter(
Bookicon.this, R.layout.item,captionArray1);
gridView1=(GridView)findViewById(R.id.list);
gridView1.setAdapter(itemsAdapter1);
itemsAdapter1.notifyDataSetChanged();
gridView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
break;
}
}
}
this method is called in the second thread to display the updated books ..
where are this method is used to display all the items in the sqlite table
private void getDataAndPopulate()
{
Log.w("hello","zyuk,");
Cursor cursor = getEvents("bcuk_book");
while (cursor.moveToNext())
{
String temp_id = cursor.getString(0);
final String temp_name = cursor.getString(1);
String temp_author=cursor.getString(2);
String temp_desc=cursor.getString(3);
byte[] temp_image = cursor.getBlob(4);
String temp_rating = cursor.getString(5);
String temp_price = cursor.getString(6);
String temp_update=cursor.getString(7);
mapId.add(temp_id);
mapName.add(temp_name);
mapAuthor.add(temp_author);
mapDesc.add(temp_desc);
mapRating.add(temp_rating);
mapPrice.add(temp_price);
map.add(temp_image);
mapUpdated.add(temp_update);
Log.e("temp_id from the sqlite", temp_id);
Log.i(temp_name, temp_name);
Log.i(temp_desc, temp_desc);
Log.i(temp_rating, temp_rating);
Log.e(temp_update,temp_update);
String[] captionArray = (String[]) mapName.toArray(new String[mapName.size()]);
ItemsAdapter itemsAdapter = new ItemsAdapter(
Bookicon.this, R.layout.item,captionArray);
gridView=(GridView)findViewById(R.id.list);
gridView.setAdapter(itemsAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
}
Issue is i am not able to display the updated one whereas it was showing already stored items ..
If let us assume there are items like 1,2,3,4,5 when i update new item with 6 i.e one record it is displaying first item i.e 1. If update 2 records then it displaying only first two records..
How to solve this issue
I'm trying to organize favourites in my app. I have a database with three columns:
_id | name | description | star
1 London some desc.
2 Berlin some desc.
3 Paris some desc. yes
I want to display favourites in listview. The refreshCursor() returns list of names with "star" column value "yes":
private static final String COLUMN_STAR = "star";
private void refreshCursor() {
stopManagingCursor(cursor);
Intent intent = getIntent();
String TABLE_NAME = intent.getStringExtra("tableName");
cursor = database.query(TABLE_NAME, null, COLUMN_STAR + " = ?",
new String[] { "yes" }, null, null, null);
startManagingCursor(cursor);
}
It's ok.
Then after I click on Paris I send extra string with clicked position:
lvData.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String entryID = new Integer(position).toString();
Intent intent = new Intent();
intent.setClass(FavouritesActivity.this, ViewFavsActivity.class);
Bundle b = new Bundle();
b.putString("elementId", entryID);
intent.putExtras(b);
startActivity(intent);
}
});
But I get position (of endtryID) 0 and ViewFavsActivity displays decription of London.
How to get actual position of Cursor and send it to ViewFavsActivity?
Help, please.
Part of FavouritesActivity (onCreate): // method refreshCursor is above
refreshCursor();
String[] from = new String[] { COLUMN_NAME };
int[] to = new int[] { R.id.tvText };
scAdapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor,
from, to);
lvData = (ListView) findViewById(R.id.list);
lvData.setAdapter(scAdapter);
lvData.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String entryID = String.valueOf(id);
Intent intent = new Intent();
intent.setClass(FavouritesActivity.this, ViewFavsActivity.class);
Bundle b = new Bundle();
b.putString("elementId", entryID);
intent.putExtras(b);
startActivity(intent);
Part of ViewFavsActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// opening DB
refreshCursor();
bundle = getIntent().getExtras();
TextView titleText = (TextView) findViewById(R.id.titleText);
setTitle = database.query(TABLE_NAME, new String[] { COLUMN_DESC },
null, null, null, null, null);
int entryID = Integer.parseInt(bundle.getString("elementId"));
setTitle.moveToPosition(entryID);
titleText.setText(setTitle.getString(setTitle
.getColumnIndex(COLUMN_DESC)));
}
private void refreshCursor() {
stopManagingCursor(cursor);
Intent intent = getIntent();
cursor = database.query(TABLE_NAME, new String[] { COLUMN_ID, COLUMN_STAR, COLUMN_DESC },
"_id = ? AND star = ?",
new String[] { intent.getStringExtra("elementId"), "yes" },
null, null, null);
}
Added:
FavouritesActivity on pastebin
ViewFavsActivity on pastebin
Project
The real problem is that you are using two different Cursor's. You get position == 0 from:
cursor = database.query(TABLE_NAME, null, COLUMN_STAR + " = ?",
new String[] { "yes" }, null, null, null);
But then ask for position 0 in:
setTitle = database.query(TABLE_NAME, new String[] { COLUMN_DESC },
null, null, null, null, null);
So the odds are good that you will get a different result.
Also Bundle can hold any primitive data type and a few more complex ones. So you don't need to convert a number into a String and then back to its original data type...
A safer approach is to use the row's id, so use this in your OnItemClickListener:
b.putLong("elementId", id);
And in ViewFavsActivity:
long entryID = bundle.getLong("elementId");
setTitle = database.query(TABLE_NAME, new String[] { COLUMN_DESC },
"_id = " + entryID, null, null, null, null);
(Note: when in doubt always use ? and query()'s selectionArgs parameter to prevent SQL injection attacks, but you are working with a long that you retrieved as an index, so you're safe in this context.)
the problem here is that your Cursor only result one object. I belive is londe, is it correct ? If yes. Always the position result in the list view is added a element more one. Ex:
If the list view have only one object:
lvData.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Here will be showed the 0 position, not 3 like you whant.
String entryID = new Integer(position).toString();
}
});
the solution:
You need to cast a view in the method to your Object placed in the Adapter. Ex:
lvData.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Here will be showed the 0 position, not 3 like you whant.
MyObject object = (MyObject)view; //This object is placed in the Adapter.
object.getId(); //This method is inserted in my object or you can Override the method toString() to return the id of your query.
//Now you can send your ID to another Activity.
//Put your code here.
}
});
It´s this. I hope that I help you with my solution. Any question please put your question here.
--
thiago L. Silva
I have developed some sms application and I can't figure out how to solve this issue... in one layout I am displaying two textviews to display the number and the date of the sms... that works fine...
But now I am implementing the onListItemClick and I want that when list item is clicked the whole messages from the database should load into the new view.... How can I accomplish that...
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
dba.open();
Cursor c=dba.executeQuery("select rowid _id,* from messages where rowid="+position+";");
Log.v(tag, "value count"+ c.getCount());
if(c.getCount()>0)
{
Log.v(tag, "value count"+c.getCount());
c.moveToPosition(position);
Intent intent = new Intent();
String mesage = c.getString(c.getColumnIndex("msg"));
Log.v("Value passed to class", mesage);
intent.putExtra(name, mesage);
intent.setClass(this, NewInterface.class);
startActivity(intent);
}
}
And here is the code of the other class to which I am passing data.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messages);
tv4 = (TextView) findViewById(R.id.tvMessages);
Bundle bundle=getIntent().getExtras();
if(bundle!=null)
{
Log.v("Value got from class", bundle.getString("name"));
tv4.setText(bundle.getString("name"));
}
The list view is populated via this method from database containing the phone numbers....
private void openAndQueryDatabase() {
newDB=new DBAdapter(this);
try {
newDB.open();
Cursor c = newDB.executeQuery("select distinct nm,rowid _id from messages");
if (c != null ) {
if (c.moveToFirst())
Log.v(tag, "Stage 1");{
do {
String firstName = c.getString(c.getColumnIndex("nm"));
Log.v(tag, firstName);
// String date = c.getString(c.getColumnIndex("dt"));
results.add(firstName);
}while (c.moveToNext());
Log.v(tag, "Stage 1");
}
}
On click of List item you are opening a db to fetch data based on position clicked. Instead of trying to read the whole datain your first Activity, why don't you just pass the int position to the next Activity using Intent and then make the database query there. It would be easier and make more sense. If you still want to pass the wholde data , use a code similar to the one below (replacing your if(c.getCount>0) block):
ArrayList<String> arrayList ;
Cursor c=null;
if(c.moveToFirst()){
int x= c.getCount();
int y =c.getColumnIndex("msg");
arrayList = new ArrayList<String>(x);
for(int a=0;a<x;a++){
c.moveToPosition(a);
arrayList.add(c.getString(y));
}
Intent intent = new Intent(this,NewInterface.class);
intent.putStringArrayListExtra("msgs",arrayList );
startActivity(intent);
}
To get the number from one of the textViews of your clicked row of ListView:
TextView tv1=(TextView)v.findViewbyId(R.id.number)//Replace this with id of tv displaying numbers
String number = tv1.getText().toString();
Add these lines in your onListItemClick and then use this number in your query.