Populating a textview of a class with data from another class - android

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.

Related

Android: arrayAdapter throwing null pointer exception?

I'm having some issues with an array adapter.
this is what is in my lessonNotesList class:
mydb = new DBHelper(this);
//Creating an ArrayList of contacts data
ArrayList array_list = mydb.getAllLessonNotes();
//Creating an Array Adapter to manipulate the contacts data into a ListView
ArrayAdapter arrayAdapter = new ArrayAdapter(this,R.layout.list_layout, array_list);
//Adding the contacts to the list view.
lessonNote = (ListView)findViewById(R.id.listView1);
lessonNote.setAdapter(arrayAdapter);
//Setting an onClickListener to process the user's actions
lessonNote.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
//Prepare the data from the ListView item to be passed to new activity
//arg2 is increased by one as its a zero based index but the contacts table in the database works of a base index of 1
int id_To_Search = VALUE;
//Bundle extras = getIntent().getExtras();
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Log.d("Id is ^&*: ", String.valueOf(id_To_Search));
//Create a new intent to open the DisplayContact activity
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.LessonNotes.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
DBHelper class:
public ArrayList getAllLessonNotes()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from "+TABLE_LESSON_NOTES, null);
res.moveToFirst();
while(res.isAfterLast() == false)
{
array_list.add(res.getString(res.getColumnIndex(DATE)));
res.moveToNext();
}
return array_list;
}
The code crashes with a NULL pointer exception here:
lessonNote.setAdapter(arrayAdapter);
Any ideas why this is happening?
I've tried debugging and the debugger is telling me that the arrayAdatper contains 1 entry as it should
I have nearly the same code for a different page and it's working 100% fine..
Any suggestions would be welcome!
Thanks
Are you sure about that line ?
lessonNote = (ListView)findViewById(R.id.listView1);
It seems that in your layout XML, no view have "listView1" id.

getting the rowId of an item in the listView from sqlite database

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 !!!

Android getting ID from Database on Onitemclick listener

Hi I have searched through various questions related to this but i am unable to resolve the issue.
I am new to Android and i am developing an application for cricket. Here i am displaying a team from database whichcontains TeamId and TeamName.TeamId is a autogenerated Value. when i click on particular team i want to get the selected TeamId from database and i want to pass this TeamID as bundle to handle next function. But i am not getting the Team Id from database.
And below is the code what i am trying so far,
Intent intent = getIntent();
teamName=(ArrayList<String>)getIntent().getSerializableExtra("Teams");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,teamName);
teamList.setAdapter(adapter);
ListView OnITEMCLICk
teamList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int id,long position) {
// TODO Auto-generated method stub
textOfSelectedItem =((TextView) v).getText().toString();
Log.v("Clicked item id", " "+ id);
Toast.makeText(getApplicationContext(), "Clicked is " + id, Toast.LENGTH_SHORT).show();
oncreated = false;
Intent intent=new Intent(TeamOneActivity.this,TeamPlayersTeamOne.class);
intent.putExtra("selected teamname", textOfSelectedItem);
startActivity(intent);
///g.setSelectedTeamOne(textOfSelectedItem);
}
});
And this is my database
public ArrayList<String> getTeamID() {
// TODO Auto-generated method stub
ArrayList<String> TeamList=new ArrayList<String>();
String selectQuery="SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor=db.rawQuery(selectQuery, null);
if(cursor.moveToFirst())
{
do
{
//String TeamName=cursor.getString(cursor.getColumnIndex("TeamName"));
String TeamID=cursor.getString(cursor.getColumnIndex("TeamID"));
//TeamList.add(TeamName);
TeamList.add(TeamID);
}while(cursor.moveToNext());
cursor.close();
}
return TeamList;
}
Can any one help how to getId from Database
As I look at your code I see that you are passing to the intent the value of textOfSelectedItem, but your variable is filled with the text that you get from the TextView, which is in no way the ID that you need. You should just write a function to extract the teamID from the database based on the teamName (if that's what you want). So you could use a similar function but instead make the query something lile "SELECT ID FROM"+TABLE_NAME+"WHERE teamName="+nameOfTeam; And then just pass that result to your new intent.

Get length of String via its ID (R.id. )

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);
}
}

How to upgrade gridview in android using two threads with only one gridview in xml layout

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

Categories

Resources