How do i add spinner inside listview row in android? - android

I am developing an app in this i have populate listview with json parser. Now i have to add local spinner array inside this listview single row.
How do i add locally spinner array inside this listview row. And also i want to get selected spinner values of listview. Following is my code please suggest me.
//activity
public class MyModifyPgmLvAddUserActivity1 extends AppCompatActivity {
private DBManager dbManager;
private ListView listView, listView1;
Toolbar toolbar;
private String TAG = MyModifyPgmLvAddUserAdapter.class.getSimpleName();
private ProgressDialog pDialog;
// private SimpleCursorAdapter adapter;
MyModifyPgmLvAddUserAdapter1 adapter;
static String RANK = "AsanaId";
static String COUNTRY = "Asananame";
static String POPULATION = "repetation";
ArrayList<PojoList> SubjectList = new ArrayList<PojoList>();
final static String[] mSpinnerItems = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
private static String url = "http://www.test.com/ypAndroid/api/getDefaultProgramlist";
String asananame, asanaid,duration, imageurl, imageversion, audiourl, audioversion, videourl, videoversion;
String sid;
boolean selected;
String id;
String[] subject = null;
String[] spinner = null;
String title;
long id1;
Button btnCreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_modifypgm_lv_add_user);
btnCreate = (Button) findViewById(R.id.button_submit);
dbManager = new DBManager(this);
dbManager.open();
Intent i = getIntent();
id= i.getStringExtra("id");
subject = i.getStringArrayExtra("subject");
spinner = i.getStringArrayExtra("spinner");
title= i.getStringExtra("title");
id1= Long.parseLong(id);
SubjectList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listview);
//Net Connection
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null){
AlertDialog.Builder alert = new AlertDialog.Builder(MyModifyPgmLvAddUserActivity1.this);
// new AlertDialog.Builder(MyModifyProgramEditDeleteActivity.this)
alert.setTitle(getResources().getString(R.string.app_name));
alert.setMessage(getResources().getString(R.string.no_internet));
alert.setPositiveButton("OK", null).show();
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Do something here where "ok" clicked and then perform intent from activity context
Intent intent = new Intent(MyModifyPgmLvAddUserActivity1.this, MyYogaPosesSubMenuActivity.class);
MyModifyPgmLvAddUserActivity1.this.startActivity(intent);
}
});
alert.show();
}
else {
new MyModifyPgmLvAddUserActivity1.DownloadJSON().execute();
}
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkButtonClick();
Intent modify_intent = new Intent(MyModifyPgmLvAddUserActivity1.this, MyModifySavedProgramActivity1.class);
modify_intent.putExtra("subject", spinner);
modify_intent.putExtra("spinner", subject);
modify_intent.putExtra("id", id);
modify_intent.putExtra("title", title);
startActivity(modify_intent);
}
});
}
private void checkButtonClick() {
ArrayList<String> list1= new ArrayList<>();
ArrayList<String> list2= new ArrayList<>();
// ArrayList<String> list3= new ArrayList<>();
PojoList pojo = null;
ArrayList<PojoList> countryList = adapter.SubjectListTemp;
for (int i = 0; i < countryList.size(); i++) {
pojo = countryList.get(i);
if (pojo.isSelected()) {
// responseText.append("\n" + country.getName());
list1.add(pojo.getAsanName());
// list2.add(convertArrayToString(subject));
list2.add(pojo.getAsanId());
// list2.add(convertArrayToString(spinner));
}
}
String [] aIds = list1.toArray(new String[list1.size()]);
String [] aNames = list2.toArray(new String[list2.size()]);
dbManager.update(id1, aIds, aNames);
// dbManager.insert(title, names, spinner);
// dbManager.set_datetime_next(id, names, spinner);
}
public static String[] convertStringToArray(String str){
String[] arr = str.split(strSeparator);
return arr;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MyModifyPgmLvAddUserActivity1.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
PojoList pojo;
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject o = new JSONObject(jsonStr);
JSONArray restaurants = o.getJSONArray("getdefaultprogramlist");
for (int k = 0; k < restaurants.length(); k++) {
JSONObject rating1 = restaurants.getJSONObject(k);
asanaid = rating1.getString("programid");
Log.d("TestJson asanaid", asanaid);
asananame = rating1.getString("programname");
Log.d("TestJson asananame", asananame);
for (int i = 0; i < restaurants.length(); i++) {
JSONObject restaurant = restaurants.getJSONObject(i);
JSONArray ratings = restaurant.getJSONArray("ProgramItem");
for (int j = 0; j < ratings.length(); j++) {
JSONObject rating = ratings.getJSONObject(j);
String stepnumber = rating.getString("AsanaId");
Log.d("TestJson stepnumber", stepnumber);
String stepdesc = rating.optString("Asananame");
Log.d("TestJson stepdesc", stepdesc);
String stepimg = rating.getString("duration");
Log.d("TestJson stepimg", stepimg);
String stepimgeversion = rating.getString("repetation");
Log.d("TestJson stepimgvrsion ", stepimgeversion);
// int sid = Integer.parseInt(convertArrayToString(mSpinnerItems));
pojo = new PojoList(stepnumber, stepdesc, selected, convertArrayToString(mSpinnerItems));
SubjectList.add(pojo);
System.out.println("Size of Entry list from Map: " + SubjectList.size());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void args) {
if (pDialog.isShowing())
pDialog.dismiss();
adapter = new MyModifyPgmLvAddUserAdapter1(MyModifyPgmLvAddUserActivity1.this, R.layout.my_yoga_poseslv_add_user_single_item, SubjectList);
listView.setAdapter(adapter);
}
}
public static String strSeparator = ",";
public static String convertArrayToString(String[] array){
String str = "";
for (int i = 0;i<array.length; i++) {
str = str+array[i];
// Do not append comma at the end of last element
if(i<array.length-1){
str = str+strSeparator;
}
}
return str;
}
}
//PojoList
public class PojoList {
String AsanName = null;
String AsanId = null;
boolean selected = false;
String sid = null;
String sarray = null;
boolean sSelected = false;
public PojoList(String Sname, String SFullForm, boolean selected, String Sarray) {
super();
this.AsanName = Sname;
this.AsanId = SFullForm;
this.selected = selected;
this.sarray = Sarray;
// this.sid = Sid;
}
public String getAsanName() {
return AsanName;
}
public void setAsanName(String code) {
this.AsanName = code;
}
public String getAsanId() {
return AsanId;
}
public void setAsanId(String id) {
this.AsanId = id;
}
#Override
public String toString() {
return AsanName + " " + AsanId ;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getId() {
return sarray;
}
public void setId(String sarray) {
this.sarray = sarray;
}
}
//adapter
public class MyModifyPgmLvAddUserAdapter1 extends ArrayAdapter<PojoList> {
public ArrayList<PojoList> MainList;
public ArrayList<PojoList> SubjectListTemp;
Context context;
private String[] mSpinnerItems = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
// public ListAdapter.SubjectDataFilter subjectDataFilter ;
public MyModifyPgmLvAddUserAdapter1(Context context, int id, ArrayList<PojoList> subjectArrayList) {
super(context, id, subjectArrayList);
this.SubjectListTemp = new ArrayList<PojoList>();
this.SubjectListTemp.addAll(subjectArrayList);
this.MainList = new ArrayList<PojoList>();
this.MainList.addAll(subjectArrayList);
}
public class ViewHolder {
TextView SubjectName, aId;
TextView SubjectFullForm, aName;
CheckBox cb;
Spinner spinner;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.my_yoga_poseslv_add_user_single_item, null);
holder = new ViewHolder();
holder.aName = (TextView) convertView.findViewById(R.id.listview_tv);
holder.aId = (TextView) convertView.findViewById(R.id.listview_id);
holder.cb = (CheckBox) convertView.findViewById(R.id.listview_cb);
holder.spinner = (Spinner) convertView.findViewById(R.id.listview_spinner);
holder.cb.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
PojoList pojo = (PojoList) cb.getTag();
Toast.makeText(getContext(),
"Clicked on Checkbox: " + cb.getText() +
"Clicked on Checkbox: "+
" is " + cb.isChecked() + "Id is : "+ pojo.getAsanName(),
Toast.LENGTH_LONG).show();
pojo.setSelected(cb.isChecked());
}
});
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_1, mSpinnerItems);
holder.spinner.setAdapter(spinnerAdapter);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
PojoList pojo = SubjectListTemp.get(position);
holder.aName.setText(pojo.getAsanName());
holder.cb.setText(pojo.getAsanId());
holder.cb.setChecked(pojo.isSelected());
holder.cb.setTag(pojo);
// holder.spinner.setSelection(Integer.parseInt(pojo.getId()));
holder.spinner.setSelected(pojo.isSelected());
return convertView;
}
}
//list row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#cccccc">
<Spinner
android:id="#+id/listview_spinner"
style="#style/AppTheme"
android:layout_width="42dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp" />
<CheckBox
android:id="#+id/listview_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="2dp"
android:layout_marginLeft="4dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/listview_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp"
android:text="TextView"
android:textSize="1sp"
android:visibility="invisible"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/listview_imgs"
android:layout_toEndOf="#+id/listview_imgs" />
<TextView
android:id="#+id/listview_id"
android:layout_width="wrap_content"
android:visibility="invisible"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/listview_spinner"
android:layout_alignRight="#+id/listview_spinner"
android:layout_alignTop="#+id/listview_imgs"
android:text="TextView" />
</RelativeLayout>
</LinearLayout>

I have created a basic project to show you how to setup a simple Spinner. This is my xml for the list row:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:padding="20dp">
<TextView
android:id="#+id/row_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/row_item_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:padding="2dp" />
This is the adapter for the listview:
public class BasicSpinnerAdapter extends BaseAdapter {
private ArrayList<String> mSpinnerItems;
private ArrayList<String> mData;
private Context mContext;
public BasicSpinnerAdapter(ArrayList<String> data, ArrayList<String> spinnerItems, Context context) {
mData = data;
mContext = context;
mSpinnerItems = spinnerItems;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_item_spinner, null);
}
TextView textView = (TextView) view.findViewById(R.id.row_item_textview);
Spinner spinner = (Spinner) view.findViewById(R.id.row_item_spinner);
textView.setText(mData.get(position));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mSpinnerItems);
spinner.setAdapter(adapter);
return view;
}
And this is my Activity, where I start it all:
public class SpinnerListviewActivity extends AppCompatActivity {
private ListView lvSpinner;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_listview_activity);
lvSpinner = (ListView) findViewById(R.id.listview_spinner);
ArrayList<String> mData = new ArrayList<>();
mData.add("Test1");
mData.add("Test2");
mData.add("Test3");
mData.add("Test4");
ArrayList<String> mSpinnerData = new ArrayList<>();
mSpinnerData.add("1");
mSpinnerData.add("2");
mSpinnerData.add("3");
mSpinnerData.add("4");
BasicSpinnerAdapter adapter = new BasicSpinnerAdapter(mData, mSpinnerData, this);
lvSpinner.setAdapter(adapter);
}
}
The xml for my Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listview_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
A screenshot of the Listview:
Hope this gives you an idea of how to setup a basic Spinner in a List row. Feel free to ask any questions!

Related

EditText AutoCompleteTextView When Typing Using Custom Adapter Json Fragment

I want EditText become AutoComplete when user start typing in the EditText field. I have create this code
public class PegawaiFragment extends Fragment {
public static PegawaiFragment newInstance() {
PegawaiFragment fragment = new PegawaiFragment();
return fragment;
}
String namapegawai;
AutoCompleteTextView textAutoComplete;
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://192.168.43.241/Android/MyKoperasi/PegawaiDashboard.php";
List<String> IdList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pegawai, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
namapegawai = prefs.getString(MainActivity.UserName,MainActivity.UserName);
TextView NamaPegawai = v.findViewById(R.id.TextViewNamaPegawai);
NamaPegawai.setText(namapegawai);
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
StudentListView = v.findViewById(R.id.listview2);
progressBar = v.findViewById(R.id.progressBar1);
new GetHttpResponse(getActivity()).execute();
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
//Intent intentSemuaMemberLihat = new Intent(getActivity(),SemuaMemberLihat.class);
// Sending ListView clicked value using intent.
//intentSemuaMemberLihat.putExtra("ListViewValue", IdList.get(position).toString());
//startActivity(intentSemuaMemberLihat);
}
});
return v;
}
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}
}
This code shows perfect, but when I start typing in EditText which in autoCompleteTextView1, no suggestion name come out. I think this is in here
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
But why the EditText doesn't show the suggestions? instead, my ListView works perfect there.
Here is my XML code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.network.poeja.mykoperasi.PegawaiFragment">
<TextView
android:id="#+id/TextViewNamaPegawai"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:layout_weight="1"
android:id="#+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Text Auto Complete"
android:layout_below="#+id/TextViewNamaPegawai">
<requestFocus />
</AutoCompleteTextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:layout_below="#+id/autoCompleteTextView1">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_below="#+id/logos"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dip"/>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
</RelativeLayout>
</FrameLayout>
===============ADAPTER CLASS
public class ListAdapterClass extends BaseAdapter {
Context context;
List<Member> valueList;
public ListAdapterClass(List<Member> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_item, null);
viewItem.TextViewNama = convertView.findViewById(R.id.textViewNama);
viewItem.TextViewNrp = convertView.findViewById(R.id.textViewNrp);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewNama.setText(valueList.get(position).nama);
viewItem.TextViewNrp.setText(valueList.get(position).nrp);
return convertView;
}
}
class ViewItem
{
TextView TextViewNama, TextViewNrp;
}
You need to provide Array containing data on ArrayAdapter. Its the source of data where adapter will search. Here is an example how to use ArrayAdapter and AutoCompleteTextView -
public class MainActivity extends Activity {
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, data);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
}
Based on your code of AutoCompleteTextView. I made a solution.
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
GetHttpResponse getHttpResponse = new GetHttpResponse(getActivity());
getHttpResponse.execute();
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
List<Member> studentList = getHttpResponse.getStudentList();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, studentList.toArray(new String[studentList.size()]));
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
Add a method to get studentList from GetHttpResponse class -
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
public ArrayList<Member> getStudentList(){
return this.studentList;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}

getting the selected item with checkbox in listview along side with the quantity number picker

i am creating a app that allows users to select the food they want and displaying the ordered food.
My listview has a checkbox, 3 textview and a numberpicker. I am now trying to get the selected items and quantity from the numberpicker and displaying on the next activity. I have tried some codes but unsure whether it works.
I am kinda new with android studio.How should i approach it from now on? Below are my codes
Listview row :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView1"
android:id="#+id/txt1"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
style="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView2"
android:id="#+id/txt2"
android:textStyle="bold"
android:layout_below="#+id/txt1"
android:layout_alignStart="#+id/txt1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView3"
android:id="#+id/txt3"
android:textStyle="bold"
android:layout_below="#+id/txt2"
android:layout_alignStart="#+id/txt2" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ckBox"
android:checked="false"
android:layout_below="#+id/txt3"
android:layout_alignStart="#+id/txt3" />
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:gravity="left"
android:layout_alignBottom="#+id/ckBox"
android:layout_toStartOf="#+id/txt1"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/numberPicker"
android:layout_toEndOf="#+id/txt2"
android:layout_marginStart="23dp"
android:layout_alignParentTop="true"
android:layout_alignBottom="#+id/ckBox" />
customadapter :
public class CustomLVAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<CustomItem> objectList;
private int[] imageId;
private class ViewHolder {
TextView txt1,txt2,txt3;
CheckBox ckBox;
ImageView image;
NumberPicker np;
}
public CustomLVAdapter(Context context, ArrayList<CustomItem> objectList,int[]prgmImages){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.objectList = objectList;
this.imageId = prgmImages;
}
public int getCount(){
return objectList.size();
}
public CustomItem getItem (int position) {
return objectList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_checkbox_textview, null);
holder.txt1 = (TextView) convertView.findViewById(R.id.txt1);
holder.txt2 = (TextView) convertView.findViewById(R.id.txt2);
holder.txt3 = (TextView) convertView.findViewById(R.id.txt3);
holder.image=(ImageView) convertView.findViewById(R.id.image);
holder.ckBox = (CheckBox) convertView.findViewById(R.id.ckBox);
holder.np = (NumberPicker) convertView.findViewById(R.id.numberPicker);
holder.np.setMinValue(0);
holder.np.setMaxValue(10);
convertView.setTag(holder);
holder.ckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomItem object = (CustomItem) cb.getTag();
Toast.makeText(context,
"You have selected: " + object.getItem() +
"Price: " + object.getPrice() +
"Qty: " + object.getQty(),
Toast.LENGTH_LONG).show();
object.setSelected(cb.isChecked());
}
}
);
holder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
NumberPicker p = picker;
CustomItem object = (CustomItem) p.getTag();
object.setQty(String.valueOf(newVal));
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
CustomItem object = objectList.get(position);
holder.txt1.setText(object.getItem());
holder.txt2.setText(object.getDesc());
holder.txt3.setText(object.getPrice());
holder.np.setTag(object);
holder.image.setImageResource(imageId[position]);
holder.ckBox.setChecked(object.isSelected());
holder.ckBox.setTag(object);
return convertView;
} }
menu activity :
public class MenuActivity extends Activity {
private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private TextView txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;
ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
txtOrder=(TextView) findViewById(R.id.txt1);
txtMember=(TextView) findViewById(R.id.txt2);
txtPrice=(TextView) findViewById(R.id.txt3);
list=(ListView) findViewById(R.id.listView);
btnAdd = (Button)findViewById(R.id.button);
rows = new ArrayList<String>();
itemList=new ArrayList<CustomItem>();
itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));
int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};
listView1 = (ListView) findViewById(R.id.listView);
CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
listView1.setAdapter(customLVAdapter);
btnSubmit = (Button) findViewById(R.id.button);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
selectedList = new ArrayList<CustomItem>();
int total = 0;
for (int i = 0; i < itemList.size(); i++) {
CustomItem object = itemList.get(i);
if (object.isSelected()) {
responseText.append(object.getItem() + "," + object.getQty() + ",");//item
selectedList.add(object);
//calculate price
total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());
}
}
Add(responseText.toString(), "5565", String.valueOf(total));
String strOrder = txtOrder.getText().toString();
String strMember = txtMember.getText().toString();
String strPrice = txtPrice.getText().toString();
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
startActivity(i);
i.putExtra("Order", strOrder);
i.putExtra("Member", strMember);
i.putExtra("Price", strPrice);
Toast.makeText(getApplicationContext(), responseText + " $" + total,
Toast.LENGTH_SHORT).show();
SelectAll();
//store in database
//go to ReceiptActivity - membership, item, totalprice
}
});
}
public void Add(final String item, final String membership, final String price)
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/insertorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("item",item );
MyData.put("membership",membership );
MyData.put("price",price );
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
SelectAll();
}
public void SelectAll()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/fetchorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
rows.clear();
for(int i=0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String order = jsonChildNode.optString("item").toString();
String membership = jsonChildNode.optString("membership").toString();
String price = jsonChildNode.optString("price").toString();
rows.add(order + ", " + membership + ", " + price );
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
android.R.layout.simple_list_item_1, rows);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue.add(MyStringRequest);
}
}
reciept activity (the codes of the selected items will be displayed here):
public class ReceiptActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
Bundle extras = getIntent().getExtras();
String strOrder = extras.getString("Order");
String strMember = extras.getString("Member");
String strPrice = extras.getString("Price");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Order:" +strOrder+" ");
}
}
Receipt xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/background2"
tools:context="com.example.android.cardemulation.ReceiptActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt4"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt5"
android:layout_below="#+id/txt4"
android:layout_centerHorizontal="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
CustomItem
public class CustomItem {
private int id;
private String item;
private String price;
private String desc;
private String qty;
private Boolean selected = false;
public CustomItem(){
}
public CustomItem(String item,String desc, String price,String qty){
this.item=item;
this.desc=desc ;
this.price=price;
this.qty=qty;
}
public CustomItem(int id, String item,String desc, String price,String qty){
this.id=id;
this.item=item;
this.desc=desc;
this.price=price;
this.qty=qty;
}
public int getId(){
return id;
}
public void setId (int id) {
this.id=id;
}
public String getItem(){
return item;
}
public void setItem(String item){
this.item=item;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc) {
this.desc=desc;
}
public String getPrice()
{
return price;
}
public void setPrice(String price) {
this.price=price;
}
public String getQty()
{
return qty;
}
public void setQty(String qty) {
this.qty=qty;
}
public boolean isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected=selected;
}
}
I am assuming your CustomItem class has a boolean variable whose value can be retrieved by a getSelected() method.
Create a public static ArrayList like this in your Adapter class
public static ArrayList<CustomItem> arl_food=new ArrayList<>();
Inside your CustomLVAdapter() constructor add this
this.objectList=objectList;
arl_food.clear();
for(int i=0;i<this.objectList.size();i++)
{
arl_food.add(this.objectList.get(i));
}
Instead of creating a new CustomItem object, you should save the data to the particular object inside your ArrayList.
Add this code inside your CheckBox click event :
arl_food.get(position).setSelected(cb.isChecked());
Then inside your NumberPicker valueChanged event :
arl_food.get(position).setQty(String.valueOf(newVal));
In your Next Activity use this list like this :
for(int i=0;i<CustomLVAdapter.arl_food.size();i++)
{
if(CustomLVAdapter.arl_food.get(i).getSelected())
{
//Show the food item from your list and do your stuff here
}
}

customAdapter not working properly with asynchronous image download

Hey guys i am trying to create a custom listview with text and images where images are coming from a url. i am trying to display them asynchronously with my list items. but as i scroll down the list, the image in list items changes and wrong images are displayed in listitems. Below is my code snippet:
CustomList.java,
it is implimenting my base adapter
public class CustomList extends BaseAdapter {
//private ArrayList listData;
private LayoutInflater layoutInflater;
private ArrayList<ListItem> listData;
public CustomList(Context context,ArrayList<ListItem> listData)
{
//Toast.makeText(History.this,"hey",Toast.LENGTH_LONG).show();
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
Log.e("mysize",String.valueOf(listData.size()));
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView,ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = layoutInflater.inflate(R.layout.history_row,null);
holder = new ViewHolder();
holder.so = (TextView)convertView.findViewById(R.id.SO);
holder.name = (TextView)convertView.findViewById(R.id.Name);
holder.process = (ImageView)convertView.findViewById(R.id.Process);
holder.cloth = (ImageView)convertView.findViewById(R.id.Cloth);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ListItem data = (ListItem)listData.get(position);
holder.so.setText(data.getSo());
if(data.getProcess().equals("0"))
{
holder.process.setImageResource(R.drawable.tick);
}
else
holder.process.setImageResource(android.R.drawable.ic_delete);
if(holder.cloth !=null)
{
holder.name.setText(data.getName());
Log.e("urlsss",data.getUrl()+ data.getName());
new ImageDownload(holder.cloth).execute(data.getUrl());
}
return convertView;
}
static class ViewHolder
{
TextView so;
TextView name;
ImageView process;
ImageView cloth;
}
}
ImageDownload.class for downloading images
public class ImageDownload extends AsyncTask<String,Void,Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownload(ImageView imageView)
{
imageViewReference = new WeakReference<ImageView>(imageView);
}
protected Bitmap doInBackground(String... params)
{
RequestHandler rh = new RequestHandler();
return rh.downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(android.R.drawable.star_on);
imageView.setImageDrawable(placeholder);
}
}
}
}
}
ListItem.java that is producing my data for each row in listView
public class ListItem {
private String so,name,process,imgUrl;
public void setSo(String so)
{
this.so = so;
}
public void setName(String name)
{
this.name = name;
}
public void setProcess(String process)
{
this.process = process;
}
public void setUrl(String url)
{
this.imgUrl = url;
}
public String getSo()
{
return so;
}
public String getName()
{
return name;
}
public String getProcess()
{
return process;
}
public String getUrl()
{
return imgUrl; }
}
This is my main activity where custom-adapter is called
public class History extends AppCompatActivity {
//url to fetch data from
public static final String URL_HISTORY = "http://192.168.1.233/vendor/history.php";
//Json tags
public static final String TAG_JSON_ARRAY="result";
public static final String TAG_SO = "SO";
public static final String TAG_NAME = "CustomerName";
public static final String TAG_DESC = "ClothDescription";
public static final String TAG_DATE = "DeliveryDate";
public static final String TAG_PRODUCT_TYPE = "ProductType";
public static final String TAG_PRODUCT_DESC = "ProductDescription";
public static final String TAG_IMAGE_URL = "ImageUrl";
public static final String TAG_PROCESS = "Process";
HashMap<String,String> data = new HashMap<>();
ArrayList<ListItem> detail_list;
ListView listView;
//key to put in hashmap
public static final String VENDOR_NAME = "Username";
//to store fetched data
String[] so;
String[] customerName;
String[] clothesDesc;
String[] delivDate;
String[] prodType;
String[] prodDesc;
String[] imgUrl;
String[] process;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView =(ListView)findViewById(R.id.listView);
detail_list = new ArrayList<ListItem>();
//to get vendorname
SharedPreferences sharedPref = getSharedPreferences("vendorInfo", Context.MODE_PRIVATE);
String vendor_name =sharedPref.getString("username", "");
data.put(VENDOR_NAME, vendor_name);
fetchHistory();
}
public void fetchHistory()
{
class FetchHistory extends AsyncTask<Void,Void,String>
{
ProgressDialog loading;
protected void onPreExecute()
{
super.onPreExecute();
loading = ProgressDialog.show(History.this,"Fetching...","Wait",false,false);
}
protected String doInBackground(Void...params)
{
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(URL_HISTORY, data);
return result;
}
protected void onPostExecute(String s)
{
super.onPostExecute(s);
loading.dismiss();
Log.e("myjson",s);
showHistory(s);
}
}
FetchHistory fh = new FetchHistory();
fh.execute();
}
public void showHistory(String json)
{
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
int length = result.length();
so = new String[length];
customerName = new String[length];
clothesDesc = new String[length];
delivDate = new String[length];
prodType = new String[length];
prodDesc = new String[length];
imgUrl = new String[length];
process = new String[length];
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
so[i] = c.getString(TAG_SO);
customerName[i] = c.getString(TAG_NAME);
clothesDesc[i] = c.getString(TAG_DESC);
delivDate[i] = c.getString(TAG_DATE);
prodType[i] = c.getString(TAG_PRODUCT_TYPE);
prodDesc[i] = c.getString(TAG_PRODUCT_DESC);
imgUrl[i] = c.getString(TAG_IMAGE_URL);
process[i] = c.getString(TAG_PROCESS);
}
}
catch(JSONException e)
{
Log.e("myexception",e.toString());
}
for(int i =0;i<customerName.length;i++)
{
//storing all value in hashmap
ListItem values = new ListItem();
values.setSo(so[i]);
values.setName(customerName[i]);
values.setUrl(imgUrl[i]);
Log.e("myurl", imgUrl[i]);
values.setProcess(process[i]);
detail_list.add(values);
}
Toast.makeText(this,"hey",Toast.LENGTH_LONG).show();
Log.e("hey", "hey00");
CustomList customList = new CustomList(this,detail_list);
listView.setAdapter(customList);
Toast.makeText(this,"you",Toast.LENGTH_LONG).show();
Log.e("you", "you00");
}
}
My layout file for each row is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linear">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/SO"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/Name"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Process"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Cloth"
android:layout_weight="1"
android:scaleType="fitXY" />
</LinearLayout>
</LinearLayout>
This is a common mistake. Your listView recycles views, so instead of creating views for the 100 items in your listView, it just creates enough to fill up the screen.
As you scroll down, that ImageView that was used for position #1, is now the same ImageView being used for position #11, and #21, and so on...
The fix require tracking what positions are currently being displayed to the user, and only setting images for those positions, and clearing the associated imageview (or cancelling the pending download) when it falls off the screen.
You can figure out when your imageView gets reassigned because it will be called in getView again, and from there you can figure out if it has a pending download you need to cancel.
Consider using one of the existing solutions or just checking out how others have done it for a full example. https://github.com/nostra13/Android-Universal-Image-Loader

How to get the check box selected position

How to get the selected position in checkbox itemId.
I have two item Veg and non-veg item. I want the result for veg Items only. I show the screen in veg items .But it is not working for veg list checked items.
Response
|1|Amaretto cookies|True
is itemId
food item
True/False.
Based on True or False I need to check the check boxes and retrieve the checked items
Veg items:
|21|1|Amaretto cookies|True|2|Amish White Bread|True|6|Caesar Salad|True|10|Guacamole|True|13|Macaroni and Cheese|True|16|Pancakes|True|17|Pasta|True|18|Ribollita|True|20|Pizza|True|21|Seven Layer Taco Dip|True|22|Shrimp Bisque|True|23|Spicy Bean Salsa|True|24|Sopapilla Cheesecake|True|25|Sopapilla Cheesecake Pie|True|26|Vegetarian Tortilla Stew|True|561|food|True|563|asdf|True|574|veg|True|579|a|True|593|hjg|True|619|hhy|True|
Non- Veg items:
|12|3|Barbeque|False|4|Buffalo Chicken Wings|False|5|Burgers|False|7|Classic Lasagna|False|8|Chicken Chow Mein|False|9|Fried Chicken|False|11|Japanese sushi|False|12|Mezze|False|14|Mutton Pepper Gravy|False|15|Paella Valenciana|False|19|Phad Thai Recipe|False|578|Pizza|False|
Url:
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;
Code:
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
System.out.println(result);
if (result != null)
{
token = new StringTokenizer2(result, "");
}
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
value.add(Integer.toString(value.size()));
Integer k=null;
table=new Hashtable<Integer,ArrayList<String>>();
itemId = new ArrayList<String>();
stritem = new ArrayList<String>();
vegitems = new ArrayList<String>();
nonvegitems = new ArrayList<String>();
int id=0,c=0,n=value.size();
for(int j=0; j<n; j++)
{
z = value.get(j);
String[] mystring = z.split("<br>");
int arraysize = mystring.length;
for(int a=0; a<arraysize-1;a++)
{
str2.add(mystring[0]);
str3.add(mystring[1]);
}
}
for(int g=0; g<str2.size();g++)
{
String name = str2.get(g);
token2 = new StringTokenizer2(name, "|", false);
while (token2.hasMoreTokens())
{
vegitems.add(token2.nextToken());
}
}
for(int x=1;x<vegitems.size();x++)
{
itemId.add(vegitems.get(x));
x=x+1;
stritem.add(vegitems.get(x));
x=x+1;
status.add(vegitems.get(x));
}
setListAdapter(new IconicAdapter(this));
selection = (TextView) findViewById(R.id.selection);
getListView().setTextFilterEnabled(true);
save.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tru = new StringBuffer();
fals = new StringBuffer();
for (int i = 0; i<status.size();i++)
{
if (status.get(i).equals("True"))
tru.append(itemId.get(i)+",");
else
fals.append(itemId.get(i)+",");
}
boolean netvalue = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname="+username+"&occasion="+occasionval+
"&choice="+tru+fals+"&ownchoice=&category=";
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&")))
{
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter
{
Activity context;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.rsvp_mealsse, stritem);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);
TextView index = (TextView) row.findViewById(R.id.index);
index.setText(String.valueOf(position+1)+".");
TextView label = (TextView) row.findViewById(R.id.title);
label.setText(stritem.get(position));
CheckBox check=(CheckBox)row.findViewById(R.id.check);
check.setId(Integer.parseInt(itemId.get(position)));
if(status.get(position).equals("True"))
check.setChecked(true);
else
check.setChecked(false);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
status.set(ind, String.valueOf(isChecked));
}
});
return (row);
}
}
Snap :
This is what it should look like.False items are checked in the snap
Above shows the full code of my project.
These are my requirements:
It is all about event planner for Food. The invited guests can select and save the interested food items such as pizza, Caesar salad, Ameretocokies etc from the items list and mail to the inviter so that the inviter can view the saved items and arrange for the selected items.
I picked the solution from Romain Guy's solution #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
I have used a ViewHolder pattern for smooth scrolling and performance. I have used a SparseBooleanArray to get checked items.
I assume you want the items whose corresponding check boxes are checked.
Also check this to understand listview re-cycles views
How ListView's recycling mechanism works
public class dsds extends Activity
{
ListView lv;
String result = null;
StringTokenizer2 token = null,token2=null;;
ArrayList<String> value,value2 = null;
ArrayList<String> str = null;
ArrayList<String> str2 = null;
ArrayList<String> newstatus=null;
Hashtable<Integer, String> checkstatus=null;
ArrayList<String>stateId=null;
StringBuffer tru,fals;
private SparseBooleanArray mCheckStates;
String z;
ArrayList<Holder> ha = new ArrayList<Holder>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
str2 = new ArrayList<String>();
stateId = new ArrayList<String>();
newstatus=new ArrayList<String>();
lv = (ListView) findViewById(R.id.listView1);
Button b= (Button) findViewById(R.id.button1);
new TheTask().execute();
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<str2.size();i++)
{
if(mCheckStates.get(i)==true)
{
result.append(str2.get(i));
result.append("\n");
}
}
Toast.makeText(dsds.this, result, 1000).show();
}
});
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname=abcdefg&occasion=Engagement");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
if (_response != null)
{
//alertbox("",result);
String[] mystring = _response.split("<br>"); // splt by break
token = new StringTokenizer2(mystring[0], "|", false);// split by |
token2 = new StringTokenizer2(mystring[1], "|", false);
}
/////// for veg
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
for(int i=1;i<value.size()-1;i=i+3)
{
// Log.i("....Veg ids.......",""+value.get(i));
stateId.add(value.get(i));
}
for(int i=2;i<value.size()-1;i=i+3)
{
str2.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
for(int i=3;i<=value.size()-1;i=i+3)
{
newstatus.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
// add all to list of Holder
for(int h=0;h<str2.size();h++)
{
Holder holder = new Holder();
holder.setTitle(str2.get(h));
holder.setId(stateId.get(h));
if(newstatus.get(h).equals("False"))
{
holder.setCheck(true);
}
else
{
holder.setCheck(false);
}
ha.add(holder);
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
lv.setAdapter(new IconicAdapter(dsds.this));
}
}
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{
Activity context;
LayoutInflater mInflater;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.list_item, str2);
mCheckStates = new SparseBooleanArray(str2.size());
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView==null)
{
convertView=mInflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Holder hol = ha.get(position);
holder.tv1.setText(hol.getId().toString());
holder.tv2.setText(hol.getTitle().toString());
if(hol.isCheck()==true)
{
holder.cb.setChecked(mCheckStates.get(position, true));
holder.cb.setTag(position);
}
else
{
holder.cb.setChecked(mCheckStates.get(position, false));
holder.cb.setTag(position);
}
holder.cb.setOnCheckedChangeListener(this);
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
static class ViewHolder
{
TextView tv1,tv2;
CheckBox cb;
}
}
Holder class
public class Holder {
String title;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
boolean check;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCheck() {
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
}
text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<ListView
android:id="#+id/listView1"
android:layout_above="#id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_tiem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="33dp"
android:layout_marginTop="40dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:text="CheckBox" />
</RelativeLayout>
Snap
Now 1 and 2 are checked and when you click the button at the bottom you see the selected text. I checked 1 and 2 manually. However it depends on the response ie True or False. Right now all veg items are true.
Note: The list displays only veg items
If you are using list-view and you want to check list-view item then you can use below code.
int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)){
..... // Your code whatever you want to do with selected item..
}
else{
....
}

Search ListView with Custom Adapter, shows no results and does not crash program

I am trying to implement a search function on a ListView that is using a custom adapter. I am following this example:http://justcallmebrian.com/?p=149. I was able to edit the code and put it in my adapter. However, it is not bring up any results. Can you look over my code and let me know what I missed or is there something else I can do?
Here is the listView:
public class DataView extends Activity implements OnItemClickListener {
private static final String rssFeed = "http://leobee.com/android/push/login/schedule.php";
private static final String AddEvent = "http://leobee.com/android/push/login/deleteUpdate.php";
private static final String ARRAY_NAME = "events";
private static final String EVENT_NAME = "event_name";
private static final String EVENT_ID = "event_id";
private static final String EVENT_DATE = "event_date";
private static final String EVENT_START = "event_start";
private static final String EVENT_END = "event_end";
private static final String EVENT_LOCATION = "event_location";
private static final String EVENT_DELETE_FLAG = "event_delete_flag";
List<Item> arrayOfList;
List<String> sortOfList;
SimpleAdapter simpleadapter;
ListView listView;
NewsRowAdapter objAdapter;
List<Integer> deleteList;
String undelete;
String eventNameDeleted;
String eventIdDeleted;
String eventDateDeleted;
String eventStartDeleted;
String eventEndDeleted;
String eventLocationDeleted;
JSONObject json;
String addBack = "0";
Button btnMessage;
Button btnLogout;
UserFunctions userFunctions;
EditText searchBox;
int textlength = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.schedulelistview);
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(getApplicationContext())) {
listView = (ListView) findViewById(R.id.listview);
listView.isTextFilterEnabled();
listView.setOnItemClickListener(this);
deleteList = new ArrayList<Integer>();
btnLogout = (Button) findViewById(R.id.btnLogout);
btnMessage = (Button) findViewById(R.id.btnMessage);
searchBox = (EditText) findViewById(R.id.EditText01);
arrayOfList = new ArrayList<Item>();
if (Utils.isNetworkAvailable(DataView.this)) {
new MyTask().execute(rssFeed);
} else {
showToast("No Network Connection. Application is unable to load data.");
}
} else {
}
}
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DataView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(ARRAY_NAME);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
Item objItem = new Item();
// here objItem is reciveing and processing data from
// JSON string text
objItem.setId(objJson.getInt(EVENT_ID));// names from
objItem.setName(objJson.getString(EVENT_NAME));
objItem.setDate(objJson.getString(EVENT_DATE));
objItem.setDeleteFlag(objJson.getInt(EVENT_DELETE_FLAG));
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < arrayOfList.size(); i++) {
Item deletflagCheck = arrayOfList.get(i);
if (deletflagCheck.getDeleteFlag() == 1) {
deleteList.add(deletflagCheck.getId());
} else {
}
}
}
setAdapterToListview();
}
}
#Override
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
Item deletflagCheck = arrayOfList.get(position);
if (deletflagCheck.getDeleteFlag() == 1) {
showDeleteDialog(position);
} else {
Intent intent = new Intent(DataView.this.getApplicationContext(),
UpdateServer.class);
for (int i = 0; i < 1; i++) {
Item item = arrayOfList.get(position);
intent.putExtra("id", item.getId());
intent.putExtra("name", item.getName());
intent.putExtra("date", item.getDate());
intent.putExtra("startTime", item.getStartTime());
intent.putExtra("endTime", item.getEndTime());
intent.putExtra("location", item.getLocation());
intent.putExtra("deleteFlag", item.getDeleteFlag());
}
startActivity(intent);
}
}
public void setAdapterToListview() {
objAdapter = new NewsRowAdapter(DataView.this,
R.layout.schedulelistrow, arrayOfList, deleteList);
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
searchBox.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// Do nothing
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
objAdapter.getFilter().filter(s);
}
});
}
public void showToast(String msg) {
Toast.makeText(DataView.this, msg, Toast.LENGTH_LONG).show();
}
}
Item class:
public class Item {
private int id;
private String name;
private String date;
private String startTime;
private String endTime;
private String location;
private int deleteFlag;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(int deleteFlag) {
this.deleteFlag = deleteFlag;
}
}
The adapter:
public class NewsRowAdapter extends ArrayAdapter<Item> {
private Activity activity;
private List<Item> items;
private Item objBean;
private int row;
private List<Integer> disable;
View view ;
int disableView;
ListFilter filter ;
List<Item> filteredItems;
public NewsRowAdapter(Activity act, int resource, List<Item> arrayList, List<Integer> disableList) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.items = arrayList;
filteredItems = items;
this.disable=disableList;
}
public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
for(int k =0;k < disable.size();k++){
if(position==disable.get(k)){
disableView=disable.get(k);
System.out.println("disagle view at" +disableView);
}
}
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
getItemViewType(position);
if(position==disableView){
view.setBackgroundColor(Color.YELLOW);
}else{
view.setBackgroundColor(Color.WHITE);
}
//ViewHolder is a custom class that gets TextViews by name: tvName, tvCity, tvBDate, tvGender, tvAge;
holder = new ViewHolder();
/* setTag Sets the tag associated with this view. A tag can be used to
* mark a view in its hierarchy and does not have to be unique
* within the hierarchy. Tags can also be used to store data within
* a view without resorting to another data structure.
*/
view.setTag(holder);
} else {
getItemViewType(position);
if(position==disableView){
view.setBackgroundColor(Color.YELLOW);
}else{
view.setBackgroundColor(Color.WHITE);
}
//the Object stored in this view as a tag
holder = (ViewHolder) view.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return view;
objBean = items.get(position);
holder.tv_event_name = (TextView) view.findViewById(R.id.tv_event_name);
holder.tv_event_date = (TextView) view.findViewById(R.id.tv_event_date);
holder.tv_event_start = (TextView) view.findViewById(R.id.tv_event_start);
holder.tv_event_end = (TextView) view.findViewById(R.id.tv_event_end);
holder.tv_event_location = (TextView) view.findViewById(R.id.tv_event_location);
if (holder.tv_event_name != null && null != objBean.getName()
&& objBean.getName().trim().length() > 0) {
holder.tv_event_name.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tv_event_date != null && null != objBean.getDate()
&& objBean.getDate().trim().length() > 0) {
holder.tv_event_date.setText(Html.fromHtml(objBean.getDate()));
}
if (holder.tv_event_start != null && null != objBean.getStartTime()
&& objBean.getStartTime().trim().length() > 0) {
holder.tv_event_start.setText(Html.fromHtml(objBean.getStartTime()));
}
if (holder.tv_event_end != null && null != objBean.getEndTime()
&& objBean.getEndTime().trim().length() > 0) {
holder.tv_event_end.setText(Html.fromHtml(objBean.getEndTime()));
}
if (holder.tv_event_location != null && null != objBean.getLocation ()
&& objBean.getLocation ().trim().length() > 0) {
holder.tv_event_location.setText(Html.fromHtml(objBean.getLocation ()));
}
return view;
}
public class ViewHolder {
public TextView
tv_event_name,
tv_event_date,
tv_event_start,
tv_event_end,
tv_event_location
/*tv_event_delete_flag*/;
}
private class ListFilter extends Filter{
List<Item> filt;
List<Item> tmpItems;
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults retval = new FilterResults();
List<Item> filt;
List<Item> tmpItems;
retval.values = items;
retval.count = items.size();
if(constraint != null && constraint.toString().length() > 0) {
constraint = constraint.toString().toUpperCase();
filt = new ArrayList<Item>();
tmpItems = new ArrayList<Item>();
tmpItems.addAll(items);
for(int i = 0; i > tmpItems.size(); i++) {
Item sf = tmpItems.get(i);
if(sf.getName().toUpperCase().contains(constraint)) {
filt.add(sf);
}
}
retval.count = filt.size();
retval.values = filt;
}
return retval;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems = (ArrayList)results.values;
notifyDataSetChanged();
clear();
for (int i = 0; i> filteredItems.size(); i++){
add(filteredItems.get(i));
}
notifyDataSetInvalidated();
}
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new ListFilter();
}
return filter;
}
}
The xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/layoutButtons"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp" >
<Button
android:id="#+id/btnLogout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:text="Logout" />
<Button
android:id="#+id/btnMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".70"
android:text="Send Message To All" />
</LinearLayout>
<EditText
android:id="#+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search" >
</EditText>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

Categories

Resources