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();
}
Related
I am trying to remove a list item from the list view using a delete Menu in the list. The delete is must for my application.
I need to delete item from fragment.
The problem in item list, I don't know how to define this List<Item> listtache.
I use this, I can launch the app and everything loads correctly. Help me please.
public class Tachefragment extends Fragment implements AdapterView.OnItemClickListener {
String supprimertache = "http://192.168.1.15/projet/supprimertache.php";
private static final int CODE_GET_REQUEST = 1024;
Httppars ht = new Httppars();
TextView txtmen;
ProgressBar progressBar;
ListView listview;
Typeface type;
ImageView img;
HashMap<String,String> hashMap = new HashMap<>();
ItemAdapter adapter ;
String listviewid;
List<Item> listtache;
List<String> idlist = new ArrayList<>();
public Tachefragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tachefragment, container, false);
txtmen = (TextView) rootView.findViewById(R.id.textmenu);
img = (ImageView) rootView.findViewById(R.id.imgmenu);
progressBar = (ProgressBar) rootView.findViewById(R.id.ProgressBar1);
listview = (ListView) rootView.findViewById(R.id.listtask);
type = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
txtmen.setTypeface(type);
listview.setOnItemClickListener(this);
listtache = new ArrayList<Item>();
new ParseJSonDataClass(container.getContext()).execute();
return rootView;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listviewid = idlist.get(i).toString();
Toast.makeText(getContext() , listviewid.toString() , Toast.LENGTH_SHORT).show();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
List<Item> item;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
httpwebservice htp = new httpwebservice(Link.affichertache);
try {
htp.ExecutePostRequest();
if (htp.getResponseCode() == 200) {
FinalJSonResult = htp.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Item itm;
item = new ArrayList<Item>();
for (int i = 0; i < jsonArray.length(); i++) {
itm = new Item();
jsonObject = jsonArray.getJSONObject(i);
idlist.add(jsonObject.getString("idt").toString());
itm.setNomt(jsonObject.getString("nomt"));
itm.setDatet(jsonObject.getString("datet"));
itm.setHeuredebut(jsonObject.getString("heuredebut"));
itm.setTempstotal(jsonObject.getString("tempstotal"));
itm.setDescription(jsonObject.getString("description"));
item.add(itm);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, htp.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (item != null) {
progressBar.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
adapter = new ItemAdapter(item, context);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(listview);
} else {
progressBar.setVisibility(View.GONE);
txtmen.setVisibility(View.VISIBLE);
img.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater minfalter = getActivity().getMenuInflater();
minfalter.inflate(R.menu.menucontext , menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Item selectitem = (Item) adapter.getItem(info.position);
switch (item.getItemId()){
case R.id.supprimer:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Voulez vous supprimer cette tache" + " " + selectitem.getNomt()+" !")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
listtache.remove(selectitem);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
In your code listtache in initialization but it is empty list .you cannot remove item if it is empty.if you want remove item from listview than you should be use item which are use in adapter.
In below example listtache replace to mListItem.
For example:
String listviewid;
List<Item> mListItem;
HashMap<String,String> hashMap = new HashMap<>();
List<String> idlist = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tachefragment, container, false);
txtmen = (TextView) rootView.findViewById(R.id.textmenu);
img = (ImageView) rootView.findViewById(R.id.imgmenu);
progressBar = (ProgressBar) rootView.findViewById(R.id.ProgressBar1);
listview = (ListView) rootView.findViewById(R.id.listtask);
type = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
txtmen.setTypeface(type);
listview.setOnItemClickListener(this);
mListItem = new ArrayList<Item>();
ht= new Httppars();
new ParseJSonDataClass(container.getContext()).execute();
return rootView;
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
httpwebservice htp = new httpwebservice(Link.affichertache);
try {
htp.ExecutePostRequest();
if (htp.getResponseCode() == 200) {
FinalJSonResult = htp.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Item itm;
for (int i = 0; i < jsonArray.length(); i++) {
itm = new Item();
jsonObject = jsonArray.getJSONObject(i);
idlist.add(jsonObject.getString("idt").toString());
itm.setNomt(jsonObject.getString("nomt"));
itm.setDatet(jsonObject.getString("datet"));
itm.setHeuredebut(jsonObject.getString("heuredebut"));
itm.setTempstotal(jsonObject.getString("tempstotal"));
itm.setDescription(jsonObject.getString("description"));
mListItem.add(itm);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, htp.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mListItem != null) {
progressBar.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
adapter = new ItemAdapter(mListItem, context);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(listview);
} else {
progressBar.setVisibility(View.GONE);
txtmen.setVisibility(View.VISIBLE);
img.setVisibility(View.VISIBLE);
}
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Item selectitem = (Item) adapter.getItem(info.position);
switch (item.getItemId()){
case R.id.supprimer:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Voulez vous supprimer cette tache" + " " + selectitem.getNomt()+" !")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListItem.remove(selectitem);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
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;
}
}
I have a activity which implements onitemlongclicllstener to a list view. I use parse.com as my back end for retrieving data into listvview. Everything works fine but onitemlongclicllstener don't work on list view. Nothing happens when list item is long clicked
my main activity
public class InterActivity extends Activity implements OnItemLongClickListener
{
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
FinalAdapter adapter;
List<CodeList> codelist = null;
SharedPreference shrdPreference;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.inter_layout);
shrdPreference = new SharedPreference();
//Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(InterActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Please wait loading ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist = new ArrayList<CodeList>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
ob = query.find();
for (ParseObject inter : ob) {
ParseFile video = (ParseFile) inter.get("demovideo");
// ParseFile downloadfile = (ParseFile) inter.get("download");
CodeList map = new CodeList();
map.setListHeading((String) inter.get("listheading"));
map.setSingleItemHeading((String) inter.get("heading"));
map.setDownloadCode((String) inter.get("download"));
map.setDailogdemovideo(video.getUrl());
// map.setDownloadCode(downloadfile.getUrl());
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.inter_layoutListView);
// Pass the results into ListViewAdapter.java
adapter = new FinalAdapter(InterActivity.this,
codelist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemLongClickListener(InterActivity.this);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3)
{
ImageView fvrtebutton = (ImageView) view.findViewById(R.id.favbtn);
String tag = fvrtebutton.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
shrdPreference.addFavorite(InterActivity.this, codelist.get(position));
Toast.makeText(InterActivity.this, getString(R.string.fav_added),
Toast.LENGTH_SHORT).show();
fvrtebutton.setTag("yes");
fvrtebutton.setImageResource(R.drawable.favorite);
} else {
shrdPreference.removeFavorite(InterActivity.this, codelist.get(position));
fvrtebutton.setTag("no");
fvrtebutton.setImageResource(R.drawable.unfavorite);
Toast.makeText(InterActivity.this,
getString(R.string.fav_removed),
Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
final adapter.java
public class FinalAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ImageLoader imgLoader;
private List<CodeList> codeList = null;
private ArrayList<CodeList> arraylist;
SharedPreference shrdprfrnce;
public FinalAdapter(Context context,
List<CodeList> codeList) {
this.context = context;
this.codeList = codeList;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<CodeList>();
this.arraylist.addAll(codeList);
shrdprfrnce = new SharedPreference();
imageLoader = new ImageLoader(context);
}
public class ViewHolder{
TextView listHeading;
TextView listHash;
ImageView alphabetList;
ImageView favariteImage;
}
#Override
public int getCount()
{
return codeList.size();
}
#Override
public Object getItem(int position)
{
return codeList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent)
{
final ViewHolder holder;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.beg_list_item,null);
holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
//holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
holder.favariteImage = (ImageView) view.findViewById(R.id.favbtn);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
CodeList codes = (CodeList) getItem(position);
holder.listHeading.setText(codeList.get(position).getListHeading());
imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
holder.alphabetList);
if (checkFavoriteItem(codes)) {
holder.favariteImage.setImageResource(R.drawable.favorite);
holder.favariteImage.setTag("yes");
} else {
holder.favariteImage.setImageResource(R.drawable.unfavorite);
holder.favariteImage.setTag("no");
}
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return view;
}
public boolean checkFavoriteItem(CodeList checkCodes) {
boolean check = false;
List<CodeList> favorites = shrdprfrnce.getFavorites(context);
if (favorites != null) {
for (CodeList codes : favorites) {
if (codes.equals(checkCodes)) {
check = true;
break;
}
}
}
return check;
}
public void add(CodeList codes) {
(
codeList.add(codes);
notifyDataSetChanged();
}
public void remove(CodeList codes) {
codeList.remove(codes);
notifyDataSetChanged();
}
}
plz remove
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
bcoz it Get Full view Click Thats y ur OnLongClick is not working yet
try with return true;
#Override
public boolean onItemLongClick(AdapterView < ? > arg0, View arg1,
int pos, long id) {
Log.v("long clicked", "pos: " + pos);
return true;
}
I try to add search list form City list using my base adapter but it doesn't work. I want to search City in cities list. Here's My code.
My CitySerach :
private ProgressDialog pDialog;
EditText inputSearch;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// Hashmap for ListView
ArrayList<HashMap<String, String>> CitiesLI = new ArrayList<HashMap<String, String>>();
// url to make request
private static String url_cityli = "http://10.0.2.2/Myweb/ecities.php";
// JSON Keys
public static final String TAG_CITEMS_LI = "cities_li";
public static final String TAG_CID_LI = "city_id";
public static final String TAG_CNAME_LI = "city_name";
public static final String TAG_CIMG_LI = "image";
JSONArray cities_li = null;
ListView list;
CitySearchAdapter adapter;
private CitySearch activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tt);
CitiesLI = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.city_list);
//list click to details view of the place
list.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String cid_li = ((TextView) view.findViewById(R.id.cid_li)).getText().toString();
Intent i = new Intent(getApplicationContext(),
//Tab.class);
CityInfoActivity.class);
// Starting new intent
i.putExtra(TAG_CID_LI, cid_li);
startActivity(i);
//startActivityForResult(i, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new CitySearchAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CitySearch.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(url_cityli, "GET",
params);
Log.d("All Products: ", json.toString());
// looping through All data
try {
cities_li = json;
for (int i = 0; i < cities_li.length(); i++) {
JSONObject c = cities_li.getJSONObject(i);
// Storing each json item in variable
String city_id = c.getString(TAG_CID_LI);
String city_name =c.getString(TAG_CNAME_LI);
String image = c.getString(TAG_CIMG_LI);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//JSON Object
map.put(TAG_CID_LI, city_id);
map.put(TAG_CNAME_LI,city_name);
map.put(TAG_CIMG_LI, image);
// adding HashList to ArrayList
CitiesLI.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(CitiesLI);
//
// Enabling Search Filter
CitySearchAdapter adapter;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Listview name of the class
CitySearch.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
});
}
}
}
Here my CitylistAdapter :
public class CitySearchAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public CitySearchAdapter(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;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.te, null);
TextView city_id = (TextView) vi.findViewById(R.id.cid_li);
TextView image = (TextView) vi.findViewById(R.id.cimg_li);
TextView city_name = (TextView) vi.findViewById(R.id.cname);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.cimage);
HashMap<String, String> city_li = new HashMap<String, String>();
city_li = data.get(position);
city_id.setText(city_li.get(CityActivity.TAG_CID_LI));
image.setText(city_li.get(CityActivity.TAG_CIMG_LI));
city_name.setText(city_li.get(CityActivity.TAG_CNAME_LI));
imageLoader.DisplayImage(city_li.get(CityActivity.TAG_CIMG_LI),thumb_image);
return vi;
}
public Object getFilter() {
// TODO Auto-generated method stub
return null;
}
}
Pleace Help me.
Thanks all
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;
}
}
}