Related
I am getting response from server and display it using listview and it works fine,now what I am trying is i added autocompletetextview to search items by name,but when i run my app it crashes and showing errors..i already ask this
Tab1Activity.java
public class Tab1Activity extends ListActivity{
private ProgressDialog pDialog;
JSONArray Product=null;
private ListView listview;
ArrayList<HashMap<String,String>> aList;
ArrayList<HashMap<String, String>> arrayTemplist;
private static String PRODUCT_URL = "";
private static final String PRODUCT_DATA="Product";
private static final String PRODUCT_ID="productid";
private static final String PRODUCT_NAME="product_name";
private static final String PRODUCT_CODE="skucode";
private static final String PRODUCT_IMAGE="product_photo";
private static final String PRODUCT_WEIGHT="weight";
private static final String PRODUCT_SALERATE="sale_rate";
//private static final String PRODUCT_LOCATION="weight";
private CustomAdapterTabone adapter;
private TextView noacpt;
private AutoCompleteTextView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_tabone);
//noacpt=(TextView)findViewById(R.id.no_acceptedlist);
/*String strtext = getIntent().getStringExtra("id");
System.out.println("<<<<<<<< id : " + strtext);*/
final ListView listview = (ListView)findViewById(android.R.id.list);
//listview.setSelector( R.drawable.list_selector);
//listview.setSelector(R.drawable.listselector);
new LoadAlbums().execute();
aList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
inputSearch = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < aList.size(); i++)
{
String currentString =aList.get(i).get(Tab1Activity.PRODUCT_NAME);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(aList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(Tab1Activity.PRODUCT_NAME);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
adapter=new CustomAdapterTabone(getApplicationContext(), arrayTemplist);
listview.setAdapter(adapter);
/* SimpleAdapter adapters = new SimpleAdapter(Tab1Activity.this, arrayTemplist,R.layout.list_item_tabone, new String[] { PRODUCT_NAME
}, new int[] {
R.id.txtpronameacptedlist});
lv.setAdapter(adapters);
*/
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getApplicationContext(), AllProductDetails.class);
intent.putExtra("productid", aList.get(position).get(PRODUCT_ID));
startActivity(intent);
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Tab1Activity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(PRODUCT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Product = jsonObj.getJSONArray(PRODUCT_DATA);
for (int i = 0; i < Product.length(); i++) {
JSONObject c = Product.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(PRODUCT_ID, c.getString(PRODUCT_ID));
map.put(PRODUCT_NAME,c.getString(PRODUCT_NAME));
map.put(PRODUCT_CODE, c.getString(PRODUCT_CODE));
map.put(PRODUCT_IMAGE, c.getString(PRODUCT_IMAGE));
map.put(PRODUCT_WEIGHT, c.getString(PRODUCT_WEIGHT));
map.put(PRODUCT_SALERATE, c.getString(PRODUCT_SALERATE)+getResources().getString(R.string.rupee));
// map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterTabone(getApplicationContext(),result);
setListAdapter(adapter);
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
CustomAdapter
public class CustomAdapterTabone extends BaseAdapter{
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="product_name";
private static final String TAG_PROFILE="skucode";
private static final String TAG_IMAGE="product_photo";
private static final String TAG_CAST="weight";
private static final String TAG_AGE="sale_rate";
// private static final String TAG_LOCATION="weight";
public CustomAdapterTabone(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_tabone, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtpronameacptedlist);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidacptedlist);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecastacptedlist);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileageacptedlist);
// holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplaceacptedlist);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
//holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
First create a custom adapter implements filterable:
public class MyFilterableAdapter extends BaseAdapter implements Filterable {
private Context context;
private List<String> items;
private List<String> filteredItems;
private ItemFilter mFilter = new ItemFilter();
public MyFilterableAdapter(Context context, List<String> items) {
//super(context, R.layout.your_row, items);
this.context = context;
this.items = items;
this.filteredItems = items;
}
#Override
public int getCount() {
return filteredItems.size();
}
#Override
public Object getItem(int position) {
return filteredItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_search_merchant, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String location = filteredItems.get(position);
if (!location.isEmpty() || viewHolder != null) {
viewHolder.tvTitle.setText(location);
}
return convertView;
}
public static class ViewHolder {
TextView tvTitle;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = items.size();
final List<String> tempItems = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
if (items.get(i).toLowerCase().contains(filterString)) {
tempItems.add(items.get(i));
}
}
results.values = tempItems;
results.count = tempItems.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public Filter getFilter() {
return mFilter;
}
}
And than create a textwatcher
public class MyTextWatcher implements TextWatcher {
private MyCustomAdapter lAdapter;
public MyTextWatcher(MyCustomAdapter lAdapter) {
this.lAdapter = lAdapter;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
lAdapter.getFilter().filter(s.toString().toLowerCase());
}
}
And finally add your TextWatcher to your Search Edit Text:
final MyCustomAdapter lAdapter = new MyCustomAdapter(context, items);
EditText etSearch = (EditText) view.findViewById(R.id.et_search);
etSearch.addTextChangedListener(new SearchTextWatcher(lAdapter));
I hope this'll help you.
I am new to android development. I have implemented an activity which is Loading Json data to a listview. I have two activities now. First one is login Activity.Second one is loading list view activity.the json data is loading perfectly. but my problem is, when i pressed back button, the list view data is removing one by one. i have no idea where the problem is.
here is my main activity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
ImageButton login;
public static ArrayList<HashMap<String, String>> oslist;
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
static final String TAG_OS = "android";
static final String TAG_VER = "ver";
static final String TAG_NAME = "name";
static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loging);
oslist = new ArrayList<HashMap<String, String>>();
login = (ImageButton)findViewById(R.id.imageButton1);
new ArrayList<HashMap<String, String>>();
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.title);
name = (TextView)findViewById(R.id.artist);
api = (TextView)findViewById(R.id.time);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParser jParser = new JsonParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
Intent reult = new Intent(MainActivity.this,ViewList.class);
//reult.putStringArrayListExtra("map", oslist);
//startActivity(reult);
reult.putExtra("arraylist", oslist);
startActivityForResult(reult, 500);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my Listview Activity
public class ViewList extends Activity {
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Intent getres = getIntent();
//HashMap<String, String> hashMap = (HashMap<String, String>)getres.getSerializableExtra("map");
final ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
ListView list=(ListView)findViewById(R.id.list);
/* ListAdapter adapter = new SimpleAdapter(ViewList.this, arl,
R.layout.row,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.title,R.id.artist, R.id.time});*/
NewsRowAdapter adapter = new NewsRowAdapter(ViewList.this, R.layout.row, arl);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(ViewList.this, "You Clicked at "+arl.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
this is my Adapter Class
public class NewsRowAdapter extends BaseAdapter {
/*//ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
//ArrayList<HashMap<String, String>> data;
private List<Item> items;
//private Item objBean;
private int row;*/
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/*public NewsRowAdapter(Activity act, int resource, HashMap<String, List<String>> listChildData)) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.data = arrayList;
}*/
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
TextView title = (TextView) vi.findViewById(R.id.title);
TextView artist = (TextView) vi.findViewById(R.id.artist);
TextView time = (TextView) vi.findViewById(R.id.time);
ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
title.setText(song.get(MainActivity.TAG_VER));
artist.setText(song.get(MainActivity.TAG_NAME));
time.setText(song.get(MainActivity.TAG_API));
//imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);
Button accept = (Button) vi.findViewById(R.id.btnaccept);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//CustomizedListView getlist = new CustomizedListView();
final int x = (int) getItemId(position);
Toast.makeText(parent.getContext(),"you clicked "+ x , Toast.LENGTH_SHORT).show();
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "view clicked: " , Toast.LENGTH_SHORT).show();
}
});
return vi;
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int possision) {
// TODO Auto-generated method stub
return possision;
}
#Override
public long getItemId(int possision) {
// TODO Auto-generated method stub
return possision;
}
}
please some one help me...
Yes it will do so, When you press back button your activity get finished , So the view inside the activity will get deleted , Either you must keep the data in a seperate class, outside activity or keep the activity alive.
I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.
I am struggling with this problem for a while now. I am building a filterable list with edittext. The list populated fine initially BUT once I type something in the edittext field. The whole list is gone and returns no results. The following are my codes.
Note: My codes are mainly based on sacoskun's post.
ThreedListViewActivity.java
public class ThreedListViewActivity extends ActionBarActivity
{
// All static variables
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
ThreedListAdapterFilterable adapter;
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.threed_listview);
setTitle(R.string.view_3d);
list=(ListView)findViewById(R.id.list);
adapter = new ThreedListAdapterFilterable(this, songsList);
new MyAsyncTask().execute();
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
};
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog dialog=new ProgressDialog(ThreedListViewActivity.this);
#Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
#Override
protected void onPreExecute()
{
dialog.setMessage("Loading ...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Void result)
{
if(dialog.isShowing() == true)
{
dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_items, menu);
return true;
}
}
ThreedListAdapterFilterable.java
public class ThreedListAdapterFilterable extends BaseAdapter implements Filterable {
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public ThreedListAdapterFilterable(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return mDataShown.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.threed_listrow, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = mDataShown.get(position);
// Setting all values in listview
title.setText(song.get(ThreedListViewActivity.KEY_TITLE));
artist.setText(song.get(ThreedListViewActivity.KEY_ARTIST));
duration.setText(song.get(ThreedListViewActivity.KEY_DURATION));
imageLoader.DisplayImage(song.get(ThreedListViewActivity.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
#SuppressWarnings("unchecked")
#Override
public String convertResultToString(Object resultValue) {
return ((HashMap<String, String>)(resultValue)).get(ThreedListViewActivity.KEY_TITLE);
}
#Override
protected FilterResults performFiltering(CharSequence s) {
if(s != null)
{
ArrayList<HashMap<String, String>> tmpAllData = mAllData;
ArrayList<HashMap<String, String>> tmpDataShown = mDataShown;
tmpDataShown.clear();
for(int i = 0; i < tmpAllData.size(); i++)
{
if(tmpAllData.get(i).get(ThreedListViewActivity.KEY_TITLE).toLowerCase().startsWith(s.toString().toLowerCase()))
{
tmpDataShown.add(tmpAllData.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
}
else
{
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence s,
FilterResults results) {
if(results != null && results.count > 0)
{
notifyDataSetChanged();
}
}};
return nameFilter;
}
}
EDIT:
This is an updated adapter that will filter my list. BUT, it doesnt update my list when I backspace the text in the input text.
public class ProjectListAdapter extends BaseAdapter implements Filterable{
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
HashMap<String, String> song = new HashMap<String, String>();
ArrayList<HashMap<String, String>> filteredItems;
public ProjectListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
filteredItems = mDataShown;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mDataShown.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi;
if(convertView==null){
vi=new View(activity);
vi = inflater.inflate(R.layout.recents_listrow, null);
}else{
vi = (View)convertView;
}
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.company); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
title.setText(filteredItems.get(position).get(RecentsFragment.KEY_TITLE));
artist.setText(filteredItems.get(position).get(RecentsFragment.KEY_COMPANY));
imageLoader.DisplayImage(filteredItems.get(position).get(RecentsFragment.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null && constraint.toString().length() > 0) {
constraint = constraint.toString().toUpperCase();
ArrayList<HashMap<String, String>> filt = mDataShown;
ArrayList<HashMap<String, String>> tmpItems = mAllData;
filt.clear();
for(int i = 0; i < tmpItems.size(); i++) {
if(tmpItems.get(i).get(RecentsFragment.KEY_TITLE).toLowerCase().startsWith(constraint.toString().toLowerCase()))
{
filt.add(tmpItems.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.count = filt.size();
filterResults.values = filt;
return filterResults;
}else{
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mDataShown = (ArrayList<HashMap<String, String>>)results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return nameFilter;
}
}
The list fragment i am trying to implement: RecentsFragment
public class RecentsFragment extends ListFragment {
// All static variables
static final String URL = "http://www.sundancepost.com/ivue/projects.xml";
// XML node keys
static final String KEY_PROJECT = "project"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_COMPANY = "company";
static final String KEY_THUMB_URL = "thumb_url";
int mCurCheckPosition = 0;
ListView list;
ProjectListAdapter adapter;
ArrayList<HashMap<String, String>> projectsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recents_list, container, false);
list = (ListView)view.findViewById(android.R.id.list);
filterText = (EditText)view.findViewById(R.id.filter_box);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(null == savedInstanceState){
ConnectivityManager cMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cMgr.getActiveNetworkInfo() != null && cMgr.getActiveNetworkInfo().isConnectedOrConnecting()) {
new MyAsyncTask().execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please check your internet connection");
builder.setTitle("Failed to download resources");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
adapter = new ProjectListAdapter(getActivity(), projectsList);
list.requestFocus();
list.setTextFilterEnabled(true);
filterText.addTextChangedListener(filterTextWatcher);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra("title",projectsList.get(position).get(KEY_TITLE));
intent.putExtra("company", projectsList.get(position).get(KEY_COMPANY));
startActivity(intent);
}
});
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("workaround", mCurCheckPosition);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
public void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog recents_dialog = new ProgressDialog(getActivity());
#Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_PROJECT);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_COMPANY, parser.getValue(e, KEY_COMPANY));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
projectsList.add(map);
}
return null;
}
#Override
protected void onPreExecute()
{
projectsList.clear();
recents_dialog.setMessage("Loading ...");
recents_dialog.show();
recents_dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Void result)
{
if(recents_dialog.isShowing() == true)
{
recents_dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
}
public class FriendsListActivity extends Activity implements OnClickListener {
private Handler mHandler;
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_INSTALLED = "installed";
static final String KEY_THUMB_URL = "picture";
protected ListView friendsList;
protected static JSONArray jsonArray;
FriendsListAdapter adapter;
ArrayList> friendslist;
EditText filterText;
String apiResponse;
Button play, invite;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_list);
friendslist = new ArrayList<HashMap<String, String>>();
mHandler = new Handler();
ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
actionBar.setTitle("Facebook Friends");
actionBar.setHomeAction(new IntentAction(this, TruthorDareActivity
.createIntent(this), R.drawable.ic_home));
friendsList = (ListView) findViewById(R.id.friendsList);
filterText = (EditText) findViewById(R.id.searchBox);
filterText.addTextChangedListener(filterTextWatcher);
friendsList.setTextFilterEnabled(true);
friendsList.requestFocus();
play = (Button) findViewById(R.id.play);
invite = (Button) findViewById(R.id.invite);
play.setOnClickListener(this);
invite.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
apiResponse = extras.getString("API_RESPONSE");
callPlayList();
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
#Override
protected void onResume() {
super.onResume();
friendsList.requestFocus();
}
public void callPlayList() {
try {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
if (json_data.has("installed")
&& json_data.getBoolean("installed") == true) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, json_data.getString("id"));
map.put(KEY_NAME, json_data.getString("name"));
map.put(KEY_THUMB_URL, json_data.getString("picture"));
map.put(KEY_INSTALLED, json_data.getString("installed"));
friendslist.add(map);
}
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
adapter = new FriendsListAdapter(FriendsListActivity.this, friendslist);
friendsList.setAdapter(adapter);
}
public void callInviteList() {
try {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
if (!json_data.has("installed")) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, json_data.getString("id"));
map.put(KEY_NAME, json_data.getString("name"));
map.put(KEY_THUMB_URL, json_data.getString("picture"));
map.put(KEY_INSTALLED, "false");
friendslist.add(map);
}
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
adapter = new FriendsListAdapter(FriendsListActivity.this, friendslist);
friendsList.setAdapter(adapter);
}
public void clearAdapter(String params) {
friendslist.clear();
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
if (params.equals("invite")) {
callInviteList();
} else {
callPlayList();
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(FriendsListActivity.this, msg,
Toast.LENGTH_LONG);
toast.show();
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
clearAdapter("play");
break;
case R.id.invite:
clearAdapter("invite");
break;
default:
break;
}
}
}
The next part is the adapter class I use in a separate class file.
public class FriendsListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
public ArrayList<HashMap<String, String>> data;
public ArrayList<HashMap<String, String>> allData;
public HashMap<String, String> friends;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private ItemsFilter mFilter;
static SharedPreferences TODLoginPrefs;
#SuppressWarnings({ "unchecked", "static-access" })
public FriendsListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = (ArrayList<HashMap<String, String>>) d;
allData = (ArrayList<HashMap<String, String>>) data.clone();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
TODLoginPrefs = activity.getSharedPreferences("LogInSession",
activity.MODE_PRIVATE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.friends_list_row, null);
TextView user = (TextView) vi.findViewById(R.id.gname);
Button play = (Button) vi.findViewById(R.id.btnPlay);
Button invite = (Button) vi.findViewById(R.id.btnInvite);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image);
friends = new HashMap<String, String>();
friends = data.get(position);
user.setText(friends.get(FriendsListActivity.KEY_NAME));
imageLoader.DisplayImage(
friends.get(FriendsListActivity.KEY_THUMB_URL), thumb_image);
final String friendrId = (friends.get(FriendsListActivity.KEY_ID));
final String name = (friends.get(FriendsListActivity.KEY_NAME));
final String installed = (friends
.get(FriendsListActivity.KEY_INSTALLED));
if (installed.equals("false")) {
play.setVisibility(View.GONE);
invite.setVisibility(View.VISIBLE);
}
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(activity)
.setTitle("Create game with " + name + "?")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
UserFunction userFunction = new UserFunction();
JSONObject json_game = userFunction
.newGame(
activity,
"Facebook",
TODLoginPrefs
.getString(
"UserID",
""),
friendrId, null, null);
if (json_game.has("success")) {
activity.startActivity(new Intent(
activity,
TruthorDareActivity.class));
} else {
try {
Toast.makeText(
activity,
json_game
.getString("error_msg"),
Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).setNegativeButton(R.string.no, null).show();
}
});
invite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(activity)
.setTitle("Invite " + name + "?")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
UserFunction userFunction = new UserFunction();
JSONObject json_game = userFunction
.newInvite(
activity,
"Facebook",
TODLoginPrefs
.getString(
"UserID",
""),
friendrId, null, null);
if (json_game.has("success")) {
Bundle params = new Bundle();
params.putString("to", friendrId);
params.putString(
"message",
activity.getResources()
.getString(
R.string.app_request_message));
Utilities.facebook.dialog(activity,
"apprequests", params,
new AppRequestsListener());
} else {
try {
Toast.makeText(
activity,
json_game
.getString("error_msg"),
Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).setNegativeButton(R.string.no, null).show();
}
});
return vi;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemsFilter();
}
return mFilter;
}
private class ItemsFilter extends Filter {
#SuppressWarnings("unchecked")
#Override
public String convertResultToString(Object resultValue) {
return ((HashMap<String, String>) (resultValue))
.get(FriendsListActivity.KEY_NAME);
}
#Override
protected FilterResults performFiltering(CharSequence s) {
if (s != null) {
ArrayList<HashMap<String, String>> tmpAllData = allData;
ArrayList<HashMap<String, String>> tmpDataShown = data;
tmpDataShown.clear();
for (int i = 0; i < tmpAllData.size(); i++) {
if (tmpAllData.get(i).get(FriendsListActivity.KEY_NAME)
.toLowerCase()
.startsWith(s.toString().toLowerCase())) {
tmpDataShown.add(tmpAllData.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
} else {
return new FilterResults();
}
}
#SuppressWarnings("unchecked")
protected void publishResults(CharSequence prefix, FilterResults results) {
data = (ArrayList<HashMap<String, String>>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
public class AppRequestsListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
Toast.makeText(activity, "App request sent", Toast.LENGTH_SHORT)
.show();
activity.startActivity(new Intent(activity,
TruthorDareActivity.class));
}
#Override
public void onFacebookError(FacebookError error) {
Toast.makeText(activity, "Facebook Error: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Toast.makeText(activity, "App request cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
In the getFilter() method try this
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mDataShown = (ArrayList<HashMap<String, String>>)results.values;
ProjectListAdapter.this.setListData(mDataShown);
ProjectListAdapter.this.notifyDataSetChanged();
};
And to refresh the list on backspace
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if(s.toString().equalsIgnoreCase(""))
{
adapter.setListData(projectListdata)
adapter.notifyDataSetChanged();
}
else
adapter.getFilter().filter(s);
}
};
I couldn't find a way to get live updates via JSON to a listview.
My activity is requesting JSON data from a webpage and the code is:
public class Second extends Activity {
static final String Li_nk = "LinkName:";
static final String Image_name = "ImageName:";
ListView list;
public final static String AUTH = "authentication";
static final String KEY_THUMB_URL = "thumb_image"; // Uri.decode("http://zeesms.info/android_app_images/Koala.jpg");
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i2 = getIntent();
String wrd = i2.getStringExtra("entrd");
Log.v("keyis", wrd);
// if(wrd.equalsIgnoreCase("test")){
JSONObject j2 = JSONfunctions.getJSONfromURL("/webservice_search.php?keyword=" + wrd + "&format=json");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray jray = j2.getJSONArray("listings");
for (int i = 0; i < jray.length(); i++) {
Log.v("state", "json data being read");
JSONObject j3 = jray.getJSONObject(i);
String first = j3.getString("listing");
Log.v("sublist", first);
JSONObject j4 = j3.getJSONObject("listing");
String sec = j4.getString("links");
int maxLength = (sec.length() < 30) ? sec.length() : 27;
sec.substring(0, maxLength);
String cutsec = sec.substring(0, maxLength);
Log.v("links are", cutsec);
String img = j4.getString("image_name");
Log.v("image name is ", img);
// Uri
// dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", String.valueOf(i));
map.put(Li_nk, cutsec);
map.put(Image_name, j4.getString("image_name"));
map.put(KEY_THUMB_URL, "http://zeesms.info/android_app_images/" + img);
mylist.add(map);
}
}
catch (JSONException e) {
alertbox();
Log.e("loG_tag", "Error parsing" + e.toString());
}
list = (ListView) findViewById(R.id.lv1);
this.list.setEmptyView(findViewById(R.id.empty));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getApplicationContext(),"Click ListItem Number "
// + position, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.riffre.com/"));
startActivity(myIntent);
}
});
LazyAdapter adapter = new LazyAdapter(this, mylist);
list.setAdapter(adapter);
list.setItemsCanFocus(false);
// }
/*
* else{ alertbox(); }
*/
}
/*
* public void register(View view) { Log.w("C2DM",
* "start registration process"); Intent intent = new
* Intent("com.google.android.c2dm.intent.REGISTER");
* intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new
* Intent(), 0)); // Sender currently not used intent.putExtra("sender",
* "nonsenses#gmail.com"); startService(intent); }
*
* public void showRegistrationId(View view) { SharedPreferences prefs =
* PreferenceManager .getDefaultSharedPreferences(this); String string =
* prefs.getString(AUTH, "n/a"); Toast.makeText(this, string,
* Toast.LENGTH_LONG).show(); Log.d("C2DM RegId", string);
*
* }
*/
public void alertbox() {
new AlertDialog.Builder(this).setMessage("Invalid Keyword,No Results found").setTitle("Alert").setCancelable(true).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
}).show();
}
}
and I'm using a custom adapter with the code as follows:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.custom_row_view1, null);
TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
//TextView duration = (TextView)vi.findViewById(R.id); // distance
ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo
HashMap<String, String> jsn = new HashMap<String, String>();
jsn = data.get(position);
// Setting all values in listview
title.setText(jsn.get(Second.Li_nk));
artist.setText(jsn.get(Second.Image_name));
//duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(jsn.get(Second.KEY_THUMB_URL), thumb_image);
return vi;
}
}
What I want is that the application updates the listview with data every minute or so. Also the latest entry in the list should stay on top.
What would be the best way to do this?
Put your JSON parsing code, that's probably your try..catch block in a separate function and not in onCreate().
So can easily call that part every minute. let's say that function name LoadData() also add one more line adapter.notifyDataSetChanged() to update adapter/list every time.
now in your onCreate(), write this code to call that function every one minute,
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runable, 1000);
Now for second problem, to add new data at top..
I am just getting one thing in mind right now to write a loop , ADD THIS TO IN YOUR FUNCTION BEFORE CALLING ADAPTER NOTIFY CHANGE,like
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String,String>> mylistTemp = new ArrayList<HashMap<String,String>>();
for(int i = mylist.size()-1 ; i >=0;i--)
{
mylistTemp.add(mylist.get(i));
}
mylist = mylistTemp;
Well if your code above is working, you should be able to achieve your goal with the following steps:
Extract your JSON-Loading code into an AsyncTask, which you can trigger every minute. (AsyncTask)
Update your ListAdapter using the AsyncTask.
Here is a possible implementation of the onCreate() method, which will run an update-task every minute:
public class JSON_AndroidActivity extends Activity {
/** Called when the activity is first created. */
private JSONLoaderTask mJSONLoaderTask;
private Handler mHandler;
private ArrayAdapter<String> mArrayAdapter;
private Runnable mRefresher = new Runnable() {
#Override
public void run() {
mJSONLoaderTask = new JSONLoaderTask(JSON_AndroidActivity.this, mArrayAdapter);
mJSONLoaderTask.execute("");
mHandler.postDelayed(this, 1000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler.postDelayed(mRefresher, 1000);
}
}
And here is a hull implementation of a possible task, where you can do your heavy loading and update your adapter for the list:
public class JSONLoaderTask extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
private final ArrayAdapter<String> mArrayAdapter;
public JSONLoaderTask(Context pContext, ArrayAdapter<String> pArrayAdapter) {
this.context = pContext;
this.mArrayAdapter = pArrayAdapter;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String result = getJSONStream();
return result;
}
private String getJSONStream() {
//load your string here
return "";
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
// Update your ArrayAdapter
}
}