Listview with filter - android

i am trying to filter the listview using edit text at the top but it providing null pointer exception in the adapter2.filter(text) of add text changed listener . please provide me some suggestion`
Here is my edit text`
friendsList.setAdapter(new FriendListAdapter(this));
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
System.out.println("test=="+text);
adapter2.filter(text);
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
//adapter.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
Here is my adapter
public class FriendListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
FriendsList friendsList;
Context context;
ViewHolder holder;
private boolean userSelected = false;
private RadioButton mCurrentlyCheckedRB;
private int mResourceId = 0;
private LayoutInflater mLayoutInflater;
private RadioButton mSelectedRB;
private int mSelectedPosition = -1;
public FriendListAdapter(FriendsList friendsList) {
this.friendsList = friendsList;
if (Utility.model == null) {
Utility.model = new FriendsGetProfilePics();
}
Utility.model.setListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
#Override
public int getCount() {
return jsonArray.length();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewgroup) {
JSONObject jsonObject = null;
Model model = (Model) getItem(position);
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
e1.printStackTrace();
}
View hView = convertView;
if (convertView == null) {
hView = mInflater.inflate(R.layout.friend_item, null);
ViewHolder holder = new ViewHolder();
holder.profile_pic = (ImageView) hView
.findViewById(R.id.profile_pic);
holder.name = (TextView) hView.findViewById(R.id.name);
holder.info = (TextView) hView.findViewById(R.id.info);
holder.radiobt = (RadioButton) hView.findViewById(R.id.radio);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
if (position == getCount() - 1 && userSelected == false) {
holder.radiobt.setChecked(true);
mCurrentlyCheckedRB = holder.radiobt;
} else {
holder.radiobt.setChecked(false);
}
holder.radiobt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if((position != mSelectedPosition && mSelectedRB != null)){
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton)v;
System.out.println("onItemClick ");
try {
if (graph_or_fql.equals("graph")) {
System.out.println("in if loop ");
friendId = jsonArray.getJSONObject(position).getLong("id");
image = jsonArray.getJSONObject(position).getString("picture");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
} else {
System.out.println("in else loop ");
friendId = jsonArray.getJSONObject(position).getLong("uid");
image = jsonArray.getJSONObject(position).getString(
"pic_square");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
}
check = true;
name = jsonArray.getJSONObject(position).getString("name");
Toast.makeText(getApplicationContext(), "You Selected : " + name,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
}
}
});
if(mSelectedPosition != position){
holder.radiobt.setChecked(false);
}else{
holder.radiobt.setChecked(true);
if(mSelectedRB != null && holder.radiobt != mSelectedRB){
mSelectedRB = holder.radiobt;
}
}
try {
if (graph_or_fql.equals("graph")) {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("id"),
jsonObject.getString("picture")));
} else {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("uid"),
jsonObject.getString("pic_square")));
}
} catch (JSONException e) {
holder.name.setText("");
}
try {
holder.name.setText(jsonObject.getString("name"));
} catch (JSONException e) {
holder.name.setText("");
}
try {
if (graph_or_fql.equals("graph")) {
holder.info.setText(jsonObject.getJSONObject("location")
.getString("name"));
} else {
JSONObject location = jsonObject
.getJSONObject("current_location");
holder.info.setText(location.getString("city") + ", "
+ location.getString("state"));
}
} catch (JSONException e) {
holder.info.setText("");
}
return hView;
}
// Filter Class
public void filter(String charText) {
System.out.println("in adapter filter");
charText = charText.toLowerCase(Locale.getDefault());
System.out.println("1");
rowitems.clear();
System.out.println("2");
if (charText.length() == 0) {
System.out.println("3");
rowitems.addAll(listData);
} else {
for (Model wp : listData) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
rowitems.add(wp);
}
}
}
notifyDataSetChanged();
}
private class ViewHolder {
ImageView profile_pic;
TextView name;
TextView info;
// CheckBox check;
RadioButton radiobt;
}
}
Here is my main activity
public class FriendsList extends Activity implements OnItemClickListener{
private Handler mHandler;
public static Long friendId;
public static String name = "";
protected ListView friendsList;
protected static JSONArray jsonArray;
protected String graph_or_fql;
public Button bt;
public static String image = "0";
public boolean check = false;
public static String freind_id = "";
public boolean select = false;
public RadioButton radiobtn;
public ListView friendList;
private List<Model> rowitems=null;
ArrayList<Model> listData;
AdapterList adapter;
EditText search;
FriendListAdapter adapter2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.friends_list);
//radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
bt = (Button) findViewById(R.id.com_facebook_picker_done_button);
radiobtn = (RadioButton) findViewById(R.id.radio);
search=(EditText) findViewById(R.id.editText100);
Bundle extras = getIntent().getExtras();
String apiResponse = extras.getString("API_RESPONSE");
graph_or_fql = extras.getString("METHOD");
try {
if (graph_or_fql.equals("graph")) {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
} else {
jsonArray = new JSONArray(apiResponse);
}
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
return;
}
friendsList = (ListView) findViewById(R.id.friends_list);
// friendsList.setAdapter(new FriendListAdapter(this));
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);
friendsList.setOnItemClickListener(this);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter2.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
i am passing the facebook friend list to the listview.please provide some suggestion
Thanks in advance

For filter the listview using edit text at the top .
I used this code.
Make one list called searchResults than in onTextChanged method of edittext simply do this-
String searchString = `your edittext object`.getText().toString();
int textLength = searchString.length();
searchResults.clear();
for (int i = 0; i < `your main list of items`.size(); i++) {
String name = `your main list of items`.get(i).get("`your key`").toString();
System.out.println(" name " + name);
if (textLength <= title.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(name.substring(0, textLength))) {
searchResults.add(`your main list of items`.get(i));
System.out.println("the array list is "+ `your main list of items`.get(i));
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
}
}
if (searchResults.isEmpty()) {
Toast toast = Toast.makeText(getApplicationContext(),"No Items Matched",Toast.LENGTH_SHORT);
toast.show();
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged();
and on setOnItemClickListener just check searchResults.isEmpty() if true than use your your main list of items and if false than use searchResults list.
May be it will help you.try this.

change your filter with following code:
#Override
public Filter getFilter() {
//Log.d("in filter", "yes");
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
and set your list in this function and after set your list :
oReturn.values = YourList;
and finall
return oReturn;
and in Your search.addTextChangedListener(new TextWatcher()) just in onTextChanged add following line:
adapter2.getFilter().filter(s.toString());

Try this,
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);

Related

Fragment listview last value is not disappear

I have listview All the values are delete and update properly but only the last value is not delete in the listview.
Added a full fragment code. Take a look
For example
If I have three values in the listview If I delete 1 and 2 its removing and listview refresh properly but the last one is not refreshed in the listview
private SwipeMenuListView mylistview;
String userid;
private EditText txtsearch;
private ArrayList<JobItem> jobitems;
private JobListAdapter adapter;
SwipeMenuCreator creator;
ImageLoader imageLoader;
DisplayImageOptions options;
public Fragment_Employer_MyJobList() {
}
public static float dp2px(Context context, int dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layoutjoblist, container, false);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(1000))
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.img_app_icon)
.showImageOnFail(R.drawable.img_app_icon)
.showImageOnLoading(R.drawable.img_app_icon).build();
mylistview = (SwipeMenuListView) rootView.findViewById(R.id.mylistview);
creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
openItem.setWidth((int) dp2px(getActivity(), 90));
// set item title
openItem.setTitle("DELETE");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
}
};
txtsearch = (EditText) rootView.findViewById(R.id.txtsearch);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
String text = txtsearch.getText().toString().toLowerCase(Locale.getDefault());
if (adapter != null)
adapter.filter(text);
}
});
return rootView;
}
SharedPreferences settings;
#Override
public void onResume() {
super.onResume();
jobitems = new ArrayList<JobItem>();
jobitems.clear();
adapter.notifyDataSetChanged();
settings = getActivity().getSharedPreferences(AppUtils.PREFS_NAME, Context.MODE_PRIVATE);
userid = settings.getString("userid", "");
AuthController.getStaticInstance().
employer_joblist(getActivity(), userid, APIConstants
.POST, new AuthControllerInterface.AuthControllerCallBack()
{
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONArray mainarray = new JSONArray(message);
for (int i = 0; i < mainarray.length(); i++) {
JSONObject json_job = mainarray.getJSONObject(i);
JobItem item = new JobItem();
item.Id = json_job.getString("ID");
item.EMPID = json_job.getString("EMPID");
item.TITLE = json_job.getString("TITLE");
item.DESC = json_job.getString("DESC");
item.CID = json_job.getString("CID");
item.PRICE = json_job.getString("PRICE");
item.LOCAT = json_job.getString("LOCAT");
item.ADATE = json_job.getString("ADATE");
item.FOLLOW = json_job.getString("FOLLOW");
JSONArray array = json_job.getJSONArray("IMAGES");
if (array.length() > 0) {
if (!array.isNull(0))
item.IMG1 = array.getString(0);
if (!array.isNull(1))
item.IMG2 = array.getString(1);
if (!array.isNull(2))
item.IMG3 = array.getString(2);
if (!array.isNull(3))
item.IMG4 = array.getString(3);
if (!array.isNull(4))
item.IMG5 = array.getString(4);
}
jobitems.add(item);
}
adapter = new JobListAdapter(getActivity(), jobitems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobItem item = jobitems.get(position);
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
mylistview.setMenuCreator(creator);
mylistview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
// unfollow
userid = settings.getString("userid", "");
AuthController.getStaticInstance().employer_delete_job(getActivity(), userid, jobitems.get(position).Id, APIConstants.POST, new AuthControllerInterface.AuthControllerCallBack() {
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
// onResume();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
// onResume();
}
//setup
onResume();
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
}
#Override
public void showLoading() {
AppUtils.showProgress(getActivity(), "Please wait...");
// onResume();
}
#Override
public void stopLoading() {
AppUtils.dismissProgress();
// onResume();
}
public class OnItemClickListner implements View.OnClickListener {
int mposition;
JobItem item;
public OnItemClickListner(int position, JobItem item) {
this.mposition = position;
this.item = item;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class JobListAdapter extends BaseAdapter {
LayoutInflater _inflater;
private List<JobItem> worldpopulationlist = null;
private ArrayList<JobItem> arraylist;
public JobListAdapter(Context context, List<JobItem> worldpopulationlist) {
_inflater = LayoutInflater.from(context);
this.worldpopulationlist = worldpopulationlist;
this.arraylist = new ArrayList<JobItem>();
this.arraylist.addAll(worldpopulationlist);
}
public int getCount() {
// TODO Auto-generated method stub
return worldpopulationlist.size();
}
public JobItem getItem(int position) {
// TODO Auto-generated method stub
return worldpopulationlist.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder _holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_job_row, null);
_holder = new ViewHolder();
_holder.txtjobtitle = (TextView) convertView
.findViewById(R.id.txtjobtitle);
_holder.txtjobbudget = (TextView) convertView
.findViewById(R.id.txtjobbudget);
_holder.txtjobdesc = (TextView) convertView
.findViewById(R.id.txtjobdesc);
_holder.imageviewjob = (ImageView) convertView
.findViewById(R.id.imageviewjob);
_holder.txtlocation = (TextView) convertView
.findViewById(R.id.txtlocation);
convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}
_holder.txtjobtitle.setText(worldpopulationlist.get(position).TITLE.trim());
_holder.txtjobbudget.setText(worldpopulationlist.get(position).PRICE.trim());
_holder.txtjobdesc.setVisibility(View.VISIBLE);
_holder.txtjobbudget.setVisibility(View.GONE);
_holder.txtjobdesc.setText(worldpopulationlist.get(position).DESC);
imageLoader.displayImage(worldpopulationlist.get(position).IMG1, _holder.imageviewjob, options);
_holder.txtlocation.setText(worldpopulationlist.get(position).LOCAT.trim());
//convertView.setOnClickListener(new OnItemClickListner(position, worldpopulationlist.get(position)));
return convertView;
}
private class ViewHolder {
ImageView imageviewjob;
TextView txtjobtitle, txtjobdesc;
TextView txtlocation, txtjobbudget;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (JobItem wp : arraylist) {
if (wp.TITLE.toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
you have to tell your ListView that something changed in it's former List by calling notifyDataSetChanged() method of your adapter
Also you should not create a new instance of ArrayList, but only clear the old instance. Don't forget to check for null before clearing.
try calling the adapter again with a null like.
setListAdapter()

pass filtered listview item to next activity

Here i am using using BaseAdapter to filter my listview items.when without using search option if i click on my listview item the listView.setOnItemClickListener works well, I mean the item at the clicked position is passed to next activity.But on the filtered result if i click on the item,some other data is passed to next activity..what might be the issue.?can anyone please help me to solve this issue..?
Activity
public class BindTenGPS extends Activity {
private MenuItem menuItem;
DbaAdapter db;
private ProgressDialog progressDialog;
ListView listView ;
EditText inputSearch;
private BindTenDeviceBaseAdapter adapter;
List<RowTenDevice> rowTenDevice;
ArrayList<String> DeviceName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list1_main);
inputSearch = (EditText)findViewById(R.id.inputSearch);
db=new DbaAdapter(getApplicationContext());
new LoadTrackNumbers().execute();
}
private class LoadTrackNumbers extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPreExecute()
{
//Create a new progress dialog
progressDialog = new ProgressDialog(BindTenGPS.this);
//Set the progress dialog to display a horizontal progress bar
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
//Set the dialog message to 'Loading application View, please wait...'
progressDialog.setMessage("Loading application View, please wait...");
//This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(true);
//This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
//The maximum number of items is 100
progressDialog.setMax(100);
//Set the current progress to zero
progressDialog.setProgress(0);
//Display the progress dialog
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
//Get the current thread's token
synchronized (this)
{
DeviceName.clear();
publishProgress(10);
this.wait(500);
Connection conn = null;
try {
Log.w("Error connection","shyam1");
String driver = "net.sourceforge.jtds.jdbc.Driver";
Log.w("Error connection","shyam2");
Log.i("Android"," MySQL Connect Example0.");
Class.forName(driver).newInstance();
Log.w("Error connection","shyam3");
String connString = "jdbc:jtds:sqlserver://ip address;instance=SQLEXPRESS;DatabaseName=AAUMConnect;";
String username = "username";
String password = "password";
Log.w("Error connection","shyam4");
publishProgress(20);
this.wait(500);
publishProgress(30);
this.wait(500);
publishProgress(40);
this.wait(500);
publishProgress(50);
this.wait(500);
conn = DriverManager.getConnection(connString,username,password);
publishProgress(80);
Log.w("Error connection","shyam5");
Statement stmt = conn.createStatement();
ResultSet reset;
db.open();
int superuser = db.GetISSuperUser();
db.close();
db.open();
int clientid = db.GetClientID();
db.close();
if(superuser == 0)
{
db.open();
String branch = db.GetBranch();
db.close();
reset = stmt.executeQuery("SELECT dbo.fn_AddEveryNthItem(LEFT(AssignVehicleToTrackTable, LEN(AssignVehicleToTrackTable) - 1), ',','#', 1) AS DeviceName FROM (SELECT DeviceName + ',' FROM AssignVehicleToTrack where ClientID = " + clientid + " and BranchName = '" + branch.trim() + "' and VirtualNo = 'GPS' order by DeviceName FOR XML PATH ('')) T1 (AssignVehicleToTrackTable)");
}
else
{
reset = stmt.executeQuery("SELECT dbo.fn_AddEveryNthItem(LEFT(AssignVehicleToTrackTable, LEN(AssignVehicleToTrackTable) - 1), ',','#', 1) AS DeviceName FROM (SELECT DeviceName + ',' FROM AssignVehicleToTrack where ClientID = " + clientid + " and VirtualNo = 'GPS' order by DeviceName FOR XML PATH ('')) T1 (AssignVehicleToTrackTable)");
}
//Print the data to the console
Log.w("Error connection","shyam6");
int i1 = 0, c = 0;
try
{
while(reset.next()){
publishProgress(c);
String[] tokens = new String[100];
tokens = reset.getString(1).split("#");
for(int i=0;i<tokens.length;i++)
{
DeviceName.add(tokens[i].substring(1));
}
i1++;
c+=10;
}
}
catch(Exception ex)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "GPS Device not available", Toast.LENGTH_LONG).show();
}
});
}
reset.close();
conn.close();
rowTenDevice = new ArrayList<RowTenDevice>();
for (int j = 0; j < DeviceName.size(); j++) {
RowTenDevice item = new RowTenDevice(DeviceName.get(j));
Log.w("Data:","D"+j+" : "+DeviceName.get(j));
rowTenDevice.add(item);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
listView = (ListView) findViewById(R.id.list);
Log.w("Data:","E1");
adapter = new BindTenDeviceBaseAdapter(BindTenGPS.this, rowTenDevice);
Log.w("Data:","E2");
listView.setAdapter(adapter);
Log.w("Data:","E3");
inputSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
BindTenGPS.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(
AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(BindTenGPS.this, ShowGPS.class);
intent.putExtra("DeviceList", rowTenDevice.get(position).getDeviceName());
startActivity(intent);
}
});
Log.w("Data:","E4");
}
});
} catch (Exception e)
{
Log.w("Error connection","shyam" + e.getMessage());
e.printStackTrace();
}
this.wait(500);
publishProgress(100);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
//set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
//after executing the code in the thread
#Override
protected void onPostExecute(Void result)
{
//close the progress dialog
progressDialog.dismiss();
//initialize the View
//setContentView(R.layout.list1_main);
}
}
}
BaseAdapter
public class BindTenDeviceBaseAdapter extends BaseAdapter implements Filterable {
Context context;
List<RowTenDevice> rowTenDevice;
List<RowTenDevice> arrayList; //temporary list to store filtered values.
LayoutInflater inflater;
public BindTenDeviceBaseAdapter(Context context, List<RowTenDevice> items) {
this.context = context;
this.rowTenDevice = items;
this.arrayList = items;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView txtTenDevice;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return arrayList.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_tendevice, null);
holder = new ViewHolder();
holder.txtTenDevice = (TextView) convertView.findViewById(R.id.tvTenDevice);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowTenDevice rowItem = (RowTenDevice) getItem(position);
holder.txtTenDevice.setText(rowItem.getDeviceName());
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
Filter filter = new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// TODO Auto-generated method stub
arrayList = (List<RowTenDevice>) results.values; // has the filtered values
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults results = new FilterResults();
List<RowTenDevice> FilteredArrList = new ArrayList<RowTenDevice>();
if (rowTenDevice == null) {
rowTenDevice = new ArrayList<RowTenDevice>(arrayList); // saves the original data in rowTenDevice
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = rowTenDevice.size();
results.values = rowTenDevice;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < rowTenDevice.size(); i++) {
RowTenDevice data = rowTenDevice.get(i);
if(data.getDeviceName().toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
RowTenDevice
public class RowTenDevice {
private String devicename;
public RowTenDevice(String devicename) {
this.devicename = devicename;
}
public String getDeviceName() {
return devicename;
}
public void setDeviceName(String devicename) {
this.devicename = devicename;
}
}
In onItemClick you are using rowTenDevice.get(position).getDeviceName(). This causes the problem. You need filtered item so create a public method in adapter to get arrayList.get(position).getDeviceName(). As arrayList is filtered list, it will give you required result.
Use following code:-
Replace line :- intent.putExtra("DeviceList", rowTenDevice.get(position).getDeviceName());
With
intent.putExtra("DeviceList", ((RowTenDevice)adapter.getItem(position)).getDeviceName());

how to make input search for custom list view

hello to every one i have a custom list view with a search and animation all works cool but in search i have a little problem . I would like to, for example, I search for a word in a sentence.
But the way I used to enter the letters i have to put them in sequence.
here is my code:
public class MainActivity extends Activity {
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] country;
Typeface tf;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
editsearch = (EditText) findViewById(R.id.search);
list = (ListView) findViewById(R.id.listview);
tf = Typeface.createFromAsset(getAssets(), "fonts/BKOODB.TTF");
country = new String[54];
for (int x = 1; x < 54 + 1; x = x + 1) {
String this_subject = "mo_" + String.valueOf(x);
int resID = getResources().getIdentifier(this_subject, "string", getPackageName());
country[x - 1] = getResources().getString(resID);
}
for (int i = 0; i < 54; i++) {
WorldPopulation wp = new WorldPopulation(country[i]);
// Binds all strings into an array
arraylist.add(wp);
}
adapter = new ListViewAdapter(this, arraylist);
list.setAdapter(adapter);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
hideKeyboard();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
new CountDownTimer(500, 500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
hideKeyboard();
}
}.start();
}
public class WorldPopulation {
private String country;
public WorldPopulation(String country) {
this.country = country;
}
public String getCountry() {
return this.country;
}
}
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_in_right);
public ListViewAdapter(Context context, List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView country;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview_item, parent, false);
TextView textview = (TextView) row.findViewById(R.id.country);
ImageView im = (ImageView) row.findViewById(R.id.imageitem);
im.setImageResource(R.drawable.hair);
textview.setText(worldpopulationlist.get(position).getCountry());
textview.setTypeface(tf);
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_in_right);
row.startAnimation(animation);
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// *********************************************************
// in here it does not send right number to secend activity*
// *********************************************************
int orgPos = 0;
if (country.length != worldpopulationlist.size()) {
notifyDataSetChanged();
// The list on which we clicked is sorted!
String clickedText = worldpopulationlist.get(position).toString();
int i1 = 0;
boolean found = false;
while (i1 < country.length && found == false) {
if (clickedText == country[i1]) {
orgPos = i1;
found = true;
} else {
i1++;
}
}
Intent i2 = new Intent(mContext, SingleItemView.class);
String Subject_number = String.valueOf(orgPos + 1);
i2.putExtra("subject_number", Subject_number);
startActivity(i2);
} else {
Intent i = new Intent(mContext, SingleItemView.class);
String Subject_number = String.valueOf(position + 1);
i.putExtra("subject_number", Subject_number);
startActivity(i);
}
}
});
return row;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (final WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
private void hideKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
try doing it in afterTextChanged Method because this allows you to enter all the text. and follow this link
public void afterTextChanged(Editable s) {
}
Try with custom adapter.
this will help you.Link

getting all selected from listview

I have a listview with searchview and multiple selection option.For that i'm trying the following code that is as follows..
Mainactivity:-
public class MainActivity extends Activity {
Context context = null;
ContactsAdapter objAdapter;
ListView lv = null;
EditText edtSearch = null;
LinearLayout llContainer = null;
Button btnOK = null;
RelativeLayout rlPBContainer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
rlPBContainer = (RelativeLayout) findViewById(R.id.pbcontainer);
edtSearch = (EditText) findViewById(R.id.input_search);
llContainer = (LinearLayout) findViewById(R.id.data_container);
btnOK = (Button) findViewById(R.id.ok_button);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getSelectedContacts();
}
});
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
String text = edtSearch.getText().toString()
.toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
addContactsInList();
}
private void getSelectedContacts() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
sb.append(bean.getName());
sb.append(",");
}
}
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
}
}
private void addContactsInList() {
// TODO Auto-generated method stub
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(MainActivity.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
hidePB();
}
};
thread.start();
}
void showPB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.VISIBLE);
edtSearch.setVisibility(View.GONE);
btnOK.setVisibility(View.GONE);
}
});
}
void hidePB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.GONE);
edtSearch.setVisibility(View.VISIBLE);
btnOK.setVisibility(View.VISIBLE);
}
});
}
}
Adapter class:-
public class ContactsAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
private List<ContactObject> mainDataList = null;
private ArrayList<ContactObject> arraylist;
public ContactsAdapter(Context context, List<ContactObject> mainDataList) {
mContext = context;
this.mainDataList = mainDataList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ContactObject>();
this.arraylist.addAll(mainDataList);
}
static class ViewHolder {
protected TextView name;
protected TextView number;
protected CheckBox check;
protected ImageView image;
}
#Override
public int getCount() {
return mainDataList.size();
}
#Override
public ContactObject getItem(int position) {
return mainDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_row, null);
holder.name = (TextView) view.findViewById(R.id.contactname);
holder.number = (TextView) view.findViewById(R.id.contactno);
holder.check = (CheckBox) view.findViewById(R.id.contactcheck);
holder.image = (ImageView) view.findViewById(R.id.contactimage);
view.setTag(holder);
view.setTag(R.id.contactname, holder.name);
view.setTag(R.id.contactno, holder.number);
view.setTag(R.id.contactcheck, holder.check);
holder.check
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton vw,
boolean isChecked) {
int getPosition = (Integer) vw.getTag();
mainDataList.get(getPosition).setSelected(
vw.isChecked());
}
});
} else {
holder = (ViewHolder) view.getTag();
}
holder.check.setTag(position);
holder.name.setText(mainDataList.get(position).getName());
holder.number.setText(mainDataList.get(position).getNumber());
if (getByteContactPhoto(mainDataList.get(position).getImage()) == null) {
holder.image.setImageResource(R.drawable.abc_ab_share_pack_mtrl_alpha);
} else {
holder.image.setImageBitmap(getByteContactPhoto(mainDataList.get(position).getImage()));
}
holder.check.setChecked(mainDataList.get(position).isSelected());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mainDataList.clear();
if (charText.length() == 0) {
mainDataList.addAll(arraylist);
} else {
for (ContactObject wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
mainDataList.add(wp);
}
}
}
notifyDataSetChanged();
}
public Bitmap getByteContactPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = mContext.getContentResolver().query(photoUri,
new String[]{ContactsContract.Contacts.Photo.DATA15}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
}
my problem is
step-1 : i have selected a contact from the listview.
step-2 : now i have searched for xxx contact and i selected it.
step-3 : now when i press on ok button it is retrieving only xxx contact.
step-4 : It needs to retrieve all the selected contacts from the view
How can i do that help me in solving this.
You can simply make a list of objects and everytime user select an item in list view you add object contained in this view, and go further. If user wants to delete an object just search for it in your list and delete it.
with the help of This link
I have taken the one array and added all the selected items before text changing this solved my problem.
MainActivity:-
public class MainActivity extends Activity {
Context context = null;
ContactsAdapter objAdapter;
ListView lv = null;
EditText edtSearch = null;
LinearLayout llContainer = null;
Button btnOK = null;
RelativeLayout rlPBContainer = null;
ArrayList<String> selected = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
rlPBContainer = (RelativeLayout) findViewById(R.id.pbcontainer);
edtSearch = (EditText) findViewById(R.id.input_search);
llContainer = (LinearLayout) findViewById(R.id.data_container);
btnOK = (Button) findViewById(R.id.ok_button);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
getSelectedContacts();
}
});
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
String text = edtSearch.getText().toString()
.toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
selected.add(bean.getName());
}
}
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
addContactsInList();
}
private void getSelectedContacts() {
StringBuffer sb = new StringBuffer();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
selected.add(bean.getName());
}
}
for (int i = 0; i < selected.size(); i++) {
sb.append(selected.get(i));
sb.append(",");
}
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
}
}
private void addContactsInList() {
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(MainActivity.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
hidePB();
}
};
thread.start();
}
void showPB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.VISIBLE);
edtSearch.setVisibility(View.GONE);
btnOK.setVisibility(View.GONE);
}
});
}
void hidePB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.GONE);
edtSearch.setVisibility(View.VISIBLE);
btnOK.setVisibility(View.VISIBLE);
}
});
}
}

Custom adapter never empty

I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.

Categories

Resources