Hi i am new to android.
1) I have a listview with names and checkboxes. I want to have a search function on this list where the user can search for a specific name.
2) I want the user to be able to select all the names in the listview with one click. When the user press on the selectAll button all the checkboxes should be checked.
I am a total beginner and totally confused.
Thanks
public class NewstipsActivity extends Activity {
CheckboxAdapter listItemAdapter;
ArrayList<String> listData;
Button getValue;
Button getchoice;
Button selectAll;
EditText edt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getchoice = (Button) findViewById(R.id.getchoice);
getValue = (Button)findViewById(R.id.get_value);
selectAll = (Button)findViewById(R.id.selectAll);
edt=(EditText)findViewById(R.id.EditText01);
ListView list = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String,Object>>();
JSONObject json = getJSON.getJSONfromURL("http://test.com/myurl.php");
try {
JSONArray results = json.getJSONArray("results");
for(int i = 0; i < results.length(); i++){
// creating new HashMap
HashMap<String, Object> map=new HashMap<String, Object>();
JSONObject e = results.getJSONObject(i);
// adding each child node to HashMap key => value
map.put("n_id", String.valueOf(i));
map.put("friend_image", R.drawable.icon);
map.put("friend_username", " " + e.getString("n_newspaper"));
map.put("friend_id", " " + e.getString("n_id"));
map.put("selected", false);
listData.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
listItemAdapter = new CheckboxAdapter(this, listData);
list.setAdapter(listItemAdapter);
//problem1 search
list.setTextFilterEnabled(true);
edt.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged( CharSequence s, int arg1, int arg2, int arg3)
{
Toast.makeText (NewstipsActivity.this, "On Search", Toast.LENGTH_LONG).show();
}
#Override
public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
{
}
#Override
public void afterTextChanged( Editable arg0)
{
}
});
getValue.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
HashMap<Integer, Boolean> state =listItemAdapter.state;
String options="Newspapers: ";
for(int j=0; j<listItemAdapter.getCount(); j++){
System.out.println("state.get("+j+")=="+state.get(j));
if(state.get(j)!=null){
#SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
String id=map.get("friend_id").toString();
options+="\n"+id+"."+username;
}
}
Toast.makeText(getApplicationContext(), options, Toast.LENGTH_LONG).show();
Intent intent = new Intent(NewstipsActivity.this, NewstipsPhoto.class);
startActivity(intent);
}
});
getchoice.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewstipsActivity.this, NewstipsPhoto.class);
startActivity(intent);
}
});
selectAll.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class CheckboxAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, Object>> listData;
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData) {
this.context = context;
this.listData = listData;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item, null);
ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
TextView username = (TextView) convertView.findViewById(R.id.friend_username);
username.setText((String) listData.get(position).get("friend_username"));
TextView id = (TextView) convertView.findViewById(R.id.friend_id);
id.setText((String) listData.get(position).get("friend_id"));
CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
state.put(position, isChecked);
} else {
state.remove(position);
}
}
});
check.setChecked((state.get(position) == null ? false : true));
return convertView;
}
}
}
Related
I am developing an apps. Where i Want to add a search functionality but i failed to do it. I try to search the whole list but my search is work only in one item in the list view.
Here is my MainActivity Code
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
private ProgressBar spinner;
ArrayList<HashMap<String, String>> arraylist;
private long lastPressedTime;
public static String imgURL = "url";
public static String VIDEO_ID = "videoId";
public static String TITLE = "title";
EditText editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final boolean b=wifiManager.isWifiEnabled();
ConnectivityManager cManager=(ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
final NetworkInfo nInfo=cManager.getActiveNetworkInfo();
if(nInfo!=null&& nInfo.isConnected()) {
Toast.makeText(this, "You are Connected to the Internet", Toast.LENGTH_LONG).show();
setContentView(R.layout.listview_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
new DownloadJSON().execute();
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Your DATA Connection is Currently Unreachable")
.setMessage("Connect your WiFi or 2G/3G DATA Connection")
.setPositiveButton("WiFi ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi Enabling in 5sec Please Wait", Toast.LENGTH_LONG).show();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.setNegativeButton("3G/2G ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//use here tablayout to work when 3G/2G connecion is available
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
Intent myints = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
Toast.makeText(MainActivity.this, "Your DATA Connection is NOW Connected", Toast.LENGTH_LONG).show();
startActivity(myints);
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "To use this Application you have to Connected to the Internet", Toast.LENGTH_LONG).show();
finish();
}
})
.setCancelable(false)
.show();
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=bangla+video+song&maxResults=50&key=api_key");
try {
// Locate the array name in JSON
JSONArray jsonarray = jsonobject.getJSONArray("items");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
JSONObject jsonObjId = jsonobject.getJSONObject("id");
map.put("videoId", jsonObjId.getString("videoId"));
JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
map.put("title", jsonObjSnippet.getString("title"));
//map.put("description", jsonObjSnippet.getString("description"));
// map.put("flag", jsonobject.getString("flag"));
JSONObject jsonObjThumbnail = jsonObjSnippet.getJSONObject("thumbnails");
String imgURL = jsonObjThumbnail.getJSONObject("high").getString("url");
map.put("url",imgURL);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
spinner.setVisibility(View.GONE);
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
}
});
}
}
// Dialouge Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new android.support.v7.app.AlertDialog.Builder (this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
MainActivity.this.finish();
}
})
.setNeutralButton(R.string.neutral, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Rate This App", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=")));
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
and here is my list view adapter code.
// Declare Variables
MainActivity main;
private PublisherInterstitialAd mPublisherInterstitialAd;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View view, ViewGroup parent) {
// Declare Variables
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
// rank.setText(resultp.get(MainActivity.VIDEO_ID));
country.setText(resultp.get(MainActivity.TITLE));
// population.setText(resultp.get(MainActivity.DESCRIPTION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.imgURL), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, PlayerViewDemoActivity.class);
intent.putExtra("videoId", resultp.get(MainActivity.VIDEO_ID));
context.startActivity(intent);
mPublisherInterstitialAd.isLoaded();
mPublisherInterstitialAd.show();
requestNewInterstitial();
}
});
return itemView;
}
private void requestNewInterstitial() {
PublisherAdRequest adRequest = new PublisherAdRequest.Builder()
.addTestDevice("020AC93F90A14C29209AF3CA716FFBD4")
.build();
mPublisherInterstitialAd.loadAd(adRequest);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.add(resultp); // resultp is hashmap
} else {
if (resultp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(resultp);
}
}
notifyDataSetChanged();
}
}
You should declare one more ArrayList name allData, it always store all objects.
ArrayList<HashMap<String, String>> allOriginalData; // always store all object
ArrayList<HashMap<String, String>> data; // use for store object that display in the ListView
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
allOriginalData = new ArrayList<HashMap<String, String>>(arraylist);
imageLoader = new ImageLoader(context);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
// search empty -> new data = all original data
data = new ArrayList<HashMap<String, String>>(allData);
} else {
// loop all original data
// check the condition and make the new data for display in ListView
for(int i = 0; i < allOriginalData.size(); i++){
HashMap<String, String> resultA = allOriginalData.get(i);
if (resultA.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(resultA);
}
}
}
notifyDataSetChanged();
}
Hi I am trying a search/filter app where data are coming from mySql database to fill up the listview. The populating of listview is working perfectly fine, except for the filtering part. It doesn't filter the listview, it's empty. Help please.
MAIN Activity:
public class MainActivity extends Activity {
public static final String url = "";
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] country;
String[] population;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Generate list View from ArrayList
displayListView();
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
// 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
}
});
}
private void displayListView() {
// Creating volley request obj
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void parseData(String json) {
JSONArray items = null;
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
items = jsonObject.getJSONArray("result");
rank = new String[items.length()];
country = new String[items.length()];
population = new String[items.length()];
for (int i = 0; i < items.length(); i++) {
JSONObject jo = items.getJSONObject(i);
rank[i] = jo.getString("rank");
country[i] = jo.getString("country");
population[i] = jo.getString("population");
WorldPopulation wp = new WorldPopulation(rank[i], country[i],
population[i]);
// Binds all strings into an array
arraylist.add(wp);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
BASE Adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
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 rank;
TextView country;
TextView population;
}
#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) {
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.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position).getPopulation());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank",(worldpopulationlist.get(position).getRank()));
// Pass all data country
intent.putExtra("country",(worldpopulationlist.get(position).getCountry()));
// Pass all data population
intent.putExtra("population",(worldpopulationlist.get(position).getPopulation()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
And the model:
public class WorldPopulation {
private String rank;
private String country;
private String population;
public WorldPopulation(String rank, String country, String population) {
this.rank = rank;
this.country = country;
this.population = population;
}
public String getRank() {
return this.rank;
}
public String getCountry() {
return this.country;
}
public String getPopulation() {
return this.population;
}
}
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
i have a listview which show list of item .item come from database.i used custom adapter.which work fine now i add edittext on the top of my listview i want to filter my list.for exmple when i type word "A" in edittext list filter and show me the only name which start from A.i try to do this but i fail.i am new in android development so please help me to solve my problem.
this is my datalist code
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changes the Text
listDataAdapter.getFilter().filter(cs);
}
#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
}
});
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, carbohydrates;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
carbohydrates = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, carbohydrates, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"dish name is : " + dataprovider.getName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
Detail.class);
startActivity(intent);
}
});
}
public void gobackk(View view) {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
this is my custom adapter code
public abstract class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
boolean index[];
public ListDataAdapter(Context context, int resource) {
super(context, resource);
index = new boolean[list.size()];
}
static class LayoutHandler {
TextView name, quantity, calorie, fat, protein, sugar, carbohydrates;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
index = new boolean[list.size()];
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.name = (TextView) row
.findViewById(R.id.text_dish_name);
layoutHandler.quantity = (TextView) row
.findViewById(R.id.text_dish_quantity);
layoutHandler.calorie = (TextView) row
.findViewById(R.id.text_dish_calorie);
layoutHandler.fat = (TextView) row.findViewById(R.id.text_dish_fat);
layoutHandler.protein = (TextView) row
.findViewById(R.id.text_dish_protein);
layoutHandler.sugar = (TextView) row
.findViewById(R.id.text_dish_sugar);
layoutHandler.carbohydrates = (TextView) row
.findViewById(R.id.text_dish_carbohydrates);
layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.name.setText(dataProvider.getName());
layoutHandler.quantity.setText(dataProvider.getQuantity());
layoutHandler.calorie
.setText(String.valueOf(dataProvider.getCalorie()));
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.carbohydrates.setText(dataProvider.getCarbohydrates());
//layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(position);
layoutHandler.names.setChecked(index[position]);
layoutHandler.names
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
index[pos] = isChecked;
showCheckedButton(position, isChecked);
}
});
return row;
}
public ArrayList<DataProvider> getSelectedIndexes() {
int size = list.size();
ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
for (int i = 0; i < size; i++) {
DataProvider cItem = (DataProvider) list.get(i);
if (index[i]) {
selectedItems.add(cItem);
}
}
return selectedItems;
}
protected abstract void showCheckedButton(int position, boolean value);
}
I am trying to implement a search option for listview which also has a checkbox in each row.
I am getting the friends list from Google plus account and showing them in the listview
using customAdapter.
The friend's name, image and id are stored in hashmap.
The problem for e.g.
I select first and second item and then type a text in the search box - the results are shown with the first item and second item being checked automatically.
Or another example:
When I select an item in search results and now clear the search text the checkbox gets cleared too.
How do I fix this issue?
Friends.java
ArrayList<HashMap<String, String>> friendList;
ArrayList<HashMap<String, String>> searchResults;
static boolean[] isChecked;
static boolean[] isSearchChecked;
private EditText searchText;
static int listPerson = 1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activityfriends);
res = this.getResources();
searchText = (EditText) findViewById(R.id.searchText);
searchText.setOnClickListener(this);
friendList = new ArrayList<HashMap<String, String>>();
searchResults = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.friend_list);
searchText.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)
{
listofperson = 2;
searchResults.clear();
if (friendList.size() > 0 )
{
for (HashMap<String, String> map : friendList)
{
if(map.get(KEY_DISPLAY_NAME).toLowerCase().contains(s.toString().toLowerCase()))
{
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(KEY_ID, map.get(KEY_ID));
hashMap.put(KEY_DISPLAY_NAME, map.get(KEY_DISPLAY_NAME));
hashMap.put(KEY_IMAGEPROFILE_URL, map.get(KEY_IMAGEPROFILE_URL));
searchResults.add(hashMap);
isSearchChecked = new boolean[searchResults.size()];
for (int i = 0; i < isSearchChecked.length; i++)
{
isSearchChecked[i] = false;
}
}
}
adapter= new FriendsAdapter(Friends.this, searchResults);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener()
{
private CheckBox cb;
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
if (listPerson == 1)
{
String person_ID = friendList.get(position).get(KEY_ID);
String person_DISPLAY_NAME = friendList.get(position).get(KEY_DISPLAY_NAME);
cb = (CheckBox) view.findViewById(R.id.checkBox);
//cb.setChecked(true);
cb.performClick();
if (cb.isChecked())
{
//add to be database
}
else if (!cb.isChecked())
{
//remove from database
}
}
else
{
String SearchResult_person_ID = searchResults.get(position).get(KEY_ID);
String SearchRResult_person_DISPLAY_NAME = searchResults.get(position).get(KEY_DISPLAY_NAME);
cb = (CheckBox) view.findViewById(R.id.checkBox);
//cb.setChecked(true);
cb.performClick();
if (cb.isChecked())
{
//add to database
}
else if (!cb.isChecked())
{
//remove from database
}
}
}
});
}
OnResult of Gplus client I have the following line of code:
PersonBuffer personBuffer = peopleData.getPersonBuffer();
try
{
friendsCount = personBuffer.getCount();
for (int i = 0; i < friendsCount; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, personBuffer.get(i).getId());
map.put(KEY_DISPLAY_NAME, personBuffer.get(i).getDisplayName());
map.put(KEY_IMAGEPROFILE_URL, personBuffer.get(i).getImage().getUrl());
friendList.add(map);
}
}
finally
{
personBuffer.close();
}
if (friendCount > 0)
{
isChecked = new boolean[peopleCount];
for (int i = 0; i < isChecked.length; i++)
{
isChecked[i] = false;
}
adapter = new FriendsAdapter(this, friendList);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
FriendsAdapter.java
public class FriendsAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public FriendsAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount()
{
return data.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout view = (LinearLayout) convertView;
if (view == null)
{
view = (LinearLayout) inflater.inflate(R.layout.friend_list_row, null);
}
HashMap<String, String> listFriends = new HashMap<String, String>();
listFriends = data.get(position);
TextView friendsname = (TextView) view.findViewById(R.id.friendsName); // title
friendsname.setText(listFriends.get(Friends.KEY_DISPLAY_NAME));
ImageView thumb_image = (ImageView)view.findViewById(R.id.list_image); // thumb image
imageLoader.DisplayImage(listFriends.get(Friends.KEY_IMAGEPROFILE_URL), thumb_image);
CheckBox cBox = (CheckBox) view.findViewById(R.id.checkBox);
cBox.setOnCheckedChangeListener(null);
cBox.setChecked(InviteFriends.isChecked[position]);
cBox.setTag(Integer.valueOf(position));
cBox.setOnCheckedChangeListener(mListener);
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
Friends.isChecked[(Integer)buttonView.getTag()] = isChecked;
}
};