I have an listview in my application and when I add search to my listview it dosen't work at all.
when I add those code to my project, getfilter doesn't resolve.
enter code here
public class MyActivity extends Activity {
InputStream in;
BufferedReader reader;
String line = "1";
public ListView listView;
VehicleAdapter adapter;
ArrayList<String> dataItems = new ArrayList<String>();
public int star = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
G.currentActivity = this;
setContentView(R.layout.main);
// Adad.setTestMode(true);
ReadText();
// String[] dataArray = dataItems.toArray(new String[0]);
//String[] dataArray = getResources().getStringArray(R.array.listdata);
//List<String> dataTemp = Arrays.asList(dataArray);
// dataItems.addAll(dataTemp);
listView = (ListView) findViewById(R.id.mainList);
EditText ed = (EditText) findViewById(R.id.editText1);
ArrayList<Bitmap> arr_bitmaps = new ArrayList<Bitmap>(4);
adapter = new VehicleAdapter(MyActivity.this, arr_bitmaps, dataItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// vaghti kar bar harfi vared kard josteju mikone :
MyActivity.this.adapter.getFilter().filter(arg0);
}
});
}
public class VehicleAdapter extends BaseAdapter {
ArrayList<String> arr_calllog_name = new ArrayList<String>();
public Activity context;
ArrayList<Bitmap> imageId;
public LayoutInflater inflater;
public VehicleAdapter(Activity context, ArrayList<Bitmap> arr_bitmaps, ArrayList<String> arr_calllog_name) {
super();
this.imageId = arr_bitmaps;
this.context = context;
this.arr_calllog_name = arr_calllog_name;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr_calllog_name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class ViewHolder {
TextView txtName;
ImageButton btn;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.child_listview, null);
holder.txtName = (TextView) convertView.findViewById(R.id.childTextView);
holder.btn = (ImageButton) convertView.findViewById(R.id.childButton);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtName.setText(PersianReshape.reshape(arr_calllog_name.get(position)));
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/B Morvarid_YasDL.com.ttf");
//holder.txtName.setTypeface(G.defaultFont);
holder.txtName.setTypeface(custom_font);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = arr_calllog_name.get(position);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.contact) {
Intent intent = new Intent(MyActivity.this, ContactUs.class);
startActivity(intent);
}
return super.onOptionsItemSelected(menuItem);
}
private void ReadText() {
try {
in = this.getAssets().open("text.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
dataItems.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my broblem is this code.
enter code here
MyActivity.this.adapter.getFilter().filter(arg0);
why getFilter() doesn't resolve?
Is it releted to my adaptor?
please help
why getFilter() doesn't resolve?
Because Filterable interface is not implemented in VehicleAdapter class.
To call adapter.getFilter().filter for Activity usng Adapter object need to implement Filterable interface in Adapter class and override getFilter.
See following example how to make Adapter Filterable:
Android Filter Custom ListView (BaseAdapter)
In custom adapter it would not work. this code for search will work in SimpleAdapter. For your adapter you have to write custom code for search.
Follow this link it would do as per your need (search filter in custom adapetr)
Custom Listview Adapter with filter Android
Related
My code is working fine when it comes to clicking items. But the problem arises when I try to open activities after filtering listview. It always opens activity 1.
Here is my source code.
navigate.java
public class navigate extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] names;
int[] flag;
ArrayList<Object> arraylist = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Generate sample data
rank = new String[] { "1", "2", "3", "4", "5","6","7","8","9","10","11"};
names = new String[] { "Animal Bite", "Asthma Attack", "Choking","CPR","Black eye",
"Drowning", "Fracture","Heart Attack","Insect Bite","Poisoning","Spinal Injury",};
flag = new int[] { R.drawable.animal,
R.drawable.asthma, R.drawable.choke, R.drawable.cpricon,
R.drawable.blckeye,R.drawable.drown,R.drawable.fracture,R.drawable.hrtattck,R.drawable.insect,R.drawable.poison,R.drawable.spinal };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
Object wp = new Object(rank[i], names[i], flag[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
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.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> listView, View view,
final int position, long id) {
switch ((int) adapter.getItemId(position)) {
case 0:
Intent newActivity = new Intent(navigate.this, animalbite.class);
startActivity(newActivity);
break;
case 1:Intent newActivity1 = new Intent(navigate.this, asthmaattack.class);
startActivity(newActivity1);
break;
case 2:Intent newActivity2 = new Intent(navigate.this, animalbite.class);
startActivity(newActivity2);
break;}
}
});
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Object> objectList = null;
private ArrayList<Object> arraylist;
public ListViewAdapter(Context context,
List<Object> objectList) {
mContext = context;
this.objectList = objectList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Object>();
this.arraylist.addAll(objectList);
}
public class ViewHolder {
TextView name;
ImageView flag;
}
#Override
public int getCount() {
return objectList.size();
}
#Override
public Object getItem(int position) {
return objectList.get(position);
}
public String getCountry(int position){return objectList.get(position).getCountry();}
#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.listview_item, null);
// Locate the TextViews in listview_item.xml
//holder.rank = (TextView) view.findViewById(R.id.rank);
holder.name = (TextView) view.findViewById(R.id.name);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(objectList.get(position).getRank());
holder.name.setText(objectList.get(position).getCountry());
;
// Set the results into ImageView
holder.flag.setImageResource(objectList.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
// Pass all data rank
// Start SingleItemView Class
switch (position) {
case 0:
Intent intent = new Intent(mContext, animalbite.class);
mContext.startActivity(intent);break;
case 1:
Intent i2 = new Intent(mContext, asthmaattack.class);
mContext.startActivity(i2);break;
case 2:
Intent i3 = new Intent(mContext, choking.class);
mContext.startActivity(i3);break;
case 3:
Intent i4 = new Intent(mContext, cpr.class);
mContext.startActivity(i4);break;
case 4:
Intent i5 = new Intent(mContext, lackeye.class);
mContext.startActivity(i5);break;
case 5:
Intent i6 = new Intent(mContext, drowning.class);
mContext.startActivity(i6);break;
case 6:
Intent i7 = new Intent(mContext, Fracture.class);
mContext.startActivity(i7);break;
case 7:
Intent i8 = new Intent(mContext, heartattack.class);
mContext.startActivity(i8);break;
case 8:
Intent i9 = new Intent(mContext, insectbite.class);
mContext.startActivity(i9);break;
case 9:
Intent i10 = new Intent(mContext, poisoning.class);
mContext.startActivity(i10);break;
case 10:
Intent i11 = new Intent(mContext, spinalinjury.class);
mContext.startActivity(i11);break;
}}});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
objectList.clear();
if (charText.length() == 0) {
objectList.addAll(arraylist);
} else {
for (Object wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
objectList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Object.java
public class Object {
private String rank;
private String country;
private int flag;
public Object(String rank, String country,
int flag) {
this.rank = rank;
this.country = country;
this.flag = flag;
}
public String getCountry() {
return this.country;
}
public int getFlag() {
return this.flag;
}
}
How can I open different activities while clicking on listview items after I filter them.
This is the sample code I used. Although it doesn't provide the functionality to open original activities through intent ,just some forged up activity,so I'm trying to change that.
http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/
I think your adapter has problem, this below sample code of my application is extended from Filterable and work fine
public class AdapterContacts extends BaseAdapter implements Filterable {
private LayoutInflater inflater;
private Context context;
private List<ContactLists> categoryArrayList;
private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
private NameFilter filter;
public AdapterContacts(ArrayList<ContactLists> array) {
categoryArrayList = array;
}
public AdapterContacts(Context context, List<ContactLists> array) {
this.context = context;
inflater = LayoutInflater.from(this.context);
categoryArrayList = array;
originalList.addAll(array);
}
#Override
public int getCount() {
return categoryArrayList.size();
}
#Override
public ContactLists getItem(int position) {
return categoryArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_contacts_list_item, null);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
ContactLists item = getItem(position);
mViewHolder.fillItems(this, item, position);
return convertView;
}
private static class UI extends HelperUI {
public TextView tv_person_nickname_mobile_number;
public TextView btn_invite_message;
public ImageView img_contact_image;
public ImageView imgv_user_rank;
public TextView tv_contact_name;
public LinearLayout ll_root;
public UI(View view) {
parseUi(view);
}
}
private class ViewHolder {
private UI UI;
public ViewHolder(View view) {
UI = new UI(view);
}
public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
UI.tv_contact_name.setText(item.getContact_name());
if (item.getStatus() == 1) {
UI.btn_invite_message.setVisibility(View.GONE);
UI.imgv_user_rank.setVisibility(View.VISIBLE);
if (item.getRank() != null || !TextUtils.isEmpty(item.getRank())) {
//Picasso.with(G.context).load(item.getRank()).into(UI.imgv_user_rank);
}
UI.tv_person_nickname_mobile_number.setText(item.getNick_name());
//UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_button_actions));
if (item.getContact_image() == null || TextUtils.isEmpty(item.getContact_image())) {
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
} else {
// show user avatar from web
//Picasso.with(G.context).load(item.getContact_image()).into(UI.img_contact_image);
UI.img_contact_image.setImageBitmap(BitmapFactory.decodeFile(G.DIR_IMAGE + "/" + item.getContact_image()));
}
} else {
// UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_invite_actions));
UI.btn_invite_message.setVisibility(View.VISIBLE);
UI.imgv_user_rank.setVisibility(View.GONE);
UI.btn_invite_message.setText(UC.getString(R.string.invite_person));
UI.btn_invite_message.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.shape_invite_button_default));
UI.tv_person_nickname_mobile_number.setText(item.getMobile_number());
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new NameFilter();
}
return filter;
}
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
}
I am trying to make a activity which has a listview ,it has edittexts,it displays the previously stored data and when clicked on edittexts and edit them, it stores the edited data and displays new data on list view. I am using hashmap to parse json values. Could you help me?
Here is my code:
public class AdditionalNutrientGoalsActivity extends ActionBarActivity
{
private static final String TAG = AdditionalNutrientGoalsActivity.class.getName();
HashMap<String, Integer> map = new HashMap<String, Integer>();
private String[] arrText =
new String[]{"Saturated Fat","Trans fat","polyunsaturated fat","Sodium","Fiber","Monosaturated Fat","Potassium"
,"Sugar","Iron","Cholestrol","Calcium","Vitamin C","Vitamin A"};
private String[] arrTemp =
new String[]{ "00 %","00 %","00 %","38 %","77 %","1049 %","00 %","00 %","38 %"
,"77 %","1049 %","77 %","1049 %"};// for now hardcodedvalues
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_nutrient_goals);
MyListAdapter myListAdapter = new MyListAdapter();
ListView listView = (ListView) findViewById(R.id.customlist1);
listView.setAdapter(myListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("list view", position + "");
showDialog(arrText[position]);
// Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_SHORT).show();
}
});
ImageView IVback = (ImageView) findViewById(R.id.back);
IVback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AdditionalNutrientGoalsActivity.this.finish();
}
});
GetData getData=new GetData();
getData.execute();
}
void showDialog(String title)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AdditionalNutrientGoalsActivity.this);
// set title
alertDialogBuilder.setTitle(title);
alertDialogBuilder
.setMessage("Enter in gm/day")
.setCancelable(false)
.setPositiveButton("Set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
//AdditionalNutrientGoalsActivity.this.finish();
}
})
.setView(new EditText(AdditionalNutrientGoalsActivity.this))
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private class MyListAdapter extends BaseAdapter
{
#Override
public int getCount() {
if(arrText != null && arrText.length != 0){
return arrText.length;
}
return 0;
}
#Override
public Object getItem(int position) {
return arrText[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String data="";
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = AdditionalNutrientGoalsActivity.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.custom_additional_nutri, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textView45);
holder.editText1 = (TextView) convertView.findViewById(R.id.textView46);
data =holder.editText1.getText().toString();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(arrText[position]);
holder.editText1.setText(data);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
// arrTemp[holder.ref] = arg0.toString();
saveData saveData=new saveData();
saveData.execute();
}
});
return convertView;
}
private class ViewHolder {
TextView textView1;
TextView editText1;
int ref;
}
}
and this is my GetData functionality:
private class GetData extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("username", SharedPref.getData(getApplicationContext(), SharConstants.username)));
parameters.add(new BasicNameValuePair("password", SharedPref.getData(getApplicationContext(), SharConstants.password)));
// parameters.add(new BasicNameValuePair("token", SharedPref.getData(getApplicationContext(), SharConstants.token)));
parameters.add(new BasicNameValuePair("date_time", SharedPref.getData(getApplicationContext(), SharConstants.date_time)));
GetJsonFromServer getJsonFromServer = new GetJsonFromServer();
String response = getJsonFromServer.getJson(ApiList.getAdditionalNutrientGoals, "POST", parameters);
Log.e(TAG, response);
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try
{
JSONObject jsonObject = new JSONObject(s);
JSONObject response = jsonObject.getJSONObject("response");
if(response.getInt("success") == 1)
{
JSONObject object= response.getJSONObject("data");
ArrayList<HashMap<String,Integer>> parameters = new ArrayList<HashMap<String, Integer>>();
// adding each child node to HashMap key => value
map.put("id",object.getInt("id"));
map.put("user_id",object.getInt("user_id"));
map.put("saturated_fat",object.getInt("saturated_fat"));
map.put("polyunsaturated_fat",object.getInt("polyunsaturated_fat"));
map.put("monounsaturated_fat",object.getInt("monounsaturated_fat"));
map.put("trans_fat",object.getInt("trans_fat"));
map.put("cholesterol",object.getInt("cholesterol"));
map.put("sodium",object.getInt("sodium"));
map.put("potassium",object.getInt("potassium"));
map.put("fiber", object.getInt("fiber"));
map.put("sugar", object.getInt("sugar"));
map.put("Vitamin_A", object.getInt("Vitamin_A"));
map.put("Vitamin_C", object.getInt("Vitamin_C"));
map.put("calcium", object.getInt("calcium"));
map.put("iron", object.getInt("iron"));
parameters.add(map);
Log.d("map","map"+" "+parameters);
}
else
{
Toast.makeText(getApplicationContext(), "Server Error, Try Again Later.", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e(TAG, e.toString());
Toast.makeText(getApplicationContext(), "Server Error", Toast.LENGTH_LONG).show();
}
}
I am not getting idea as to how to store data and fetch data.
I'd like to save SparseBooleanArray using either SharedPreferences, or anything else, that's more preferred.
I've tried using https://stackoverflow.com/a/16711258/2530836, but everytime the activity is created, bundle is re-initialized, and bundle.getParcelable() returns null. I'm sure there is a workaround for this, but I haven't arrived at it despite a few hours of brainstorming.
Also, if there isn't, could I use something like SharedPreferences?
Here's the code:
public class ContactActivity extends Activity implements AdapterView.OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
ArrayList<String> exceptions = new ArrayList<String>();
MyAdapter adapter;
Button select;
Bundle bundle = new Bundle();
Context contactActivityContext;
SharedPreferences prefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_layout);
getAllContacts(this.getContentResolver());
ListView list= (ListView) findViewById(R.id.lv);
adapter = new MyAdapter();
list.setAdapter(adapter);
list.setOnItemClickListener(this);
list.setItemsCanFocus(false);
list.setTextFilterEnabled(true);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
for (int i = 0; i < name1.size(); i++)
{
if (adapter.isChecked(i)) {
checkedcontacts.append(name1.get(i).toString());
exceptions.add(name1.get(i).toString());
checkedcontacts.append(", ");
}
}
checkedcontacts.deleteCharAt(checkedcontacts.length() - 2);
checkedcontacts.append("selected");
editor = prefs.edit();
editor.putInt("Status_size", exceptions.size()); /* sKey is an array */
for(int i=0;i<exceptions.size();i++)
{
editor.remove("Status_" + i);
editor.putString("Status_" + i, exceptions.get(i));
}
editor.commit();
Toast.makeText(ContactActivity.this, checkedcontacts, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
adapter.toggle(arg2);
}
private void setContext(Context contactActivityContext){
this.contactActivityContext = contactActivityContext;
}
protected Context getContext(){
return contactActivityContext;
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC" );
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ SparseBooleanArray mCheckStates;
ContactActivity mContactActivity = new ContactActivity();
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
int mPos;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");
mInflater = (LayoutInflater) ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
public void setPosition(int p){
mPos = p;
}
public int getPosition(){
return mPos;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
setPosition(position);
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
#Override
public void onDestroy(){
bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
super.onDestroy();
}
}
You can store it in SharedPreferances
The thing about sparsebooleanarrays is: it maps integers to boolean values, hence you can save it as a string, eliminate the braces,spaces and = signs, and all you have is an int value (for index value) and the corresponding boolean value, separated by a comma, now use the string accordingly. Hope it helps :)
Bundle is created by you in the class and it is not used by activity to store the value.
If You're using the bundle of application, still you can't get the instance once you killed the application.
For you're problem better go with shared preference but in shared preference you can't store objects.
If you want to use shared preference then there are 2 solutions.
Convert object to string and store in shared preference and retrieve back and reform the Object from String. (use Gson or Jackson or you're preferred way )
Use Complex Preferences third party one, Where you can store objects and retrieve directly.
If you're more interested using bundle only then Check this discussion on stackoverflow.
save-bundle-to-sharedpreferences
how-to-serialize-a-bundle
Hope this will help you.
When I had problems trying to fix the position of my listView items to the desired intent when filtered, and got info I could override the problem using a custom adapter, I have done that but I do not know how to assign the clicks to each items, please check below code:
public class IndexPageActivity extends Activity {
ListView listView;
EditText editTextB;
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener((OnItemClickListener) this);
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements OnItemClickListener{
ArrayList<SingleRow> pagelist;
Context context;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<SingleRow>();
Resources res = c.getResources();
String [] pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(new SingleRow(pagedatas[i]));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public Object getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return row;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
// TODO Auto-generated method stub
}
}
I will appreciate any help given. Thank Yhu!
EDIT
Will this work?
if (index == 0) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page1.html");
startActivity(i);
} else if (index == 1) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page2.html");
startActivity(i);
Edited ALL
I just got what you need, I added a filter to your baseAdapter and then on text change within the editText You filter the listView and then you go to the activity needed.
here is the full code but you need to bare in mind that I have changed the following:
I changed the pageList to ArrayList instead of
There is a bug in filtering that when I erase what I wrote in the EditText it doesnt update the ListView, you need to figure out why.
I changed the returned value of the function getItem(int i) from Object to String
Within the onItemClick you have to search for the name instead of the position.
here is the code:
public class IndexPageActivity extends Activity implements OnItemClickListener{
ListView listView;
EditText editTextB;
PagesAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
adapter1 = new PagesAdapter(this);
listView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
listView.setOnItemClickListener(this);
editTextB.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
IndexPageActivity.this.adapter1.getFilter().filter(cs.toString());
adapter1.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Intent i;
String name = adapter1.getItem(position);
Log.d("id", name);
if (name.equals("Item1"))
{
i = new Intent(this, anActivity.class);
startActivity(i);
}
else if (name.equals("Item2"))
{
i = new Intent(this, anActivity2.class);
startActivity(i);
}
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements Filterable{
ArrayList<String> pagelist;
List<String> arrayList;
Context context;
String [] pagedatas;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<String>();
Resources res = c.getResources();
pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(pagedatas[i]);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public String getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
String temp=pagelist.get(i);
pagetitle.setText(temp);
return row;
}
public class filter_here extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ){
Result.values = pagelist;
Result.count = pagelist.size();
return Result;
}
ArrayList<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString;
for(int i = 0; i<pagelist.size(); i++){
filterableString = pagelist.get(i);
if(filterableString.toLowerCase().contains(filterString)){
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
pagelist = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return new filter_here();
}
}
Two different ways for it:
1) If you want to use something like this at onCreate of your activity;
listView.setOnItemClickListener((OnItemClickListener) this);
You should implement OnItemClickListener to your activity:
IndexPageActivity extends Activity implements OnItemClickListener
and implement its onItemClick method at your activity. (also remove OnItemClickListener interface from your custom adapter)
2) You can simply use below without implementing OnItemClickListener to any class:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: handle row clicks here
}
I suggest 2nd option. That is easier.
Edit: This not relevant to your problem but you should reuse your views/rows at listView. Change your getView method to:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.single_row, parent, false);
} else {
view = convertView;
}
TextView pagetitle = (TextView) view.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return view;
}
Set your setOnItemClickListenerlike this:
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Your code here
//int position is the index of the list item you clicked
//use it to manipulate the item for each click
}
});
}
I have using data in db and showing in listview for each row i have given an sms button to go to the smsactivity,but while clicking the sms button its not going to anyactiviyt,it simply there,not showing any error or logcat error also
this is my activity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item2);
mDbHelper = new GinfyDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData() {
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE,GinfyDbAdapter.CATEGORY_COLUMN_CONTENT,GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text2,R.id.text1,R.id.count};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row2,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return mDbHelper.fetchProjectByName(constraint.toString());
}
});
tts = new TextToSpeech(this, this);
final ListView lv = getListView();
txtText = (TextView) findViewById(R.id.text1);
lv.setTextFilterEnabled(true);
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
//btnaudioprayer.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main1, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddyourprayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void speakOut() {
// String text = txtText.getText().toString();
// String text = "Android speech";
tts.speak(typed, TextToSpeech.QUEUE_FLUSH, null);
}
class CustomAdapter extends SimpleCursorAdapter {
private LayoutInflater mInflater;
#SuppressWarnings("deprecation")
public CustomAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
// TODO Auto-generated constructor stub
mInflater= LayoutInflater.from(context);
}
public View getView(final int position, View convertView, ViewGroup parent, Cursor cursor)
{
ViewHolder holder;
if(convertView==null){
convertView= mInflater.inflate(R.layout.activity_row2, null);
convertView = inflater.inflate(R.layout.activity_row2, parent, false);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.text1);
holder.tv1 = (TextView) convertView.findViewById(R.id.text2);
holder.buttonsms = (Button) convertView.findViewById(R.id.buttonsms);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
int col1 = cursor.getColumnIndex("title");
final String title = cursor.getString(col1 );
int col2 = cursor.getColumnIndex("content");
final String content = cursor.getString(col2 );
holder.tv.setText( title);
holder.tv1.setText( content);
holder.buttonsms.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer sb2 = new StringBuffer();
sb2.append("Title:");
sb2.append(Html.fromHtml(title));
sb2.append(",Content:");
sb2.append(Html.fromHtml(content));
sb2.append("\n");
String strContactList1 = (sb2.toString().trim());
sendsmsdata(strContactList1);
}
});
// bindView(v,context,cursor);
return convertView;
}
public class ViewHolder {
TextView tv,tv1;
Button buttonsms;
}
}
public void sendsmsdata(String strContactList1) {
Intent intent3=new Intent(YourPrayerActivity.this,SendSMSActivity.class);
intent3.putExtra("firstKeyName", strContactList1);
startActivity(intent3);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I am using simpleadapter for fetching data from db,after that for button function i am using customadapter to fetch data from listview,class customadapter extper SimpleCursorAdapter
Here i mention my xml file also.
<LinearLayout
android:id="#+id/Share"
android:layout_width="0.0dip"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:background="#drawable/button_new_feed"
android:orientation="horizontal" >
<Button
android:id="#+id/buttonsms"
android:layout_width="25.0dip"
android:layout_height="fill_parent"
android:layout_marginLeft="4.0dip"
android:src="#drawable/sms" />
<ImageButton
android:id="#+id/mail"
android:layout_width="25.0dip"
android:layout_height="fill_parent"
android:layout_marginLeft="6.0dip"
android:src="#drawable/mail" />
</LinearLayout>
It was hard to find out what went wrong
You have this and CustomAdapter. You have button inside the activity_row2 inflated for your row items.
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row2,
projectsCursor,
from,
to,
0);
You have defined a CustomAdapter but never use it.
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE,GinfyDbAdapter.CATEGORY_COLUMN_CONTENT,GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text2,R.id.text1,R.id.count};
dataAdapter = new CustomAdapter (YourPrayerActivity .this, R.layout.activity_row2, projectsCursor, from, to);
Also Change your CustomAdapter as below
class CustomAdapter extends SimpleCursorAdapter {
private LayoutInflater mInflater;
#SuppressWarnings("deprecation")
public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
{
super(context, layout, c, from, to);
mInflater= LayoutInflater.from(context);
Toast.makeText(YourPrayerActivity.this, "text", 1000).show();
// TODO Auto-generated constructor stub
}
#Override
public void bindView(View view, Context context, final Cursor cursor){
int row_id = cursor.getColumnIndex("_id"); //Your row id (might need to replace)
TextView tv = (TextView) view.findViewById(R.id.text1);
final TextView tv1 = (TextView) view.findViewById(R.id.text2);
int col1 = cursor.getColumnIndex("title");
String title = cursor.getString(col1 );
int col2 = cursor.getColumnIndex("content");
final String content = cursor.getString(col2 );
tv.setText( title);
tv1.setText( content);
Button button = (Button) view.findViewById(R.id.buttonsms);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
Log.i("....................",""+cursor.getCount());
Toast.makeText(YourPrayerActivity.this, "text",400000).show();
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.activity_row2, parent, false);
bindView(v,context,cursor);
return v;
}
}
buttonSMS.setFocusable(false);
set this property