sqlite database and listview - android

Okay, I have searched threw here and did not find my answer at all. What my android app is suppose to be doing is get a list from my php & mysql server, then store it on the database on the phone. This all works, and I can even create a listview with the information from my sqlite db. Where I am stuck as a new coder is trying to figure out how to display the information when they click on the listview item that will take them to another page that will show all the details for that listview.
So in short what I want is have my listview, items 1,item 2, item 3 for example, then when they click item 2, it gets the information for item 2 and displays it. Can someone point me in the correct direction, i know i have to use setOnClickListener, but just unsure how to make it look for that certain item.
public class Events extends Activity
{
// Identifies a particular Loader being used in this component
String event_name, event_time, event_price, event_loc;
static JSONObject object =null;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.events);
openDB();
new PrefetchData().execute();
// used to refresh my page.
Button button = (Button) findViewById(R.id.refresh);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
openDB();
new PrefetchData().execute();
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
closeDB();
}
private void openDB()
{
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB()
{
myDb.close();
}
private class PrefetchData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
myDb.deleteAll();
JsonParser jsonParser = new JsonParser();
String json = jsonParser.getJSONFromUrl("http://www.website.com/test.json");
Log.e("JSON Response: ", "> " + json);
if (json != null)
{
try
{
JSONObject parent = new JSONObject(json);
JSONArray eventDetails = parent.getJSONArray("event");
for(int i=0; i < eventDetails.length(); i++)
{
object = eventDetails.getJSONObject(i);
event_name = object.getString("event_name");
event_time = object.getString("event_time");
event_price = object.getString("event_price");
event_loc = object.getString("event_loc");
//event_pic = object.getString("event_pic");
myDb.insertRow(event_name,event_time,event_price,event_loc);
Log.e("JSON", "> " + event_name + event_time + event_price + event_loc );
}
} catch (JSONException e)
{
// TODO Auto-generated catch block
Log.e("Json Error", "Error: " + e.toString());
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
populateListViewFromDB();
myDb.close();
// After completing http call
// will close this activity and lauch main activity
//Intent i = new Intent(MainActivity.this, Events.class);
//i.putExtra("event_name", event_name);
//i.putExtra("event_time", event_time);
//i.putExtra("event_price", event_price);
//startActivity(i);
// close this activity
//finish();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB()
{
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_TIME, DBAdapter.KEY_PRICE, DBAdapter.KEY_LOC};
int[] toViewIDs = new int[]
{R.id.item_name};//, R.id.item_time};//, R.id.item_price, R.id.item_loc};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.item_layout, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewfordb);
myList.setAdapter(myCursorAdapter);
}
}

Don't use the setOnClickListener.
Be sure to use a CursorAdapter and to specify an ID column inside your db.
when you set the protected void onListItemClick(ListView l, View v, int position, long id) automatically the id is the ID inside the db. this way you can pass it through an intent and use the id to get back the data from the db.
Hope it's clear enough. Sorry i wrote quite in a rush
from your code simply add
myList.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//here the id value is what you need to take data from the db filtering by id
}
}
);

you should set listeners to your ListView something like this
private OnItemClickListener onListItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
// TODO YOUR CODE
}
};
private OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
YOUR_CODE
}
};
those are two types, longClicj and just click, you can use it both or one, its depends on your needs
also on your onCreate method you should set the listeners to your listView
listView.setOnItemClickListener(onListItemClickListener);
listView.setOnItemLongClickListener(onItemLongClickListener);

Related

How can I get the name of a clicked cell in my listview to load into a new activity?

How can I get the name of a specific cell in my listview to load into a new activity ? At present, when I click any of the arrows it loads the last person in my contacts (Yvonne) in the next activity that loads when the arrow is clicked. I want the name in the corresponding cell to load in the next activity. How can I do this?
For example, in the image above, I want Alexi to load into the next Activity. But instead I keep getting Yvonne.
At present my code looks like this:
public class MainActivity extends Activity {
// ArrayList called selectContacts that will contain SelectContact info
ArrayList<SelectContact> selectContacts;
ListView listView;
SearchView search;
SelectContactAdapter adapter;
String name;
String phoneNumber;
String lookupkey;
CharSequence nameofcontact;
// *****18-04-2016***
Cursor cursor;
// ListView mainListView;
// ArrayList hashMapsArrayList;
public String cleartext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//selectContacts is an empty array list that will hold our SelectContct info
selectContacts = new ArrayList<SelectContact>();
listView = (ListView) findViewById(R.id.contacts_list);
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Perhaps running this thread on the UI thread has solved the issue of the app
// crashing? ListView had not been updating properly, I think.
runOnUiThread(new Runnable() {
public void run() {
// we want to delete the old selectContacts from the listview when the Activity loads
// because it may need to be updated and we want the user to see the updated listview,
// like if the user adds new names and numbers to their phone contacts.
selectContacts.clear();
// we have this here to avoid cursor errors
if (cursor != null) {
cursor.moveToFirst();
}
try {
// get a handle on the Content Resolver, so we can query the provider,
cursor = getApplicationContext().getContentResolver()
// the table to query
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
// Null. This means that we are not making any conditional query into the contacts table.
// Hence, all data is returned into the cursor.
// Projection - the columns you want to query
null,
// Selection - with this you are extracting records with assigned (by you) conditions and rules
null,
// SelectionArgs - This replaces any question marks (?) in the selection string
// if you have something like String[] args = { "first string", "second#string.com" };
null,
// display in ascending order
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
// get the column number of the Contact_ID column, make it an integer.
// I think having it stored as a number makes for faster operations later on.
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
// get the column number of the DISPLAY_NAME column
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
// get the column number of the NUMBER column
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// ****
int contactlookupkey = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY);
// ****
cursor.moveToFirst();
// We make a new Hashset to hold all our contact_ids, including duplicates, if they come up
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
// get a handle on the contactid, which is a string. Loop through all the contact_ids
String contactid = cursor.getString(Idx);
// if our Hashset doesn't already contain the contactid string,
// then add it to the hashset
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
// get a handle on the display name, which is a string
name = cursor.getString(nameIdx);
// get a handle on the phone number, which is a string
phoneNumber = cursor.getString(phoneNumberIdx);
// String image = cursor.getString(photoIdIdx);
lookupkey = cursor.getString(contactlookupkey);
System.out.println("Id--->" + contactid + " Name--->" + name);
System.out.println("Id--->" + contactid + " Number--->" + phoneNumber);
System.out.println("Id--->" + contactid + " lookupkey--->" + lookupkey);
SelectContact selectContact = new SelectContact();
selectContact.setName(name);
selectContact.setPhone(phoneNumber);
selectContacts.add(selectContact);
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//into each inflate_listview, put a name and phone number, which are the details making
// our SelectContact, above. And SelectContacts is all these inflate_listviews together
// This is the first property of our SelectContactAdapter, a list
// The next part, MainActivity.this, is our context, which is where we want the list to appear
adapter = new SelectContactAdapter(selectContacts, MainActivity.this);
// adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listView.setFastScrollEnabled(true);
// we need to notify the listview that changes may have been made on
// the background thread, doInBackground, like adding or deleting contacts,
// and these changes need to be reflected visibly in the listview. It works
// in conjunction with selectContacts.clear()
// adapter.notifyDataSetChanged();
}
});
}}
//the is the arrow image, it opens the activity for show and edit
public void DisplayorEditContact(View v) {
System.out.println("works so far");
System.out.println(name);
Intent intent = new Intent(getApplicationContext(), EditorNewContact.class).putExtra("thecontactname",name);
startActivity(intent);
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onResume() {
//I want to clear the searchview text when my app resumes or closes, but I keep getting an error, my app shuts down
// cleartext = findViewById(R.id.searchView).toString();
// cleartext.isEmpty();
// search.setQuery("", false);
super.onResume();
// load the contacts again, refresh them, when the user resumes the activity
LoadContact loadContact = new LoadContact();
loadContact.execute();
// cursor.close();
}
}
The salient part of the code I believe is :
//the is the arrow image, it opens the activity for show and edit
public void DisplayorEditContact(View v) {
System.out.println("works so far");
System.out.println(name);
Intent intent = new Intent(getApplicationContext(), EditorNewContact.class).putExtra("thecontactname",name);
startActivity(intent);
}
And the child activity, into which I want Alexi to load (at present I keep getting Yvonne) looks like this :
public class EditorNewContact extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_contact);
String s= getIntent().getStringExtra("thecontactname");
System.out.println("the name is" + s);
EditText edittext = (EditText) findViewById(R.id.editText);
edittext.setText(s);
I was asked to share my SelectContactAdapter, so here it is :
public class SelectContactAdapter extends BaseAdapter {
//define a list made out of SelectContacts and call it _data
public List<SelectContact> _data;
//define an array list made out of SelectContacts and call it arraylist
private ArrayList<SelectContact> arraylist;
Context _c;
//define a ViewHolder to hold our name and number info, instead of constantly querying
// findviewbyid. Makes the ListView run smoother
ViewHolder v;
// RoundImage roundedImage;
public SelectContactAdapter(List<SelectContact> selectContacts, Context context) {
_data = selectContacts;
_c = context;
this.arraylist = new ArrayList<SelectContact>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
//we're naming our convertView as view
View view = convertView;
//if there is nothing there (if it's null) inflate the layout for each row
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.inflate_listview, null);
// Log.e("Inside", "here--------------------------- In view1");
//or else use the view (what we can see in each row) that is already there
} else {
view = convertView;
// Log.e("Inside", "here--------------------------- In view2");
}
v = new ViewHolder();
// So, for example, title is cast to the name id, in activity main,
// phone is cast to the id called no etc
v.title = (TextView) view.findViewById(R.id.name);
// v.check = (CheckBox) view.findViewById(R.id.check);
v.phone = (TextView) view.findViewById(R.id.no);
v.imageView = (ImageView) view.findViewById(R.id.arrowright);
// for each new cell with title, name, number etc...
//
final SelectContact data = (SelectContact) _data.get(i);
v.title.setText(data.getName());
// v.check.setChecked(data.getCheckedBox());
v.phone.setText(data.getPhone());
view.setTag(data);
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// _data is our list of contacts
_data.clear();
// If there is nothing in the searchview, if the charText length is 0,
// then show all the contacts
if (charText.length() == 0) {
_data.addAll(arraylist);
// or else....
} else {
for (SelectContact wp : arraylist) {
// If a contact's name matches the input thus far, which is charText,
// then include it in the listview.
if ((wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) || (wp.getPhone().toLowerCase(Locale.getDefault())
.contains(charText)))
{
_data.add(wp);
}
}
}
notifyDataSetChanged();
}
static class ViewHolder {
// In each cell in the listview show the items you want to have
ImageView imageView;
TextView title, phone;
// CheckBox check;
}
}
It is hard to predict how your code works without seeing the SelectContactAdapter source code. But I can suggest a probably easiest solution, which is using a tag
all you need to do is to set a tag to your arrow image somewhere in your adapter's getView method like this:
youArrowImage.setTag("here_is_a_name_of_a_row");
and then in your DisplayorEditContact(View v) you can access it like this:
String itemName = (String)v.getTag();
here I suppose that v is a reference to clicked arrow image
You could also just monitor the click in your ListView setOnItemClickListener.
// Click listener to bring to profile
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent viewProfileIntent = new Intent(getApplicationContext(), UserProfile.class);
viewProfileIntent.putExtra("name", selectContacts.get(position));
Log.i("User Tapped", selectContacts.get(position));
startActivity(viewProfileIntent);
}
});
Please add following line to your SelectContactsAdapter.java
final SelectContact data = (SelectContact) _data.get(i);
v.title.setText(data.getName());
v.phone.setText(data.getPhone());
// Please add this line to your existing code right after above lines
v.imageView.setTag(data.getName());
Modify your method as below
public void DisplayorEditContact(View v) {
System.out.println("works so far");
System.out.println(v.getTag().toString());
Intent intent = new Intent(getApplicationContext(), EditorNewContact.class).putExtra("thecontactname",v.getTag().toString());
startActivity(intent);
}
Hope this helps
Your this method will like this:
public void DisplayorEditContact(View v) {
TextView tvName = (TextView) v.findViewById(R.id.YOUR_TEXT_NAME);
System.out.println(tvName.getText().toString());
}
Hope this will solve your problem :)
You need to use onItemClickListener on your list view.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SelectContact contact = (SelectContact)parent.getItemAtPosition(position);
Intent secondActivity = new Intent(MainActivity.this, EditorNewContact.class);
secondActivity.putExtra("Key", contact);
startActivity(secondActivity);
}
});
Also, in your EditorNewContact activity, you will need to resolve this intent in the onCreate method, like:
Intent intent = getIntent();
SelectContact contact = (SelectContact) intent.get("Key");
Also, your SelectContact class can be Serializeable, If that is the can, the the intent will look like.
Intent secondActivity = new Intent(MainActivity.this, EditorNewContact.class);
secondActivity.putSerializeableExtra("Key", contact);
startActivity(secondActivity);
And, to resolve this:
Intent intent = getIntent();
SelectContact contact = (SelectContact) intent.getSerializableExtra("Key");
i hope this helps.

Android Studio ListView - null pointer exception when trying to extract text from selected item

I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);

Getting the listview item

I have a listview that I fill its items by downloading a user tweets and I'm trying to get the item (the tweet) to a toast on an onClick, but I'm getting weird data not the text.
public class FragmentTab1 extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
i = (ListView) rootView.findViewById(R.id.listViewTweets);
new LongOperation().execute("");
i.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
itemPosition = position;
// ListView Clicked item value
itemValue = adapter.getItem(position).toString();
// Show Alert
Toast.makeText(getActivity().getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , 1000)
.show();
}
});
return rootView;
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Intent intent = getActivity().getIntent();
String[] srch = new String[] {name};
ResponseList<User> users = null;
statusListTextOnly = new ArrayList<String>();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (User user : users) {
System.out.println("Friend's Name " + user.getName()); // this print my friends name
if (user.getStatus() != null)
{
System.out.println("Friend timeline");
try {
statusess = twitter.getUserTimeline(name);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
List<Tweet> tweets = new ArrayList<Tweet>();
Tweet[] stockArr = new Tweet[tweets.size()];
adapter = new TweetAdapter(FragmentTab1.this.getActivity(),
R.layout.listview_item_row, stockArr);
i.setAdapter(adapter);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
currently: the toast is Position: 18 Listitem: xx.xxx.xxx.xx#416f985
xxx.xxx.xxx.xx `is my package name`
The reason you are getting such weird Toast is because the text containing the Toast is an object of type Tweet.
What you need to do is get the text from that object. I don't know how your Tweet class looks, but I think it would be something like this:
itemValue = adapter.getItem(position).title;
This way the Toast will display a string and not an object.
You have to implement toString() method in your object of 'i' Type.
for e.g
if i is a object of Student Class like:
Class Student{
String name;
int marks;
public String toString(){
return ("Name="+name +"Marks="+marks);
}
As shown above you have to implement toSTring method. If you do not implement toString method in java/android default toString will return class name with #some address like currently it is returning.
onItemClick is giving position variable which you can use to retrieve the list item in that position.
The answers before explained why you are getting a "weird toast" so to fix that, in your tweetAdapter class you are using tweet.title as a string.
So try this:
adapter.getItem(position).title;
Because the adapter will get the item that is sent through your TweetAdapter, using the tweet.title here will work too.
Try this
String itemValue = ((TextView)view).getText().toString();
Hope this helps.
You can declare your Tweet[] stockArr array globally and can access it inside listview's onItemClick listener as -:
stockArr(position).getTweet().toString();
Anything you can access from Tweet object from above solution.
You can get your Adapter from setOnItemClickListener using
TweetAdapter mAdapter=((TweetAdapter)parent.getAdapter());
So on mAdapter.getItem(position) will help.

How to refresh a ListView in the activity

I have a ListActivity class. It has a button which sorts the item according to one of their attributes. But it so happens that the item are getting sort by their name but upon clicking the item of its original position is getting executed.
Here is the code snippet :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
mButton = (ToggleButton) findViewById(R.id.mButton);
ArrayList<myObject> ListData = new ArrayList<myObject>();
back = (ImageButton) findViewById(R.id.backButton);
label = (TextView) findViewById(R.id.likethis);
label.setText("List");
inputSearch = (EditText) findViewById(R.id.inputSearch);
//Manager -- class that reads from the sdcard
Manager plm = new Manager();
// get all files from sdcard
//getList() function of Manager class
//List declared outside oncreate()
this.List = plm.getList();
final ArrayList<myObject> backUp = new ArrayList<myObject>(songsList);
if(sortCalled) {
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
mButton.setChecked(true);
Collections.sort(List);
notifyDataChanged(List);
}
else {
mButton.setBackground(getResources().getDrawable(R.drawable.m_unchecked));
mButton.setChecked(false);
notifyDataChanged(backUp);
}
back.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
inputSearch.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
adapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
//ArrayList <Song> temp;
((SimpleAdapter) PlayListActivity.this.adapter).getFilter().filter(s, new Filter.FilterListener() {
public void onFilterComplete(int count) {
// TODO Auto-generated method stub
adapter.notifyDataSetChanged();
}
});
adapter.notifyDataSetChanged();
}
});
mButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mButton.isChecked()){
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
Collections.sort(List);
sortCalled = true;
notifyDataChanged(List);
}
else{
sortCalled = false;
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_unchecked));
notifyDataChanged(backUp);
}
}
});
}
public void settingListAdapter(SimpleAdapter adapter){
setListAdapter(adapter);
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int Index = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
// Sending Index to MainActivity
in.putExtra("Index", Index);
setResult(100, in);
// Closing ListView
finish();
}
});
}
public void notifyDataChanged(ArrayList<Song> songsList) {
// TODO Auto-generated method stub
setListAdapter(null);
sortCalled = true;
ArrayList<myObject> songsListData = new ArrayList<myObject>();
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
myObject ob = sList.get(i);
// adding HashList to ArrayList
ListData.add(ob);
}
ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String,String>>();
// int j = 0;
for(myObject i : ListData){
HashMap<String, String> feed = new HashMap<String, String>();
feed.put("Title", i.getTitle());
array.add(feed);
}
BaseAdapter adapter1;
// int i = 0;
// Adding menuItems to ListView
adapter1 = new SimpleAdapter(this, array,
R.layout.list_item, new String[]{"Title" }, new int[] {
R.id.Title });
setListAdapter(adapter1);
adapter1.notifyDataSetChanged();
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int Index = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
// Sending songIndex to MainActivity
in.putExtra("Index", Index);
setResult(100, in);
// Closing ListView
finish();
}
});
I think you should try this.when you sort the data of your listview.it is working me perfectly
adapter.notifyDataSetChanged();
Everytime you make a change to adapter you should call notifyDataSetChanged() in UIThread
Please check this video to understand listView better
Edit
For an ArrayAdapter, notifyDataSetChanged only works if you use the add, insert, remove, and clear functions on the Adapter.
When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add, insert, remove, clear, etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged every time the list is update. To call it on the UI-Thread use the runOnUiThread method of the Activity. Then notifyDataSetChanged will work.
You could try the Adapter.notifyDataSetChanged() function. It might work.
If you are using a SimpleCursorAdapter, calling requery() on the cursor attached to the adapter will automatically refresh the adapter and attached view.
If it's BaseAdapter content changes, you call BaseAdapter.notifyDataSetChanged() which will tell the ListView to update itself.
In other words you only need to make the following tiny change:
public void setValue(Object newValue) {
this.value = newValue;
notifyDataSetChanged();
}
Actually, since you're changing the state of an existing item (rather than adding new ones etc) then notifyDataSetInvalidated() would be a better choice.

Populating ListView from a SQLite database

public class ConnectDatabase extends Activity {
private SimpleDBAdapter mDbHelper;
private ListView list;
private String[] values;
private String[] list1;
private int i=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView )findViewById(R.id.simpleListView);
mDbHelper = new SimpleDBAdapter(ConnectDatabase.this);
mDbHelper.createDatabase();
mDbHelper.open();
values = mDbHelper.getEditTextValue();
mDbHelper.close();
for(i=0;i<10;i++) {
String tempvalue;
tempvalue=values[i];
list1[i]=tempvalue;
Log.v("log_tag"," tempvalue "+tempvalue);
Log.v("log_tag", "list1 is"+list1[i]);
//Log.v("log_tag"," list1"+list1[i]);
}
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values));
//list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
/*for(int i=0;i<values.length;i++) {
String templist=values[i];
list1[i]=templist;
}*/
String fname=values[position];
Log.v("log_tag", "The fname is"+ fname);
Intent intent=new Intent(ConnectDatabase.this, Userinfo.class);
intent.putExtra("FirstName",fname );
startActivity(intent);
}
});
// to remove the last comma
}
}
Here I am doing ListView from SQLite database and want to display in ListView with only the first 10 ListView rows at the time but I get the error at the line list1[i]=tempvalue; so I can't copy array here anyone can help me to do copy the array name values where I get all the Column index values from my SQLite database.
Hope anyone have an idea to do this.
Your post is quite hard to read, but I think the issue is that list1 has not been initialised.
You need to add a line like this:
list1 = new String[10];
before you attempt to set a value within the array.
ps - I picked a value of 10 as your for loop has i<10.

Categories

Resources