Android Listview duplicates on15th row onwards - android

iam currently doing a project in which i populate a Listview from JSON.
The JSON iam passing works perfectly and my listview shows all list values properly But problem occurs when i click on any list after 10/12th list the values which i get is repeated from the first.
The respective values are not retrieved.
I also refereed other post regarding this issue but now solved my problem.
Below is my code. I hope someone will find the solution for it.
package com.desitv.geojoy;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.desitv.geojoy.R;
import com.desitv.geojoy.adapter.LatestGridAdapter;
import com.desitv.geojoy.item.ItemLatest;
import com.desitv.geojoy.util.AlertDialogManager;
import com.desitv.geojoy.util.Constant;
import com.desitv.geojoy.util.JsonUtils;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class LatestFragment extends SherlockFragment {
ListView lsv_latest;
List<ItemLatest> arrayOfLatestMusic;
LatestGridAdapter objAdapter;
AlertDialogManager alert = new AlertDialogManager();
ArrayList<String> allListImageUrl,allListChannelCatName;
ArrayList<String> allListChannelId,allListChannelCatId,allListChannelUrl,allListChannelName,allListChannelDesc;
String[] allArrayImage,allArrayChannelCatName;
String[] allArrayChannelId,allArrayChannelCatId,allArrayChannelurl,allArrayChannelName,allArrayChannelDesc;
private ItemLatest objAllBean;
private int columnWidth;
JsonUtils util;
int textlength = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
setHasOptionsMenu(true);
lsv_latest=(ListView)rootView.findViewById(R.id.lsv_latest);
arrayOfLatestMusic=new ArrayList<ItemLatest>();
allListImageUrl=new ArrayList<String>();
allListChannelCatName=new ArrayList<String>();
allListChannelCatId=new ArrayList<String>();
allListChannelId=new ArrayList<String>();
allListChannelName=new ArrayList<String>();
allListChannelUrl=new ArrayList<String>();
allListChannelDesc=new ArrayList<String>();
allArrayImage=new String[allListImageUrl.size()];
allArrayChannelCatName=new String[allListChannelCatName.size()];
allArrayChannelId=new String[allListChannelId.size()];
allArrayChannelCatId=new String[allListChannelCatId.size()];
allArrayChannelurl=new String[allListChannelUrl.size()];
allArrayChannelName=new String[allListChannelName.size()];
allArrayChannelDesc=new String[allListChannelDesc.size()];
util=new JsonUtils(getActivity());
if (JsonUtils.isNetworkAvailable(getActivity())) {
new MyTask().execute(Constant.LATEST_URL);
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(getActivity(), "Internet Connection Error",
"Please connect to working Internet connection", false);
}
lsv_latest.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
objAllBean=arrayOfLatestMusic.get(position);
int pos=objAllBean.getId();
Intent intplay=new Intent(getActivity(),TvDetails.class);
intplay.putExtra("POSITION", pos);
intplay.putExtra("CHANNEL_IMAGE", allArrayImage);
intplay.putExtra("CHANNEL_CATNAME", allArrayChannelCatName);
intplay.putExtra("CHANNEL_CATID", allArrayChannelCatId);
intplay.putExtra("CHANNEL_URL", allArrayChannelurl);
intplay.putExtra("CHANNEL_NAME", allArrayChannelName);
intplay.putExtra("CHANNEL_CID", allArrayChannelId);
intplay.putExtra("CHANNEL_DISCRIPTION", allArrayChannelDesc);
startActivity(intplay);
}
});
return rootView;
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(getActivity(), "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.LATEST_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemLatest objItem = new ItemLatest();
objItem.setId(objJson.getInt(Constant.CHANNEL_ID));
objItem.setCategoryId(objJson.getInt(Constant.CHANNEL_CATID));
objItem.setCategoryName(objJson.getString(Constant.CHANNEL_CAT_NAME));
objItem.setChannelName(objJson.getString(Constant.LATEST_CHANNEL_NAME));
objItem.setChannelUrl(objJson.getString(Constant.lATETST_CHANNEL_URL));
objItem.setDescription(objJson.getString(Constant.LATEST_CHANNEL_DESCRIPTION));
objItem.setImage(objJson.getString(Constant.LATEST_CHANNEL_IMAGE));
arrayOfLatestMusic.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
for(int j=0;j<arrayOfLatestMusic.size();j++)
{
objAllBean=arrayOfLatestMusic.get(j);
allListImageUrl.add(objAllBean.getImage());
allArrayImage=allListImageUrl.toArray(allArrayImage);
allListChannelCatName.add(objAllBean.getCategoryName());
allArrayChannelCatName=allListChannelCatName.toArray(allArrayChannelCatName);
allListChannelId.add(String.valueOf(objAllBean.getId()));
allArrayChannelId=allListChannelId.toArray(allArrayChannelId);
allListChannelCatId.add(String.valueOf(objAllBean.getCategoryId()));
allArrayChannelCatId=allListChannelCatId.toArray(allArrayChannelCatId);
allListChannelUrl.add(String.valueOf(objAllBean.getChannelUrl()));
allArrayChannelurl=allListChannelUrl.toArray(allArrayChannelurl);
allListChannelName.add(String.valueOf(objAllBean.getChannelName()));
allArrayChannelName=allListChannelName.toArray(allArrayChannelName);
allListChannelDesc.add(objAllBean.getDescription());
allArrayChannelDesc=allListChannelDesc.toArray(allArrayChannelDesc);
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
objAdapter = new LatestGridAdapter(getActivity(), R.layout.latest_lsv_item,
arrayOfLatestMusic,columnWidth);
lsv_latest.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
textlength=newText.length();
arrayOfLatestMusic.clear();
for(int i=0;i< allArrayChannelName.length;i++)
{
if(textlength <= allArrayChannelName[i].length())
{
if(newText.toString().equalsIgnoreCase((String) allArrayChannelName[i].subSequence(0, textlength)))
{
ItemLatest objItem = new ItemLatest();
objItem.setId(Integer.parseInt(allArrayChannelId[i]));
objItem.setCategoryId(Integer.parseInt(allArrayChannelCatId[i]));
objItem.setCategoryName(allArrayChannelCatName[i]);
objItem.setDescription(allArrayChannelDesc[i]);
objItem.setImage(allArrayImage[i]);
objItem.setChannelName(allArrayChannelName[i]);
objItem.setChannelUrl(allArrayChannelurl[i]);
arrayOfLatestMusic.add(objItem);
}
}
}
setAdapterToListview();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// Do something
return true;
}
});
}
}
LatestGridAdapter code
package com.desitv.geojoy.adapter;
import java.util.List;
import com.desitv.geojoy.R;
import com.desitv.geojoy.imageloader.ImageLoader;
import com.desitv.geojoy.item.ItemLatest;
import com.desitv.geojoy.util.Constant;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LatestGridAdapter extends ArrayAdapter<ItemLatest>{
private Activity activity;
private List<ItemLatest> itemsLatest;
private ItemLatest objLatestBean;
private int row;
public ImageLoader imageLoader;
public LatestGridAdapter(Activity act, int resource, List<ItemLatest> arrayList, int columnWidth) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.itemsLatest = arrayList;
imageLoader=new ImageLoader(activity);
}
#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);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if ((itemsLatest == null) || ((position + 1) > itemsLatest.size()))
return view;
objLatestBean = itemsLatest.get(position);
holder.imgv_latetst=(ImageView)view.findViewById(R.id.picture);
holder.name=(TextView)view.findViewById(R.id.text);
holder.txt_category=(TextView)view.findViewById(R.id.text_category);
imageLoader.DisplayImage(Constant.SERVER_IMAGE_UPFOLDER_THUMB+objLatestBean.getImage().toString(), holder.imgv_latetst);
holder.name.setText(objLatestBean.getChannelName().toString());
holder.txt_category.setText(objLatestBean.getCategoryName().toString());
return view;
}
public class ViewHolder {
public ImageView imgv_latetst;
public TextView name,txt_category;
}
}

Related

GridView doesn't show anything after JSON parsing the values into its items

I have gridview for a tab in tabLayout. I load the values from mysql database to fill the textviews of gridview. I see that the JSON parsing runs correctly and returns correct JSON result. But nothing shows up in grid view.
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.mysampleapp.R;
import java.util.ArrayList;
public class GridAdapterStores extends BaseAdapter {
private Context context;
private ArrayList<String> storename=new ArrayList<String>();
private ArrayList<Integer> imagelinks=new ArrayList<Integer>();
public GridAdapterStores(Context c,ArrayList<String> storename, ArrayList<Integer> imagelinks) {
context = c;
this.imagelinks = imagelinks;
this.storename = storename;
}
#Override
public int getCount() {
return storename.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
View grid;
if (convertView == null) {
grid = new View(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.grid_stores,parent,false);
}
else {
grid = (View) convertView;
}
TextView textViewStoreName = (TextView) grid.findViewById(R.id.store_name);
ImageView imageViewStoreImage = (ImageView) grid.findViewById(R.id.store_image);
textViewStoreName.setText(storename.get(position));
Integer x=imagelinks.get(position);
imageViewStoreImage.setImageResource(x);
return grid;
}
}
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;
import com.mysampleapp.R;
import java.util.ArrayList;
public class StoresFragment extends Fragment {
private ProgressDialog loading;
private ArrayList<String> storenamefinal=new ArrayList<String>();
private ArrayList<Integer> imagelinksfinal=new ArrayList<Integer>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater , ViewGroup container,Bundle savedInstanceState){
return inflater.inflate(R.layout.stores_layout,null);
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
GridView gridview=(GridView) getActivity().findViewById(R.id.grid_stores);
getData();
final GridAdapterStores gridadapter= new GridAdapterStores(getActivity(),storenamefinal,imagelinksfinal);
gridview.setAdapter(gridadapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
/* Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(gridadapter.getItem(position).getImageUrlString()));
startActivity(i);}});*/
// Toast.makeText(getActivity(), "You Clicked at " + cat[+position], Toast.LENGTH_SHORT).show();
Intent i = new Intent(getActivity(), stores_show.class);
i.putExtra("storename", storenamefinal.get(position));
getActivity().startActivity(i);
}
});
}
//public class getData extends AsyncTask<String,>>{
//}
private void getData() {
loading = ProgressDialog.show(getActivity(), "Please wait...", "Fetching...", false, false);
String url = Config1.DATA_URL;
Toast.makeText(getActivity(), url, Toast.LENGTH_LONG).show();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config1.JSON_ARRAY);
Toast.makeText(getActivity(),result.toString(),Toast.LENGTH_LONG).show();
int i=result.length();
Log.i("Result Length",result.toString());
for(int j=0;j<i;j++){
storenamefinal.add(null);
imagelinksfinal.add(null);
}
String temp;
for(int j=0;j<i;j++)
{
JSONObject Data = result.getJSONObject(j);
Log.i("Data",Data.toString());
temp= (Data.getString(Config1.KEY_PRIO));
Log.i("temp", temp.toString());
storenamefinal.set(Integer.parseInt(temp) - 1, Data.getString(Config1.KEY_NAME));
Log.i("Result Length", storenamefinal.toString());
imagelinksfinal.add(R.drawable.sg1);
}
Log.i("Result Length", storenamefinal.toString());
Toast.makeText(getActivity(),storenamefinal.get(0),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I have tried searching on Google and stackoverflow , found nothing successful,
{"result":[{"storename":"Flipkart.com","imagelinks":"","mainpriority":"2"},{"storename":"Jabong.com","imagelinks":"","mainpriority":"4"},{"storename":"Myntra.com","imagelinks":"","mainpriority":"5"},{"storename":"Amazon.in","imagelinks":"","mainpriority":"1"},{"storename":"Snapdeal.com","imagelinks":"","mainpriority":"3"},{"storename":"Koovs.in","imagelinks":"","mainpriority":"6"},{"storename":"Limeroad.com","imagelinks":"","mainpriority":"7"},{"storename":"Shopperstop.com","imagelinks":"","mainpriority":"8"},{"storename":"Stalkbuylove.com","imagelinks":"","mainpriority":"9"},{"storename":"Yepme.com","imagelinks":"","mainpriority":"10"},{"storename":"Faballey.com","imagelinks":"","mainpriority":"11"},{"storename":"Fabindia.com ","imagelinks":"","mainpriority":"12"},{"storename":"PrettySecrets.com","imagelinks":"","mainpriority":"13"},{"storename":"AmericanSwan.com","imagelinks":"","mainpriority":"14"},{"storename":"Clovia.com","imagelinks":"","mainpriority":"15"},{"storename":"Bata.in","imagelinks":"","mainpriority":"16"},{"storename":"TrendyBharat.com","imagelinks":"","mainpriority":"17"},{"storename":"Royzez.com","imagelinks":"","mainpriority":"18"}]}
`
Storenamefinal will have entries of storenames from resulting JSON(above)
I tried your code and it crashes the application
after debugging i got that the problem is with the image resources
when i commented below two lines the app works fine.
//check these resources
Integer x=imagelinks.get(position);
imageViewStoreImage.setImageResource(x);
your showJSON() function that i tried
private void showJSON() {
try {
String response ="{\"result\":[{\"storename\":\"Flipkart.com\",\"imagelinks\":\"\",\"mainpriority\":\"2\"},{\"storename\":\"Jabong.com\",\"imagelinks\":\"\",\"mainpriority\":\"4\"},{\"storename\":\"Myntra.com\",\"imagelinks\":\"\",\"mainpriority\":\"5\"},{\"storename\":\"Amazon.in\",\"imagelinks\":\"\",\"mainpriority\":\"1\"},{\"storename\":\"Snapdeal.com\",\"imagelinks\":\"\",\"mainpriority\":\"3\"},{\"storename\":\"Koovs.in\",\"imagelinks\":\"\",\"mainpriority\":\"6\"},{\"storename\":\"Limeroad.com\",\"imagelinks\":\"\",\"mainpriority\":\"7\"},{\"storename\":\"Shopperstop.com\",\"imagelinks\":\"\",\"mainpriority\":\"8\"},{\"storename\":\"Stalkbuylove.com\",\"imagelinks\":\"\",\"mainpriority\":\"9\"},{\"storename\":\"Yepme.com\",\"imagelinks\":\"\",\"mainpriority\":\"10\"},{\"storename\":\"Faballey.com\",\"imagelinks\":\"\",\"mainpriority\":\"11\"},{\"storename\":\"Fabindia.com \",\"imagelinks\":\"\",\"mainpriority\":\"12\"},{\"storename\":\"PrettySecrets.com\",\"imagelinks\":\"\",\"mainpriority\":\"13\"},{\"storename\":\"AmericanSwan.com\",\"imagelinks\":\"\",\"mainpriority\":\"14\"},{\"storename\":\"Clovia.com\",\"imagelinks\":\"\",\"mainpriority\":\"15\"},{\"storename\":\"Bata.in\",\"imagelinks\":\"\",\"mainpriority\":\"16\"},{\"storename\":\"TrendyBharat.com\",\"imagelinks\":\"\",\"mainpriority\":\"17\"},{\"storename\":\"Royzez.com\",\"imagelinks\":\"\",\"mainpriority\":\"18\"}]} ";
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
int i=result.length();
Log.i("Result Length", result.toString());
for(int j=0;j<i;j++){
storenamefinal.add(null);
imagelinksfinal.add(null);
}
String temp;
for(int j=0;j<i;j++)
{
JSONObject Data = result.getJSONObject(j);
Log.i("Data",Data.toString());
temp= (Data.getString("mainpriority"));
Log.i("temp", temp.toString());
storenamefinal.set(Integer.parseInt(temp) - 1, Data.getString("storename"));
Log.i("Result Length", storenamefinal.toString());
imagelinksfinal.add(R.drawable.ic_launcher);
}
Log.i("Result Length", storenamefinal.toString());
Toast.makeText(MainActivity.this,storenamefinal.get(0),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
GridAdapterStores.java file
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by mithilesh.izardar on 6/17/2016.
*/
public class GridAdapterStores extends BaseAdapter {
private Context context;
private ArrayList<String> storename=new ArrayList<String>();
private ArrayList<Integer> imagelinks=new ArrayList<Integer>();
public GridAdapterStores(Context c,ArrayList<String> storename, ArrayList<Integer> imagelinks) {
context = c;
this.imagelinks = imagelinks;
this.storename = storename;
}
#Override
public int getCount() {
return storename.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
View grid;
if (convertView == null) {
grid = new View(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.grid_stores,parent,false);
}
else {
grid = (View) convertView;
}
TextView textViewStoreName = (TextView) grid.findViewById(R.id.store_name);
ImageView imageViewStoreImage = (ImageView) grid.findViewById(R.id.store_image);
textViewStoreName.setText(storename.get(position));
// Integer x=imagelinks.get(position);
// imageViewStoreImage.setImageResource(x);
return grid;
}
Happy Coding :)

issue in pass arraylist to autocompletetextview

I want to display 3 textviews in autocomplete textview drop down so I'm using arryalist but when I pass arraylist to AutoCompleteTextview,nothing display in dropdown.
I print the arryalist.tostring() in logcat.and the output is
[com.novityrecharge.Beans.AutocompletetextviewGeSe#41097f28]
How to solve this
Autcocompleteadapter2.java
package com.novityrecharge.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import com.novityrecharge.Beans.AutocompletetextviewGeSe;
import com.novityrecharge.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by varshils on 3/26/2016.
*/
public class AutoCompleteAdapter2 extends ArrayAdapter<AutocompletetextviewGeSe> {
private Activity context;
ArrayList<AutocompletetextviewGeSe> data;
int layoutResourceId;
public AutoCompleteAdapter2(Activity context, int resource,ArrayList<AutocompletetextviewGeSe> data)
{
super(context, resource, data);
this.context = context;
this.data = data;
this.layoutResourceId = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getDropDownView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{ // This view starts when we click the spinner.
View row = convertView;
listHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new listHolder();
holder.firm = (TextView)row.findViewById(R.id.a_firm);
holder.mob = (TextView)row.findViewById(R.id.a_mobno);
holder.mcode = (TextView)row.findViewById(R.id.a_mcode);
row.setTag(holder);
}
else
{
holder = (listHolder)row.getTag();
}
AutocompletetextviewGeSe item = data.get(position);
holder.firm.setText(item.getAfirm());
holder.mob.setText(item.getAmob());
holder.mcode.setText(item.getAmcode());
return row;
}
static class listHolder
{
TextView firm,mob,mcode;
}
}
Topuptransfer.java
package com.novityrecharge;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import com.novityrecharge.Beans.AutocompletetextviewGeSe;
import com.novityrecharge.Beans.ResponseString;
import com.novityrecharge.CrashingReport.ExceptionHandler;
import com.novityrecharge.Interfaces.callback;
import com.novityrecharge.adapter.AutoCompleteAdapter;
import com.novityrecharge.adapter.AutoCompleteAdapter2;
import com.novityrecharge.async.AsyncTaskCommon;
import com.novityrecharge.async.AsynctaskgetBalance;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by varshils on 1/13/2016.
*/
public class TopupTransfer extends BaseActivity{
AutoCompleteTextView memberView;
ArrayList <AutocompletetextviewGeSe> name1= null;
Button btnSubmit;
String membercode2,amount;
TextInputLayout smspin_textInputLayout;
EditText amnt,smspin;;
HashMap<String,String> memberDetail;
AutoCompleteAdapter2 adapter;
DatabaseHelper db;
int amont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.topuptransfer);
if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof ExceptionHandler))
{
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
}
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CB5F5")));
db = new DatabaseHelper(TopupTransfer.this);
memberView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
name1 = new ArrayList<AutocompletetextviewGeSe>();
memberDetail = new HashMap<String,String>();
amnt = (EditText) findViewById(R.id.topup_amnt);
btnSubmit = (Button) findViewById(R.id.button);
smspin = (EditText) findViewById(R.id.smspin);
smspin_textInputLayout = (TextInputLayout) findViewById(R.id.topuptransfer_smspin);
if(ResponseString.getRequiredSmsPin().equals("TRUE"))
{
smspin_textInputLayout.setVisibility(View.VISIBLE);
smspin.setVisibility(View.VISIBLE);
}
else
{
smspin_textInputLayout.setVisibility(View.GONE);
smspin.setVisibility(View.GONE);
}
memberView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = s.toString();
Log.d("text", "" + text);
int len = text.length();
if (memberView != null)
{
if( len >= 3) {
Log.d("text", "" + text);
try {
name1 = GetList2(text);
Log.d("ADPTER LIST", name1.toString());
adapter = new AutoCompleteAdapter2(TopupTransfer.this,R.layout.autocompletetextview_layout,name1);
memberView.setAdapter(adapter);
}catch(Exception e){
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(TopupTransfer.this));
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(amnt.getText().toString().length() != 0)
{
amont = Integer.parseInt(amnt.getText().toString());
}
if(ResponseString.getRequiredSmsPin().equals("TRUE"))
{
String sms = smspin.getText().toString();
String rs = ResponseString.getSmspwd();
if (sms.length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsentersmspin));
return;
}
else if (!sms.equals(rs)) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.pinentercorrect));
return;
}
}else if (memberView.getText().toString().length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsenterfirm));
memberView.requestFocus();
return;
}else if (amnt.getText().toString().length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsenteramnt));
amnt.requestFocus();
return;
}else if(amont <= 0)
{
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsentercrectamnt));
return;
}
String Dpattern = memberView.getText().toString();
membercode2 = BaseActivity.detailMember.get(Dpattern);
amount = amnt.getText().toString();
Log.d("topup membercode",membercode2);
try {
if (membercode2 == null) {
//Toast.makeText(TopupTransfer.this, "Firm name is not Valid", Toast.LENGTH_SHORT).show();
toastValidationMessage(TopupTransfer.this, "Firm name is not Valid");
memberView.requestFocus();
} else {
boolean con = isInternetConnected();
if (con) {
AsynctaskgetBalance asy = new AsynctaskgetBalance(TopupTransfer.this,new callback(){
public void run(String result){
if (ResponseString.getStcode().equals("0")) {
AlertDialog.Builder builder = new AlertDialog.Builder(TopupTransfer.this);
builder.setTitle(R.string.app_name);
builder.setMessage(BaseActivity.sMsg);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BaseActivity.sMsg = "";
finish();
Intent m = new Intent(TopupTransfer.this,TopupTransfer.class);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
startActivity(m);
}
});
setOnlyBalance();
builder.show();
} else {
toastValidationMessage(TopupTransfer.this,sMsg);
}
}
} , membercode2,amount,"","BALANCE","DISCOUNT");
asy.execute("TopupTransfer");
} else {
toastValidationMessage(TopupTransfer.this,getResources().getString(R.string.checkinternet));
}
}
}catch (Exception e)
{
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(TopupTransfer.this));
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.action_signout:
logout(TopupTransfer.this);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (fullLayout != null && fullLayout.isDrawerOpen(GravityCompat.START)) {
fullLayout.closeDrawer(GravityCompat.START);
} else {
Intent intent = new Intent(TopupTransfer.this, HomePage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
#Override
protected void onPause() {
super.onPause();
if ((BaseActivity.pleaseWaitDialog != null) && BaseActivity.pleaseWaitDialog.isShowing()) {
BaseActivity.pleaseWaitDialog.dismiss();
BaseActivity.pleaseWaitDialog = null;
}
}
}
GetList2()
ArrayList<AutocompletetextviewGeSe> GetList2(String text) {
AutocompletetextviewGeSe autogese;
ArrayList<AutocompletetextviewGeSe> arrayListtemp = new ArrayList<AutocompletetextviewGeSe>();;
Cursor cursor = db.getTimeRecordList(text, "ChildUserInfo");
if (cursor != null){
if (cursor.moveToFirst()) {
do {
autogese = new AutocompletetextviewGeSe();
autogese.setAfirm(cursor.getString(cursor.getColumnIndex("FirmName")));
autogese.setAmob(cursor.getString(cursor.getColumnIndex("MobileNumber")));
autogese.setAmcode(cursor.getString(cursor.getColumnIndex("MemberCode")));
arrayListtemp = new ArrayList<AutocompletetextviewGeSe>();
arrayListtemp.add(autogese);
} while (cursor.moveToNext());
}
}
Log.d("arraylist",arrayListtemp.toString());
return arrayListtemp;
}

ListView goes upside when slide it to bottom in android

Hello I am newbie to android and working on a list-view demo,I recently found a weird behavior of list-view when i scroll it down it forcefully comes upside,Can anybody tell me what should be the reason behind this behavior.I am posting my code here.
activity
package one.tusk.stush.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.SearchPostActivity;
import one.tusk.stush.adapters.TimelineAdapter;
import one.tusk.stush.connect.Post;
import one.tusk.stush.loaders.SearchPostsLoader;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
public class SearchPostsFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<List<Post>>, OnRefreshListener, OnScrollListener {
public static android.widget.PopupMenu popupMenu;
private int index = -1;
private int top = 0;
TimelineAdapter mTimelineAdapter;
SearchPostsLoader mTimelineLoader;
PullToRefreshLayout mPullToRefreshLayout;
ListView mListViewTimeline;
ProgressBar mProgressBarLoading;
TextView mTextViewNoItems;
ImageView im;
Menu mm;
int total;
int lastPosition;
int lastTop;
String search;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
search = getArguments().getString("search");
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_timeline_other, container, false);
setHasOptionsMenu(false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
public void onResume () {
super.onResume();
getActivity().invalidateOptionsMenu();
mListViewTimeline.setSelectionFromTop(
lastPosition,
lastTop
);
// if(index!=-1){
// mListViewTimeline.setSelectionFromTop(index, top);
// }
setHasOptionsMenu(false);
}
#Override
public void onStop() {
super.onStop();
lastPosition = mListViewTimeline.getFirstVisiblePosition();
View v = mListViewTimeline.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
// lastPosition = mListViewTimeline.getSelectedItemPosition();
// int lastPositionInGroup = lastPosition - mListViewTimeline.getFirstVisiblePosition();
// lastTop = mListViewTimeline.getChildAt( lastPositionInGroup ).getTop();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.search_post, menu);
//MenuItem refreshItem = menu.findItem(R.id.action_edit);
//refreshItem.setVisible(true);
//inflater.inflate(R.menu.fragment_profile_menu, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.search22) {
// Log.d("MyApp", "action bar clicked");
Intent intent = new Intent(getActivity(), SearchPostActivity.class);
intent.putExtra("View_mode", true);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
total = 0;
mPullToRefreshLayout = (PullToRefreshLayout) getActivity().findViewById(R.id.ptr_layout);
ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().listener(this).setup(mPullToRefreshLayout);
mProgressBarLoading = (ProgressBar) getActivity().findViewById(R.id.progressBarLoading);
mTextViewNoItems = (TextView) getActivity().findViewById(R.id.textViewNoItems);
mTimelineAdapter = new TimelineAdapter(getActivity());
mListViewTimeline = (ListView) getActivity().findViewById(R.id.listViewTimeline);
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setEmptyView(mProgressBarLoading);
mListViewTimeline.setAdapter(mTimelineAdapter);
mListViewTimeline.setOnScrollListener(this);
// mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setVerticalScrollBarEnabled(false);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<List<Post>> onCreateLoader(int id, Bundle args) {
mTimelineLoader = new SearchPostsLoader(getActivity(), mListViewTimeline, search);
setHasOptionsMenu(false);
return mTimelineLoader;
}
#Override
public void onLoadFinished(Loader<List<Post>> arg0, List<Post> data) {
mTimelineAdapter.setData(data);
mTimelineAdapter.notifyDataSetChanged();
mPullToRefreshLayout.setRefreshComplete();
mTextViewNoItems.setVisibility(View.VISIBLE);
mProgressBarLoading.setVisibility(View.INVISIBLE);
mListViewTimeline.setEmptyView(mTextViewNoItems);
}
#Override
public void onLoaderReset(Loader<List<Post>> arg0) {
mTimelineAdapter.setData(null);
setHasOptionsMenu(false);
}
#Override
public void onRefreshStarted(View view) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, this);
mTextViewNoItems.setVisibility(View.INVISIBLE);
mProgressBarLoading.setVisibility(View.VISIBLE);
mListViewTimeline.setEmptyView(mProgressBarLoading);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount && visibleItemCount != 0) {
if (mTimelineLoader.loadMore() && !mTimelineLoader.loading()) {
total = totalItemCount - 1;
lastPosition = view.getFirstVisiblePosition();
View v = view.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
mTimelineLoader.onContentChanged();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void searchPost(String query)
{
search = query;
lastPosition = 0;
lastTop = 0;
mTimelineAdapter.clear();
// mTimelineLoader.loadInBackground();
Log.d("12","UPDATE");
getLoaderManager().restartLoader(0, null, this);
}
}
Adapter
package one.tusk.stush.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.connect.Post;
import one.tusk.stush.views.PostListItem;
public class TimelineAdapter extends ArrayAdapter<Post> {
private final LayoutInflater mInflater;
public TimelineAdapter(Context context) {
super(context, R.layout.list_item_post);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Post> data) {
setNotifyOnChange(true);
clear();
if (data != null) {
addAll(data);
notifyDataSetChanged();
}
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
PostListItem view;
if (convertView == null) {
view = (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
} else {
view = (PostListItem) convertView;
}
view.setPost(post);
notifyDataSetChanged();
return view;
}
}
You can try this,
Change your code
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
to
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
if (searchAdapter== null) {
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
} else {
searchAdapter.setData(results);
mListViewSearchUsers.notifyDatasetChange();
}
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
Change some code in adapter (comment some code)
public void setData(List<User> data) {
// clear();
if (data != null) {
addAll(data);
// notifyDataSetChanged();
}
}
Update:(problem resolved by comm‌​ents this line)
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
I hope this will help you.

Search Function didn't work

appreciate your help here. I don't why it didn't work. I have added the following function to search for user. I debug it and it appears it stucked at the filter (argo) function. My code as follows. There is nothing in the logcat error. Appreciate your help.
My code (updated code)
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class EditFriendsActivity extends ListActivity {
public static final String TAG = EditFriendsActivity.class.getSimpleName();
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected List<ParseUser> mUsers;
CustomAdaptor adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_edit_friends);
// Show the Up button in the action bar.
setupActionBar();
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.orderByAscending(ParseConstants.KEY_USERNAME);
query.setLimit(1000);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success
mUsers = users;
String[] usernames = new String[mUsers.size()];
int i = 0;
for(ParseUser user : mUsers) {
usernames[i] = user.getUsername();
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
EditFriendsActivity.this,
android.R.layout.simple_list_item_checked,
usernames);
setListAdapter(adapter);
addFriendCheckmarks();
}
else {
Log.e(TAG, e.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(EditFriendsActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.findrecipients, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
SearchView.OnQueryTextListener queryTextListener = new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
android.content.Context context;
context = getApplicationContext();
Search srchContact = new Search(context, adapter, (ListView) mUsers);
srchContact.Search(arg0);
return true;
}
#Override
public boolean onQueryTextChange(String arg0) {
// TODO Auto-generated method stub
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public class Search
{
android.content.Context context;
CustomAdaptor tempAdptr;
CustomAdaptor adptr;
android.widget.ListView lstContact;
java.util.ArrayList<ParseUser> arrMyObject;
public Search(android.content.Context con , CustomAdaptor adp , android.widget.ListView lst )
{
context = con;
arrMyObject = new java.util.ArrayList<ParseUser>();
tempAdptr = new CustomAdaptor(context, android.R.layout.simple_list_item_checked, arrMyObject);
adptr = adp;
lstContact = lst;
}
public void Search(String strSearch)
{
lstContact.setAdapter(tempAdptr);
if(strSearch.equals(""))
{
lstContact.setAdapter(adptr);
return ;
}
arrMyObject.removeAll(arrMyObject) ;
for(int i = 0 ; i < mUsers.size() ; i++)
{
if(mUsers.get(i).getUsername().contains(strSearch))
{
//Add item to your list
}
}
tempAdptr.notifyDataSetChanged();
}
}
public class CustomAdaptor extends ArrayAdapter<ParseUser> {
android.content.Context context;
int resId;
java.util.ArrayList<ParseUser> arrData;
public CustomAdaptor(Context ac, int resource, java.util.ArrayList<ParseUser> data) {
super(ac, resource, data);
// TODO Auto-generated constructor stub
context = ac;
resId = resource;
arrData = data;
}
#Override
public android.view.View getView(final int position,android.view.View convertView, android.view.ViewGroup parent)
{
try
{
ParseUser member = arrData.get(position);
android.view.LayoutInflater inflater = (LayoutInflater) context.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
android.view.View Row =inflater.inflate(resId, parent , false);
// Set Your XML file
return Row;
}
catch (Exception e)
{
return null;
}
}
}
I have similar code that can be useful:
In this code , we have several class:
First:Search class that search in a list and show result in list view
Second: CustomAdapter that prepare list view
Third: Main that call Search function in Search class
public class Search
{
android.content.Context context;
CustomAdaptor tempAdptr;
CustomAdaptor adptr;
android.widget.ListView lstContact;
java.util.ArrayList<MyObject> arrMyObject;
public SearchContact(android.content.Context con , CustomAdaptor adp , android.widget.ListView lst )
{
context = con;
arrMyObject = new java.util.ArrayList<MyObject>();
tempAdptr = new CustomAdaptor(context, R.layout.contact_row, arrMyObject);
adptr = adp;
lstContact = lst;
}
public void Search(String strSearch)
{
lstContact.setAdapter(tempAdptr);
if(strSearch.equals(""))
{
lstContact.setAdapter(adptr);
return ;
}
arrMyObject.removeAll(arrMyObject) ;
for(int i = 0 ; i < MainActivity.GetArrMyObject().size() ; i++)
{
if(arrlist.get(i).contains(strSearch))
{
//Add item to your list
}
}
tempAdptr.notifyDataSetChanged();
}
}
//------------------------------------------------------------------------------------
public class CustomAdaptor extends ArrayAdapter<MyObject> {
android.content.Context context;
int resId;
java.util.ArrayList<MyObject> arrData;
public ContactAdaptor(android.content.Context ac, int resource , java.util.ArrayList<MyObject> data ) {
super(ac, resource, data);
context = ac;
resId = resource;
arrData = data;
}
#Override
public android.view.View getView(final int position,android.view.View convertView, android.view.ViewGroup parent)
{
try
{
MyObject member = arrData.get(position);
android.view.LayoutInflater inflater = (LayoutInflater) context.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
android.view.View Row =inflater.inflate(resId, parent , false);
// Set Your XML file
return Row;
}
catch (Exception e)
{
return null;
}
}
}
Now you can use this code in main:
SearchContact srchContact = new SearchContact(context, adptr, arraylist);
srchContact.Search(YourObject);

How do i pass the value of my username and its id to the next activity?

I want to be able to click on the "username" which will lead me to a new class - SetMed.java. Along with the username, i would like it's ID's to be passed on as well. I have tried using Intent but it does not work. Any help is greatly appreciated.
This is my MainActivity.java
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ListView_CheckBoxActivity extends Activity {
//Adapter
CheckboxAdapter listItemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Buttons and incident response
Button getValue=(Button)findViewById(R.id.get_value);
getValue.setOnClickListener(listener);
//listview
ListView list = (ListView) findViewById(R.id.list);
//Array list to store the data
ArrayList<HashMap<String, Object>> listData=new ArrayList<HashMap<String,Object>>();
String []name={"Diabetes","example","example","example","example"};
String []id={"Insulin, Glucagon, Prandin","example","example","example","example"};
for(int i=0;i<5;i++)
{
HashMap<String, Object>
map=new HashMap<String, Object>();
map.put("friend_image", R.drawable.icon);
map.put("friend_username", name[i]);
map.put("friend_id", id[i]);
map.put("selected", false);
//Add data
listData.add(map);
}
//Adapter
listItemAdapter = new CheckboxAdapter(this, listData);
list.setAdapter(listItemAdapter);
}
//Incident Response
OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(ListView_CheckBoxActivity.this, SetMed.class);
boolean[] array = new boolean[5];
array[0] = CheckboxAdapter.isChecked();
intent.putExtra("status", array);
HashMap<Integer, Boolean> state =listItemAdapter.state;
String options="Medicine Selected:";
for(int j=0; j<listItemAdapter.getCount(); j++)
{
System.out.println("state.get("+j+")=="+state.get(j));
if(state.get(j)!=null)
{
#SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
options+="\n"+username;
}
}
//Display selection
startActivity(intent)
}
};
}
This is my CheckBoxAdapter class.
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
public class CheckboxAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, Object>> listData;
//Record checkbox state
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
// Constructor
public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData)
{
this.context = context;
this.listData = listData;
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
// Rewrite View
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item, null);
ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
TextView username = (TextView) convertView.findViewById(R.id.friend_username);
username.setText((String) listData.get(position).get("friend_username"));
TextView id = (TextView) convertView.findViewById(R.id.friend_id);
id.setText((String) listData.get(position).get("friend_id"));
CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
state.put(position, isChecked);
} else
{
state.remove(position);
}
}
});
check.setChecked((state.get(position) == null ? false : true));
return convertView;
}
public static boolean isChecked() {
// TODO Auto-generated method stub
return false;
}
Class SetMed
public class SetMed extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_set_med);
TextView diabetes = (TextView) findViewById(R.id.diabetes);
Bundle bundle = this.getIntent().getExtras();
if (bundle.getBoolean("Diabetes", false)) {
diabetes.setText("Diabetes");
} else {
diabetes.setText("");
}
}
}

Categories

Resources