I am working on laundry app. I have a listview (Fragment) like this so user can select the items.
My Problem is when I click the continue and then I come back to this screen again its value become zero. How can I save listview state.
I tried this code in my fragment but no luck. And also try save and restore instance state method but facing same problem.
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
ManFragment.java
package info.tranetech.laundry.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import info.tranetech.laundry.R;
import info.tranetech.laundry.adapter.JSONParser;
public class ManFragment extends Fragment {
private View rootView;
//Dry
public static String TAG_ITEM_MAN = "name";
public static String TAG_PRICE_DRY = "drycleaning_price";
public static String TAG_PRICE_WASH_IRON = "washiron_price";
public static String TAG_PRICE_WASH = "wash_price";
public static String TAG_PRICE_IRON = "iron_price";
public static String Name, Price_Dry, price_wash_iron, price_wash, price_iron;
public static String url_dry = "http://openspace.tranetech.com/mis/Laundry/men_dry.php";
static TextView ItemName, ItemPrice;
public static int Cat_Position;
ArrayList<HashMap<String, String>> DryList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> WashList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> WashIronList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> IronList = new ArrayList<HashMap<String, String>>();
ListView list;
ProgressDialog pdialog;
static Spinner Spin_Man;
public ManFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.man_pricelist, container, false);
// Locate the listview in listview_main.xml
list = (ListView) rootView.findViewById(R.id.man_listView);
Spin_Man = (Spinner) rootView.findViewById(R.id.spinner_man);
new DryData().execute();
Spin_Man.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
try {
switch (position) {
case 0:
Cat_Position = position;
Filllist();
getView();
break;
case 1:
Cat_Position = position;
Filllist();
getView();
break;
case 2:
Cat_Position = position;
Filllist();
getView();
break;
case 3:
Cat_Position = position;
Filllist();
getView();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "Position " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
return rootView;
}
private class DryData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(getActivity());
pdialog.setMessage("Please Wait...");
pdialog.setCancelable(true);
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
JSONParser jp = new JSONParser();
String jsonStr = jp.makeServiceCall(url_dry, JSONParser.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jobj = new JSONObject(jsonStr);
JSONArray jarray = jobj.getJSONArray("Data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobjin = jarray.getJSONObject(i);
String name = jobjin.getString(TAG_ITEM_MAN);
String price_dry = jobjin.getString(TAG_PRICE_DRY);
String price_wash_iron = jobjin.getString(TAG_PRICE_WASH_IRON);
String price_wash = jobjin.getString(TAG_PRICE_WASH);
String price_iron = jobjin.getString(TAG_PRICE_IRON);
HashMap<String, String> add_dry = new HashMap<String, String>();
add_dry.put(TAG_ITEM_MAN, name);
add_dry.put(TAG_PRICE_DRY, price_dry);
HashMap<String, String> add_wash_iron = new HashMap<String, String>();
add_wash_iron.put(TAG_ITEM_MAN, name);
add_wash_iron.put(TAG_PRICE_WASH_IRON, price_wash_iron);
HashMap<String, String> add_wash = new HashMap<String, String>();
add_wash_iron.put(TAG_ITEM_MAN, name);
add_wash.put(TAG_PRICE_WASH, price_wash);
HashMap<String, String> add_iron = new HashMap<String, String>();
add_iron.put(TAG_ITEM_MAN, name);
add_iron.put(TAG_PRICE_IRON, price_iron);
DryList.add(add_dry);
WashList.add(add_wash);
WashIronList.add(add_wash_iron);
IronList.add(add_iron);
}
} catch (JSONException e) {
e.printStackTrace();
// TODO: handle exception
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url_dry");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pdialog.isShowing()) {
pdialog.dismiss();
}
Filllist();
}
}
public void Filllist() {
// TODO Auto-generated method stub
Cus adapter = new Cus();
list.setAdapter(adapter);
// Helper.getListViewSize(list);
}
private class Cus extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return DryList.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) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.price_row, null);
}
ItemName = (TextView) convertView.findViewById(R.id.item_name);
ItemPrice = (TextView) convertView.findViewById(R.id.price);
Name = DryList.get(position).get(TAG_ITEM_MAN).toString();
Price_Dry = DryList.get(position).get(TAG_PRICE_DRY).toString();
price_wash_iron = WashIronList.get(position).get(TAG_PRICE_WASH_IRON).toString();
price_wash = WashList.get(position).get(TAG_PRICE_WASH).toString();
price_iron = IronList.get(position).get(TAG_PRICE_IRON).toString();
if (Cat_Position == 0) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + Price_Dry);
} else if (Cat_Position == 1) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + price_iron);
} else if (Cat_Position == 2) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + price_wash);
} else if (Cat_Position == 3) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + price_wash_iron);
}
return convertView;
}
}
}
Define Arraylist globally and call webservices as:
if (catListDao.size() > 0) {
adapter = new ExpertViewAdapter(act, R.layout.custom_expert, catListDao);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
} else {
if (!isViewShown) {
new FetchAllData(getActivity(), 2, 10, 0).execute();
}
}
}
Related
Hello I'm working on an app which has an edittext to search for items on the listview. If the user types a letter in the edittext the listview is getting filtered perfectlty.Have used Adapter also.Now i have following issues:
1)when i m clearing letters edittext my listview is not getting Updated..
2) if i enter wrong letter or letter which does not corrorsponds to any item of a listview the listview is getting clear.
Have gone thorugh exmaples in SO
Android filter listview custom adapter
And googled also for same problem but not getting solved it..Plz anybody help me..
Here is my code:
package com.AAAAA.AAAAA;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.AAAAA.adapter.UpdateSingleItemViewActivity;
import com.AAAAA.adapter.UpdatesAdapterList;
import com.AAAAA.local.database.DBController;
import com.AAAAA.AAAAA.AAAAA.constant.Constant;
import com.AAAAA.AAAAA.AAAAA.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setTextFilterEnabled(true);
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
//adapter.getFilter().filter(arg0);
}
});
}
}
Here is my Adapter:
package com.AAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.AAAA.AAAA.Cardiology_updates;
import com.AAAA.AAAA.R;
import com.AAAA.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String,String>> filterData;
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
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.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
//resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
}); return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(data);
}else{
for (HashMap<String,String> row: data) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Activity opens on cliking listview items:
package com.AAAAA.adapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
public class UpdateSingleItemViewActivity extends Activity {
int position;
String UpdateTile;
String UpdateDescription;
String population;
String UpdateImage;
//String position;
ViewPager viewPager;
PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_single_item_view);
Log.e("UpdateSingleItemViewActivity class",
"UpdateSingleItemViewActivity class");
/*
* WebView webview = new WebView(this); setContentView(webview);
*/
Button btnback = (Button) findViewById(R.id.Button01);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//WebView webview = (WebView) findViewById(R.id.webview);
Intent i = getIntent();
// Get the result of rank
UpdateTile = i.getStringExtra("UpdateTile");
// Get the result of country
UpdateDescription = i.getStringExtra("UpdateDescription");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
UpdateImage = i.getStringExtra("UpdateImage");
//i.putExtra("POSITION_KEY", position);
position = i.getExtras().getInt("position");
//webview.loadData(UpdateDescription, "text/html", null);
viewPager = (ViewPager) findViewById(R.id.viewpager_layout);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(UpdateSingleItemViewActivity.this, Cardiology_updates.FinalLocalDataList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
}
}
its Corrosponding adapter:
package com.AAAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
import com.AAAAA.imageloader.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
String UpdateTile;
String UpdateDescription;
//String population;
String UpdateImage;
String position;
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
ArrayList<HashMap<String,String>> filterData;
public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
WebView webview;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
//resultp =data.get(position);
webview=(WebView)itemView.findViewById(R.id.webview1);
//webview.setText(webview[position]);
webview.loadData(filterData.get(position).get(Cardiology_updates.UpdateDescription), "text/html", null);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
When used custom adapter always try to implement ViewHolder design pattern for ListView performance and use custom filter function instead Filterable implementation :
Custom filter funcation required two array list one is filterable data list and another one is for orignal data list :
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
Example :
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
public class UpdatesAdapterList extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> filterData;
private ArrayList<HashMap<String,String>> orignalData;
public ImageLoader imageLoader;
public UpdatesAdapterList(Context context,ArrayList<HashMap<String, String>> orignalData) {
this.context = context;
this.orignalData = orignalData;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.orignalData);
imageLoader = new ImageLoader(this.context);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
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.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Hello i have made a dynamic listview..Now i want to add filter in listview.if i enter text in edittext then item which mathces the search should display..have called addTextChangedListener to my edittext..and called a method filter in my adapter..but m not getting any idea what should i write in my filter method as it is a dynamic listview...
Here is my code:
package com.XXXXX.XXXXX;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.XXXXX.adapter.UpdateSingleItemViewActivity;
import com.XXXXX.adapter.UpdatesAdapterList;
import com.XXXXX.local.database.DBController;
import com.XXXXX.XXXXX.XXXXX.constant.Constant;
import com.XXXXX.XXXXX.XXXXX.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
adapter.getFilter().filter(arg0);
}
});
}
}
Here is my adapter class includes filter:
package com.XXXXX.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.XXXXX.XXXXX.Cardiology_updates;
import com.XXXXX.XXXXX.R;
import com.XXXXX.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter implements Filterable {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
HashMap<String, String> resultp = new HashMap<String, String>();
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView UpdateTitle;
TextView country;
TextView population;
ImageView UpdateImage;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_updateitem, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
UpdateTitle = (TextView) itemView.findViewById(R.id.txtUpdatetitle);
//country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
UpdateImage = (ImageView) itemView.findViewById(R.id.list_UpdateImage);
// Capture position and set results to the TextViews
UpdateTitle.setText(resultp.get(Cardiology_updates.UpdateTitle));
// country.setText(resultp.get(UpdatesActivity.COUNTRY));
// population.setText());
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(Cardiology_updates.UpdateImage), UpdateImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", resultp.get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", resultp.get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",resultp.get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", resultp.get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return itemView;
}
public Filter getFilter() {
Filter filter = new Filter() {
FilterResults results;
ArrayList<HashMap<String, String>> filteredList;
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Has the filtered values
data = (ArrayList<HashMap<String, String>>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// Holds the results of a filtering operation in values
results = new FilterResults();
filteredList= new ArrayList<HashMap<String, String>>();
//This is the search string user typed in EditText.
String searchString = constraint.toString().toUpperCase(Locale.getDefault());
/*
* Code to update the filteredList based on Search String.
*
* I'm just writing pseudo code for search, based on
* Cardiology_updates.UpdateTitle
*/
int mCount=data.size();
for (int i = 0; i < mCount; i++) {
HashMap<String, String> obj= data.get(i);
String updateTitle=obj.get(Cardiology_updates.UpdateTitle);
if(updateTitle.contains(searchString)){
filteredList.add(obj);
}
}
synchronized (this) {
// set the Filtered result to return
results.count = filteredList.size();
results.values = filteredList;
}
return results;
}
};
return filter;
}
}
You need to implement Filterable interface in your UpdatesAdapterList class.
For detailed explanation visit How to implement getfilter() with custom adapter that extends baseadapter?.
public class UpdatesAdapterList extends BaseAdapter implements Filterable {
...
#Override
public Filter getFilter(){
// Your Search logic goes here..
Filter filter = new Filter() {
FilterResults results;
ArrayList<HashMap<String, String>> filteredList;
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Has the filtered values
data = (ArrayList<HashMap<String, String>>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// Holds the results of a filtering operation in values
results = new FilterResults();
filteredList= new ArrayList<HashMap<String, String>>();
//This is the search string user typed in EditText.
String searchString = constraint.toString();
/*
* Code to update the filteredList based on Search String.
*
* I'm just writing pseudo code for search, based on
* Cardiology_updates.UpdateTitle
*/
int mCount=data.size();
for (int i = 0; i < mCount; i++) {
HashMap<String, String> obj= data.get(i);
String updateTitle=obj.get(Cardiology_updates.UpdateTitle);
if(updateTitle.contains(searchString)){
filteredList.add(obj);
}
}
synchronized (this) {
// set the Filtered result to return
results.count = filteredList.size();
results.values = filteredList;
}
}
return results;
}
};
return filter;
}
}
I've got a functioning Universal Image Loader that I'm trying to switch to grabbing the image URLs from JSON rather than the Constants Class that it normally uses. I've created a JSON Parsing Class that outputs an ArrayList called galleryArrList. But I can't figure out how to implement my JSON Parsing class and also how to modify the Adapter class in the UILGrid class to accept the galleryArrList String. Here are the Classes:
UILGrid Class:
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.mysite.wcbc.UKVPConstants.Extra;
public class UILGrid extends AbsListViewBaseActivity {
String[] imageUrls;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Extra.IMAGES);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}
private void startImagePagerActivity(int position) {
Intent intent = new Intent(this, CVP2.class); // ---- Change here
intent.putExtra(Extra.IMAGES, imageUrls);
intent.putExtra(Extra.IMAGE_POSITION, position);
startActivity(intent);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
}
my UILJSONParse Class:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class UILJSONParse extends AsyncTask<String, String, JSONObject> {
// url to make request
private static String url = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
// Hashmap for ListView
// ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> galleryArrList = new ArrayList<HashMap<String, String>>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
// gallery JSONArray
JSONArray JSArrGallery = null;
#Override
protected JSONObject doInBackground(String... arg0) {
// Creating JSON Parser instance
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(url);
return jsonOb;
}
#Override
protected void onPostExecute(JSONObject jsonOb) {
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_GALLERYURL, urlStr);
map.put(TAG_GALLERYDESCR, descrStr);
// adding HashMap map to ArrayList galleryArrList, defined
// above
galleryArrList.add(map);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
}// --- END onPostExecute
}// --- END UILJSONParse Class
I've figured this out since asking the question. I have a Button Interface Activity where an AsyncTask is called that grabs the JSON data when a button is clicked. The AysncTask then bundles the data and sends it to my Gallery Grid Class. The AsyncTask is calling the above JSON Parsing Class. So here's the code:
// --- artwork button
cartoon_BTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
jsonFileStr = "artwork_json";
new ArtworkJSON().execute();
}
});
// --- end artwork button
private class ArtworkJSON extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
String TAG_ID = "id";
String TAG_DESCR = "artworkdescr";
String TAG_MEDIUM = "artworkmedium";
String TAG_PRICE = "artworkprice";
String TAG_URL = "artworkurl";
ArrayList<HashMap<String, String>> hashArraylist;
ArrayList<String> urlArrayList;
ArrayList<String> idArrayList;
ArrayList<String> descrArrayList;
ArrayList<String> mediumArrayList;
ArrayList<String> priceArrayList;
String[] idStrArray, urlStrArray, descrStrArray, mediumStrArray,
priceStrArray;
String urlPathStr = "http://www.mysite.com/"
+ jsonFileStr + ".txt";
JSONArray JSArrArtwork = null;
String idStr, urlStr, descrStr, mediumStr, priceStr;
ProgressDialog loadImagesDia;
Intent bundleIn;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
loadImagesDia = new ProgressDialog(Main_Interface.this);
loadImagesDia.setMessage("Loading Images...");
loadImagesDia.setIndeterminate(false);
// Show progressdialog
loadImagesDia.show();
}
#Override
protected Void doInBackground(Void... params) {
hashArraylist = new ArrayList<HashMap<String, String>>();//
// Retrieve JSON Objects from the given URL address
jsonobject = JSONforGallery.getJSONfromURL(urlPathStr);
try {
// Locate the array name in JSON
JSArrArtwork = jsonobject.getJSONArray("artwork");
idArrayList = new ArrayList<String>();
urlArrayList = new ArrayList<String>();
descrArrayList = new ArrayList<String>();
mediumArrayList = new ArrayList<String>();
priceArrayList = new ArrayList<String>();
for (int i = 0; i < JSArrArtwork.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();//
JSONObject artworkJO = JSArrArtwork.getJSONObject(i);
map.put("id", artworkJO.getString(TAG_ID));//
map.put("url", artworkJO.getString(TAG_URL));//
map.put("descr", artworkJO.getString(TAG_DESCR));//
map.put("medium", artworkJO.getString(TAG_MEDIUM));//
map.put("price", artworkJO.getString(TAG_PRICE));//
idStr = artworkJO.getString(TAG_ID);
urlStr = artworkJO.getString(TAG_URL);
descrStr = artworkJO.getString(TAG_DESCR);
mediumStr = artworkJO.getString(TAG_MEDIUM);
priceStr = artworkJO.getString(TAG_PRICE);
hashArraylist.add(map);//
idArrayList.add(idStr);
urlArrayList.add(urlStr);
descrArrayList.add(descrStr);
mediumArrayList.add(mediumStr);
priceArrayList.add(priceStr);
idStrArray = idArrayList.toArray(new String[idArrayList
.size()]);
urlStrArray = urlArrayList.toArray(new String[urlArrayList
.size()]);
descrStrArray = descrArrayList
.toArray(new String[descrArrayList.size()]);
mediumStrArray = mediumArrayList
.toArray(new String[mediumArrayList.size()]);
priceStrArray = priceArrayList
.toArray(new String[priceArrayList.size()]);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
loadImagesDia.dismiss();
bundleIn = new Intent("com.veedabugmedia.ktg.UILGRID");
bundleIn.putExtra("idStrArrayKey", idStrArray);
bundleIn.putExtra("hashARKey", hashArraylist);
bundleIn.putExtra("urlStrArrayKey", urlStrArray);
bundleIn.putExtra("descrStrArrayKey", descrStrArray);
bundleIn.putExtra("mediumStrArrayKey", mediumStrArray);
bundleIn.putExtra("priceStrArrayKey", priceStrArray);
startActivity(bundleIn);
}
}
My updated UILGrid Activity:
public class UILGrid extends AbsListViewBaseActivity {
String[] idStr, imageUrls, descrStrGrid, mediumStrGrid, priceStrGrid;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
// Retrieve data from About_Interface on item click event
Intent getBundsIn = getIntent();
idStr = getBundsIn.getStringArrayExtra("idStrArrayKey");
imageUrls = getBundsIn.getStringArrayExtra("urlStrArrayKey");
descrStrGrid = getBundsIn.getStringArrayExtra("descrStrArrayKey");
mediumStrGrid = getBundsIn.getStringArrayExtra("mediumStrArrayKey");
priceStrGrid = getBundsIn.getStringArrayExtra("priceStrArrayKey");
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}// --- END onCreate
private void startImagePagerActivity(int position) {
Intent pagerIn = new Intent(this, UILPager.class);
pagerIn.putExtra("pagerUrlStrKey", imageUrls);
pagerIn.putExtra("pagerDescrStrKey", descrStrGrid);
pagerIn.putExtra("pagerMediumStrKey", mediumStrGrid);
pagerIn.putExtra("pagerPriceStrKey", priceStrGrid);
pagerIn.putExtra("pagerPositionKey", position);
startActivity(pagerIn);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
UILGrid.this.finish();
}
}
package com.nous.demoexample;
import static com.nous.demoexample.Constant.EIGTH_COLUMN;
import static com.nous.demoexample.Constant.FIFTH_COLUMN;
import static com.nous.demoexample.Constant.FIRST_COLUMN;
import static com.nous.demoexample.Constant.FOURTH_COLUMN;
import static com.nous.demoexample.Constant.SECOND_COLUMN;
import static com.nous.demoexample.Constant.SEVENTH_COLUMN;
import static com.nous.demoexample.Constant.SIXTH_COLUMN;
import static com.nous.demoexample.Constant.THIRD_COLUMN;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import com.paresh.demoexample.R;
public class MultiColumnActivity extends Activity implements OnClickListener {
private ArrayList<HashMap<String, String>> list;
Button filterButton;
Context context = this;
ListView lview;
// GridView lview;
final CharSequence[] items = { "Select all", " Date ", " Locationto",
" Client Name ", " Product code ", "Product Description",
"Location from", "Quantity", "Pallets" };
protected ArrayList<CharSequence> selectedInterests = new ArrayList<CharSequence>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
// lview = (GridView) findViewById(R.id.listview);
lview = (ListView) findViewById(R.id.listview);
filterButton = (Button) findViewById(R.id.filterbutton);
filterButton.setOnClickListener(this);
populateList();
listviewAdapter adapter = new listviewAdapter(this, list);
lview.setAdapter(adapter);
int lm = lview.getCount();
System.out.println(lm);
}
private void populateList() {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, "DATE");
temp.put(SECOND_COLUMN, "LOCATION TO");
temp.put(THIRD_COLUMN, "CLIENT NAME");
temp.put(FOURTH_COLUMN, "PRODUCT CODE");
temp.put(FIFTH_COLUMN, "PRODUCT DESCRIPTION");
temp.put(SIXTH_COLUMN, "LOCATION FROM");
temp.put(SEVENTH_COLUMN, "QUANTITY");
temp.put(EIGTH_COLUMN, "PALLETS");
list.add(temp);
HashMap<String, String> temp1 = new HashMap<String, String>();
temp1.put(FIRST_COLUMN, "7 / 2 / 2013");
temp1.put(SECOND_COLUMN, "SW00-000");
temp1.put(THIRD_COLUMN, "Mercury Direct");
temp1.put(FOURTH_COLUMN, "MERCUR-A5WW2013-491-000-000-Loose");
temp1.put(FIFTH_COLUMN, "A5 WORLDWIDE HOLS 13 C");
temp1.put(SIXTH_COLUMN, "Warehouse");
temp1.put(SEVENTH_COLUMN, " 5000");
temp1.put(EIGTH_COLUMN, "1");
list.add(temp1);
HashMap<String, String> temp2 = new HashMap<String, String>();
temp2.put(FIRST_COLUMN, "7 / 2 / 2013");
temp2.put(SECOND_COLUMN, "DAH22A");
temp2.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp2.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp2.put(FIFTH_COLUMN, "NORWAY 2013");
temp2.put(SIXTH_COLUMN, "ShrinkWrap");
temp2.put(SEVENTH_COLUMN, " 4000");
temp2.put(EIGTH_COLUMN, "1");
list.add(temp2);
HashMap<String, String> temp3 = new HashMap<String, String>();
temp3.put(FIRST_COLUMN, "7 / 2 / 2013");
temp3.put(SECOND_COLUMN, "DAH22A/02");
temp3.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp3.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp3.put(FIFTH_COLUMN, "NORWAY 2013");
temp3.put(SIXTH_COLUMN, "ShrinkWrap");
temp3.put(SEVENTH_COLUMN, " 4000");
temp3.put(EIGTH_COLUMN, "1");
list.add(temp3);
HashMap<String, String> temp4 = new HashMap<String, String>();
temp4.put(FIRST_COLUMN, "7 / 2 / 2013");
temp4.put(SECOND_COLUMN, "DAH22A/02");
temp4.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp4.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp4.put(FIFTH_COLUMN, "NORWAY 2013");
temp4.put(SIXTH_COLUMN, "ShrinkWrap");
temp4.put(SEVENTH_COLUMN, " 4000");
temp4.put(EIGTH_COLUMN, "1");
list.add(temp4);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.filterbutton: {
showDialog();
break;
}
default:
break;
}
}
private void showDialog() {
// arraylist to keep the selected items
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Fields");
/*
* boolean[] checkedInterests = new boolean[items.length]; int count =
* items.length;
*
* for (int i = 0; i < count; i++) { checkedInterests[i] =
* selectedInterests .contains(items[i]);
*
* }
*/
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
// indexSelected contains the index of item (of which
// checkbox checked)
#Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the
// selected items
// write your code when user checked the checkbox
seletedItems.add(indexSelected);
selectedInterests.add(items[indexSelected]); // by
// anup
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove
// it
// write your code when user Uchecked the checkbox
seletedItems.remove(Integer.valueOf(indexSelected));
}
onChangeSelectedSelection();
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on OK
// You can write the code to save the selected item here
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
});
AlertDialog dialog = builder.create();
dialog = builder.create();// AlertDialog dialog; create like this
// outside onClick
dialog.show();
}
protected void onChangeSelectedSelection() {
StringBuilder stringBuilder = new StringBuilder();
for (CharSequence selection : selectedInterests)
stringBuilder.append(selection + ",");
// filterButton.setText(stringBuilder.toString());
String input = selectedInterests.toString();
System.out.println(input);
if (input.contains("Date")) {
//here i want to display Date Only Listview
}
if(input.contains("Locationto")){
// here i want to display location to only in same list
}
}
}
Constant.java
package com.nous.demoexample;
public class Constant {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public static final String THIRD_COLUMN = "Third";
public static final String FOURTH_COLUMN = "Fourth";
public static final String FIFTH_COLUMN = "Fifth";
public static final String SIXTH_COLUMN = "Sixth";
public static final String SEVENTH_COLUMN = "Seventh";
public static final String EIGTH_COLUMN = "Eighth";
}
listvieadapter.java
package com.nous.demoexample;
import static com.nous.demoexample.Constant.FIRST_COLUMN;
import static com.nous.demoexample.Constant.FOURTH_COLUMN;
import static com.nous.demoexample.Constant.SECOND_COLUMN;
import static com.nous.demoexample.Constant.THIRD_COLUMN;
import static com.nous.demoexample.Constant.FIFTH_COLUMN;
import static com.nous.demoexample.Constant.SIXTH_COLUMN;
import static com.nous.demoexample.Constant.SEVENTH_COLUMN;
import static com.nous.demoexample.Constant.EIGTH_COLUMN;
import java.util.ArrayList;
import java.util.HashMap;
import com.paresh.demoexample.R;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class listviewAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
public listviewAdapter(Activity activity,
ArrayList<HashMap<String, String>> list) {
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth, txtFifth, txtSixth, txtSeventh, txtEigth;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
holder = new ViewHolder();
holder.txtFirst = (TextView) convertView
.findViewById(R.id.FirstText);
holder.txtSecond = (TextView) convertView
.findViewById(R.id.SecondText);
holder.txtThird = (TextView) convertView
.findViewById(R.id.ThirdText);
holder.txtFourth = (TextView) convertView
.findViewById(R.id.FourthText);
holder.txtFifth = (TextView) convertView
.findViewById(R.id.FifthText);
holder.txtSixth = (TextView) convertView
.findViewById(R.id.SixthText);
holder.txtSeventh = (TextView) convertView
.findViewById(R.id.SeventhText);
holder.txtEigth = (TextView) convertView
.findViewById(R.id.EigthText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.txtFirst.setText(map.get(FIRST_COLUMN));
holder.txtSe
cond.setText(map.get(SECOND_COLUMN));
holder.txtThird.setText(map.get(THIRD_COLUMN));
holder.txtFourth.setText(map.get(FOURTH_COLUMN));
holder.txtFifth.setText(map.get(FIFTH_COLUMN));
holder.txtSixth.setText(map.get(SIXTH_COLUMN));
holder.txtSeventh.setText(map.get(SEVENTH_COLUMN));
holder.txtEigth.setText(map.get(EIGTH_COLUMN));
return convertView;
}
}
I am able to display all data date wise location wise and ....together But i want to Filter data -date wise location means if we check in location wise then it should Print location Only if filter date wise it should display date ..in list please help i have tired much But unable to do this....i have create check Box for select option date wise filter , location wise filter so please check my code if u want i can send complete code .
If you are using EditText to search then you have to write your own filter method..here is an example Custom ListView Search .
you have to change filter method something like this.
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if(isDate)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}else{
if(wp.getLocation().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
}
notifyDataSetChanged();
}
The short version of my question: If I have a listview where each item has a button and that button causes a textview on that listitem to be updated, how do I make changes I make to the list row from a onClickListener in getView permanent?
Detailed description of problem: I have a listview and that listview has a "bump" button (equivalent to a "like" button on Facebook) and when a user presses this like button 3 things happen:
A async request is made to my api which records the "bump" by adding a record to one of my db tables. If the request is successful the api issues a response with 2 fields ( is_bumped(boolean) & bump_count(int) )
If the api request was successful then we grab bumpCount from the response and use it to update the bumpTv to reflect the new total number of times that list item has been "bumped".... example: "3 Bumps"
If the API request was successful and isBumped=true then we update the image resource to a version of my bump icon that looks selected/pressed.
All of this works just fine at first glance, but if you "bump" a list item and then scroll all the way to the bottom of the list and then back to the top, the list item you just bumped will no longer appear to be bumped unless you refresh the entire activity. I know this has to have something to do with the data that I bind to the adapter not being updated, but how do I go about updating without refreshing the entire update?
package com.quothor.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class NewLazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public FragmentManager frag_manager;
static class ViewHolder {
TextView name;
TextView div3;
TextView div2;
TextView bumpTv;
TextView message;
TextView commentsTv;
SmartImageView thumb_image;
ImageButton bumpBtn;
ImageButton requestBtn;
ImageButton settingsBtn;
TextView created ;
int position;
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d, FragmentManager manager) {
activity = a;
frag_manager=manager;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
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) {
ViewHolder holder;
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name); // title
holder.div3 = (TextView)convertView.findViewById(R.id.divider3); // title
holder.div2 = (TextView)convertView.findViewById(R.id.divider2); // title
holder.bumpTv = (TextView)convertView.findViewById(R.id.bump); // title
holder.message = (TextView)convertView.findViewById(R.id.message); // artist name
holder.commentsTv = (TextView)convertView.findViewById(R.id.comments); // artist name
holder.thumb_image = (SmartImageView) convertView.findViewById(R.id.list_image);
holder.bumpBtn= (ImageButton)convertView.findViewById(R.id.bump_btn);
holder.requestBtn = (ImageButton)convertView.findViewById(R.id.hidden_btn);
holder.settingsBtn = (ImageButton)convertView.findViewById(R.id.settings_btn);
holder.created = (TextView)convertView.findViewById(R.id.created); // duration
holder.bumpBtn.setTag(holder);
holder.bumpBtn.setOnClickListener(new Bump(position, update));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.i("LazyAdapter data", String.valueOf(position)+" "+update.toString());
if(update.get("bump_count") != null){
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
//holder.bumpBtn.setOnClickListener(new Bump(position, update));
String bump_count=update.get("bump_count");
String is_bumped=update.get("is_bumped");
//sets bump textview
if(bump_count.equals("0")){
}else if(bump_count.equals("1")){
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bump");
}else{
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bumps");
}
if(is_bumped.equals("true")){
holder.bumpBtn.setImageResource(R.drawable.quothor_thumb_blue);
//bumpBtn.setBackgroundResource(R.drawable.quothor_bump_btn_bg_black);
}else{
holder.bumpBtn.setImageResource(R.drawable.quothor_bump_icon_black);
//bumpBtn.setBackgroundResource(android.R.drawable.btn_default);
}
}
if(update.get("relationship_view")!=null){
if(update.get("uid")!=TabHostFragmentActivity.loggedin_uid){
if(update.get("relation_to_user")!=null){
holder.requestBtn.setVisibility(holder.requestBtn.VISIBLE);
String relation= update.get("relation_to_user");
if(relation.equals("Friend")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.friend_btn);
}else if(relation.equals("Familiar")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.familiar_btn);
}
holder.requestBtn.setOnClickListener(new myOnClickListener(position));
holder.settingsBtn.setOnClickListener(new myOnClickListener(position));
}
}
}
if(update.get("created") != null){
TextView created = (TextView)convertView.findViewById(R.id.created); // duration
String str_created=update.get("created");
long created_l = Long.parseLong(str_created);
String time_ago=TimeAgo.fromPhpTime(created_l);
created.setVisibility(convertView.VISIBLE);
created.setText(time_ago);
}
if(update.get("comment_count")!=null){
holder.div2.setVisibility(holder.div2.VISIBLE);
holder.commentsTv.setVisibility(holder.commentsTv.VISIBLE);
String comments = update.get("comment_count");
if(comments.equals("0")){
holder.commentsTv.setText("no comments");
}else if(comments.equals("1")){
holder.commentsTv.setText("1 comment");
}else{
holder.commentsTv.setText(comments+ " comments");
}
}else{
holder.commentsTv.setVisibility(holder.commentsTv.INVISIBLE);
}
// Setting all values in listview
holder.name.setText(update.get("name"));
if(update.get("message") != null){
holder.message.setText(update.get("message"));
}else{
holder.message.setVisibility(holder.message.INVISIBLE);
}
holder.thumb_image.setImageUrl(update.get("thumb_img"));
/*
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
*/
return convertView;
}
public class myOnClickListener implements OnClickListener{
private int position;
private String clicked_uid;
public myOnClickListener(int position){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid=update.get("uid");
Log.d("Clicked UID:", clicked_uid+"");
String relation= update.get("relation_to_user");
String uid = update.get("uid");
String name = update.get("name");
String thumb_img = update.get("thumb_img");
FragmentManager fm = frag_manager;
EditRelationshipDialog editRelationshipDialog = new EditRelationshipDialog().newInstance(uid,relation,name,thumb_img);
editRelationshipDialog.show(fm, "relationshipsdialog");
}
}
public class Bump implements OnClickListener{
private int position;
private String clicked_uid;
public Bump(int position, HashMap<String, String> update){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
final View theview=v;
Log.i("Update Position:", update.toString());
String msg_id=update.get("msg_id");
//ViewHolder mH = (ViewHolder) theview.getTag();
// mH.message.setText("clicked");
RequestParams params = new RequestParams();
params.put("msg_id", msg_id);
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post(TabHostFragmentActivity.token,"http://api/bump", params, new JsonHttpResponseHandler() {
#Override
public void onFailure(Throwable arg0, JSONObject arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
Log.i("bump request failed in lazy adapter", arg1.toString());
Toast.makeText(activity.getApplicationContext(), arg1.toString() , Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(JSONObject json) {
ViewHolder mH = (ViewHolder) theview.getTag();
try {
String is_bumped=json.getString("is_bumped");
String bump_count=json.getString("bump_count");
if(bump_count != null){
if(bump_count.equals("0")){
}else if(bump_count.equals("1")){
mH.div3.setVisibility(mH.div3.VISIBLE);
mH.bumpTv.setVisibility(mH.bumpTv.VISIBLE);
mH.bumpBtn.setVisibility(mH.bumpBtn.VISIBLE);
mH.bumpTv.setText(bump_count+" bump");
}else{
mH.div3.setVisibility(mH.div3.VISIBLE);
mH.bumpTv.setVisibility(mH.bumpTv.VISIBLE);
mH.bumpBtn.setVisibility(mH.bumpBtn.VISIBLE);
mH.bumpTv.setText(bump_count+" bumps");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String is_bumped=json.getString("is_bumped");
if(is_bumped.equals("true")){
mH.bumpBtn.setImageResource(R.drawable.quothor_thumb_blue);
//bumpBtn.setBackgroundResource(R.drawable.quothor_bump_btn_bg_black);
}else{
mH.bumpBtn.setImageResource(R.drawable.quothor_bump_icon_black);
//bumpBtn.setBackgroundResource(android.R.drawable.btn_default);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
EDIT: After taking the advice in the comments i was sure my list would begin functioning the way I had intended it to , but it only opened up a whole new can of hell....now for some reason if a user clicks the "bump" button anywhere in the first 6 items it works just fine, but beyond that something weird starts happening. when a user hits the bump button on one of the list items below the first 6 items it sends the wrong position and its a position somewhere between 0 and 6 ?!?!?
package com.quothor.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class NewLazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public FragmentManager frag_manager;
static class ViewHolder {
TextView name;
TextView div3;
TextView div2;
TextView bumpTv;
TextView message;
TextView commentsTv;
SmartImageView thumb_image;
ImageButton bumpBtn;
ImageButton requestBtn;
ImageButton settingsBtn;
TextView created ;
int position;
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d, FragmentManager manager) {
activity = a;
frag_manager=manager;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
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) {
ViewHolder holder;
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("position being scrolled over", String.valueOf(position));
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name); // title
holder.div3 = (TextView)convertView.findViewById(R.id.divider3); // title
holder.div2 = (TextView)convertView.findViewById(R.id.divider2); // title
holder.bumpTv = (TextView)convertView.findViewById(R.id.bump); // title
holder.message = (TextView)convertView.findViewById(R.id.message); // artist name
holder.commentsTv = (TextView)convertView.findViewById(R.id.comments); // artist name
holder.thumb_image = (SmartImageView) convertView.findViewById(R.id.list_image);
holder.bumpBtn= (ImageButton)convertView.findViewById(R.id.bump_btn);
holder.requestBtn = (ImageButton)convertView.findViewById(R.id.hidden_btn);
holder.settingsBtn = (ImageButton)convertView.findViewById(R.id.settings_btn);
holder.created = (TextView)convertView.findViewById(R.id.created); // duration
holder.bumpBtn.setTag(holder);
holder.bumpBtn.setOnClickListener(new Bump(position, update));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.i("LazyAdapter data", String.valueOf(position)+" "+update.toString());
if(update.get("bump_count") != null){
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
//holder.bumpBtn.setOnClickListener(new Bump(position, update));
String bump_count=update.get("bump_count");
String is_bumped=update.get("is_bumped");
//sets bump textview
if(bump_count.equals("0")){
}else if(bump_count.equals("1")){
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bump");
}else{
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bumps");
}
if(is_bumped.equals("true")){
holder.bumpBtn.setImageResource(R.drawable.quothor_thumb_blue);
//bumpBtn.setBackgroundResource(R.drawable.quothor_bump_btn_bg_black);
}else{
holder.bumpBtn.setImageResource(R.drawable.quothor_bump_icon_black);
//bumpBtn.setBackgroundResource(android.R.drawable.btn_default);
}
}
if(update.get("relationship_view")!=null){
if(update.get("uid")!=TabHostFragmentActivity.loggedin_uid){
if(update.get("relation_to_user")!=null){
holder.requestBtn.setVisibility(holder.requestBtn.VISIBLE);
String relation= update.get("relation_to_user");
if(relation.equals("Friend")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.friend_btn);
}else if(relation.equals("Familiar")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.familiar_btn);
}
holder.requestBtn.setOnClickListener(new myOnClickListener(position));
holder.settingsBtn.setOnClickListener(new myOnClickListener(position));
}
}
}
if(update.get("created") != null){
TextView created = (TextView)convertView.findViewById(R.id.created); // duration
String str_created=update.get("created");
long created_l = Long.parseLong(str_created);
String time_ago=TimeAgo.fromPhpTime(created_l);
created.setVisibility(convertView.VISIBLE);
created.setText(time_ago);
}
if(update.get("comment_count")!=null){
holder.div2.setVisibility(holder.div2.VISIBLE);
holder.commentsTv.setVisibility(holder.commentsTv.VISIBLE);
String comments = update.get("comment_count");
if(comments.equals("0")){
holder.commentsTv.setText("no comments");
}else if(comments.equals("1")){
holder.commentsTv.setText("1 comment");
}else{
holder.commentsTv.setText(comments+ " comments");
}
}else{
holder.commentsTv.setVisibility(holder.commentsTv.INVISIBLE);
}
// Setting all values in listview
holder.name.setText(update.get("msg_id"));
if(update.get("message") != null){
holder.message.setText(update.get("message"));
}else{
holder.message.setVisibility(holder.message.INVISIBLE);
}
holder.thumb_image.setImageUrl(update.get("thumb_img"));
/*
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
*/
return convertView;
}
public class myOnClickListener implements OnClickListener{
private int position;
private String clicked_uid;
public myOnClickListener(int position){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid=update.get("uid");
Log.d("Clicked UID:", clicked_uid+"");
String relation= update.get("relation_to_user");
String uid = update.get("uid");
String name = update.get("name");
String thumb_img = update.get("thumb_img");
FragmentManager fm = frag_manager;
EditRelationshipDialog editRelationshipDialog = new EditRelationshipDialog().newInstance(uid,relation,name,thumb_img);
editRelationshipDialog.show(fm, "relationshipsdialog");
}
}
public class Bump implements OnClickListener{
private int position;
private String clicked_uid;
public Bump(int position, HashMap<String, String> update){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
final View theview=v;
Log.i("POSITION BEING CLICKED",String.valueOf(position));
Log.i("Update Position:", update.toString());
String msg_id=update.get("msg_id");
Log.i("msg_id",msg_id);
//ViewHolder mH = (ViewHolder) theview.getTag();
// mH.message.setText("clicked");
RequestParams params = new RequestParams();
params.put("msg_id", msg_id);
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post(TabHostFragmentActivity.token,"http://api/content/bump", params, new JsonHttpResponseHandler() {
#Override
public void onFailure(Throwable arg0, JSONObject arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
Log.i("bump request failed in lazy adapter", arg1.toString());
Toast.makeText(activity.getApplicationContext(), arg1.toString() , Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(JSONObject json) {
ViewHolder mH = (ViewHolder) theview.getTag();
HashMap<String, String> latestUpdate = new HashMap<String, String>();
latestUpdate = data.get(position);
Log.i("list item being edited", latestUpdate.toString());
try {
String bump_count=json.getString("bump_count");
if(bump_count != null){
latestUpdate.put("bump_count", bump_count);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String is_bumped=json.getString("is_bumped");
latestUpdate.put("is_bumped", is_bumped);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
data.remove(position);
data.add(position, latestUpdate);
notifyDataSetChanged();
}
});
}
}
}
In the question's comments, it was established that even though the UI was being updated (based on user interaction), the underlying data used by adapter's getView() weren't.
Solution: Update the data source and call notifyDataSetChanged() on the adapter. Let getView() handle UI updates.
Read through the comments for more information.