1.My search functionality works fine using edittext,but for example if I type "1" than delete it the listview shows null,how can I make listview shows JSON again after I type something then delete it?
2.If I change to search COUNTRY rather than RANK ,I need to type full character like "INDIA" how can I just type "in" then it can appear INDIA?
thanks
MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String URL="url";
static String FLAG = "flag";
EditText mEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
mEditText = (EditText) findViewById(R.id.inputSearch);
mEditText.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) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.RANK);
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#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("http://ndublog.twomini.com/123.txt.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("url",jsonobject.getString("url"));
map.put("flag", jsonobject.getString("flag"));
// 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
mProgressDialog.dismiss();
}
}
}
ListViewAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
public 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 null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
TextView population;
TextView url;
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);
url=(TextView)itemView.findViewById(R.id.url);
// 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.RANK));
country.setText(resultp.get(MainActivity.COUNTRY));
population.setText(resultp.get(MainActivity.POPULATION));
url.setText(resultp.get(MainActivity.URL));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), 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, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
intent.putExtra("url",resultp.get(MainActivity.URL));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
Edit this code below,thanks
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String URL="url";
static String FLAG = "flag";
EditText mEditText;
String globalQuery="";
ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
ListViewAdapter globalListAdapter,globalAdapter=null;
public void filteredList()
{
//First of all checks for our globalList is not a null one.
if(globalList!=null)
{
ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
ListViewAdapter globalAdapter = null;
if(!globalQuery.trim().equals(""))
{
boolean isThereAnyThing=false;
for(int i=0;i<globalList.size();i++)
{
//Get the value of globalList that is HashMap indexed at i.
HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
String rank=tempMap.get(MainActivity.RANK);
String country=tempMap.get(MainActivity.COUNTRY);
String population=tempMap.get(MainActivity.POPULATION);
String url=tempMap.get(MainActivity.URL);
String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
{
//If anything matches then it will add to tempList
tempList.add(tempMap);
isThereAnyThing=true;
}
}
//Checks for is there anything matched from the ArrayList with the user type search query
if(isThereAnyThing)
{
//then set the globalAdapter with the new HashMaps tempList
globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
listview.setAdapter(globalAdapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
else
{
//If else set list adapter to null
setListAdapter(null);
}
}
else
{
// Do something when there's no input
if(globalAdapter==null)
{
//If no user inputs then it will list everything in the globalList.
justListAll();
}
else
{
final ListViewAdapter finalGlobalAdapter = globalAdapter;
runOnUiThread(new Runnable()
{
public void run()
{
((ListViewAdapter) finalGlobalAdapter).notifyDataSetChanged();
}
});
}
}
// updating listview
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
mEditText = (EditText) findViewById(R.id.inputSearch);
mEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
// Search
globalQuery=s.toString();
//This method will filter all your categories just calling this method.
filteredList();
} else {
globalQuery="";
//If the text is empty the list all the content of the list adapter
justListAll();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals("")){new DownloadJSON().execute();}
else{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
if (searchString.contains(currentString)) {
//pass the character-sequence instead of currentstring
arrayTemplist.add(arraylist.get(i));
}
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#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("http://ndublog.twomini.com/123.txt.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("url",jsonobject.getString("url"));
map.put("flag", jsonobject.getString("flag"));
// 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
mProgressDialog.dismiss();
}
}
public void justListAll()
{
ListViewAdapter globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
listview.setAdapter(adapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
}
Thank you for asking the question in a good way as per the SO guidelines.
Iam sure this will solve your question.
//First of all declare a global variables
String globalQuery="";
ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
ListViewAdapter globalListAdapter;
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
// Search
globalQuery=s.toString();
//This method will filter all your categories just calling this method.
filteredList();
} else {
globalQuery="";
//If the text is empty the list all the content of the list adapter
justListAll();
}
}
public void justListAll()
{
globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
listview.setAdapter(adapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
public void filteredList()
{
//First of all checks for our globalList is not a null one.
if(globalList!=null)
{
ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
if(!globalQuery.trim().equals(""))
{
boolean isThereAnyThing=false;
for(int i=0;i<globalList.size();i++)
{
//Get the value of globalList that is HashMap indexed at i.
HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
String rank=tempMap.get(MainActivity.RANK);
String country=tempMap.get(MainActivity.COUNTRY);
String population=tempMap.get(MainActivity.POPULATION);
String url=tempMap.get(MainActivity.URL);
String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
{
//If anything matches then it will add to tempList
tempList.add(tempMap);
isThereAnyThing=true;
}
}
//Checks for is there anything matched from the ArrayList with the user type search query
if(isThereAnyThing)
{
//then set the globalAdapter with the new HashMaps tempList
globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
listview.setAdapter(globalAdapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
else
{
//If else set list adapter to null
setListAdapter(null);
}
}
else
{
// Do something when there's no input
if(globalAdapter==null)
{
//If no user inputs then it will list everything in the globalList.
justListAll();
}
else
{
runOnUiThread(new Runnable()
{
public void run()
{
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
});
}
}
// updating listview
}
}
Only a thing you want to do is populate all the JSON parsed values to the global ArrayList globalList.
Hope it answers the whole question with extra packups.
When you delete the character, the text in the EditText view is null therefore it is looking for null and the list displays null. Make sure you perform a null check before searching through your JSON array.
It looks like you just need to change this line:
String currentString = arraylist.get(i).get(MainActivity.RANK);
to
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
do the following change to your edittext watcher... if the edittext.gettext().tostring().equals("") ...then just execute the asynctask
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals(""))
{
new DownloadJSON().execute();
//this will set you the whole json again to your listview
}
else
{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.RANK);
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
}
and in case of COUNTRY..why its behaving diff...it think you have to match the edittext substring with the arraylist
just replace the following code
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
with
if (searchString.contains(currentString)) {
//pass the character-sequence instead of currentstring
arrayTemplist.add(arraylist.get(i));
}
for COUNTRY search...
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals(""))
{
new DownloadJSON().execute();
//this will set you the whole json again to your listview
}
else
{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
if ( searchString .equalsIgnoreCase(currentString .substring(0,searchString .length()-1))) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
}
Related
I am trying to fetch data from MySql server and display it in my listview.
Parser.java
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
String arr[];
ArrayList<String> players=new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parser");
pd.setMessage("Parsing ....Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter=new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1,players);
//ADAPT TO LISTVIEW
lv.setAdapter(adapter);
//LISTENET
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(c,players.get(position), Toast.LENGTH_LONG).show();
//Snackbar.make(view,players.get(position),Snackbar.LENGTH_LONG).show();;
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray ja=new JSONArray(data);
//CREATE JO OBJ TO HOLD A SINGLE ITEM
JSONObject jo=null;
players.clear();
//LOOP THRU ARRAY
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
//RETRIEVE NAME
String name=jo.getString("Name");
//ADD IT TO OUR ARRAYLIST
players.add(name);
jo = ja.getJSONObject(i);
String pposition = jo.getString("Position");
arr[i] = pposition;
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
MainActivity.java
public class MainActivity extends Activity {
String url="http://bookvilla.esy.es/book.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView lv= (ListView) findViewById(R.id.lv);
final Downloader d=new Downloader(this,url,lv);
d.execute();
}
}
I would like to mention one thing that when i try to fetch only "Name" its working perfectly...but when i add these lines :
jo = ja.getJSONObject(i);
String pposition = jo.getString("Position");
arr[i] = pposition;
Exception starts appearing
Error log
Kindly help.
Below is the code which will display the list of name in the list view.
I want to filter the list view based on the input of search textbox.
I have added the addTextChangedListener method for the edittext. But I am facing an error in getFilter() method as "can't resolve". As per the google I found the getFilter() method work on ArrayAdapter. I want to know how can I make getFilter() method work with ListAdapter.
Please can anyone let me know.
package com.smoothbalance.smothbalance;
public class AddedClientList extends CommonDrawer {
EditText searchTextBox;
ListAdapter adapter;
ListView addedlistofclient;
// JSON Nodes
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_FULL_NAME = "full_name";
private static final String TAG_EMAIL = "email";
//JSON array
JSONArray json_data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.activity_added_client_list, null, false);
mDrawerLayout.addView(view, 0);
addedlistofclient = (ListView) findViewById(R.id.listView_Added_Client);
searchTextBox = (EditText) findViewById(R.id.Search_added_clients);
dataList = new ArrayList<HashMap<String, String>>();
if (CommonFunctions.isNetworkAvailable(getBaseContext())) {
params.add(new BasicNameValuePair("", user_id));
new Added_client_list().execute();
} else {
Toast.makeText(getApplicationContext(), "Network Not Available... \n Please check Your Wifi Connection or Mobile Network", Toast.LENGTH_LONG).show();
}
searchTextBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
AddedClientList.this.adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private class Added_client_list extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... param) {
String network_error = null;
String url = getString(R.string.getClientlist) + user_id + "/Clients";
ServiceHandler serviceHandler = new ServiceHandler();
String jsonStr = serviceHandler.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
network_error = jsonStr;
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
// getting json array node
json_data = jsonObject.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < json_data.length(); i++) {
JSONObject c = json_data.getJSONObject(i);
String id = c.getString(TAG_ID);
String full_name = c.getString(TAG_FULL_NAME);
String email = c.getString(TAG_EMAIL);
// tmp hashmap for single data
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_FULL_NAME, full_name);
data.put(TAG_EMAIL, email);
// adding contact to contact list
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return network_error;
}
#Override
protected void onPostExecute(String aVoid) {
adapter = new SimpleAdapter(AddedClientList.this, dataList, R.layout.customelistview, new String[]
{TAG_FULL_NAME, TAG_EMAIL,}, new int[]{R.id.details, R.id.serviceData});
addedlistofclient.setAdapter(adapter);
}
}
As Luksprog mentioned in the comment, ListAdapter is not filterable, you would have either have to create a customAdapter by extending the listadapter and implementing filterable in that object, or use an adapter provided by the sdk that implementals filterable
I am new in Android development, I want to bind a Json array to android AutocompleteTextView in Form (Registration form).
the Json array is showed in below
{"Status":true,"errorType":null,"InstituteList":[{"InstituteID":"1","InstituteName":"Demo Institute"},{"InstituteID":"16","InstituteName":"Sheridan College"},{"InstituteID":"17","InstituteName":"iCent Prosp"},{"InstituteID":"18","InstituteName":"Seneca College"}]}
here the Type Institution Name is the auto completeTextView. The main requirement is that, I can bind the values like in the Json response InstituteName on the front end and When click on the Submit Button it needs to take the InstituteID Object.
Currently I can bind the InstituteName Object to AutocompleteTextView and Working fine.
But the Submit Action was not performing perfectly.
I cant getting the InstituteID in my codes for performing
Here is my code.
Getting response from web service as json array and binding in asyncTask.
#Override
protected void onPostExecute(String res) {
try
{
Log.i("Intitute List",res);
JSONObject responseObject = new JSONObject(res);
String status=responseObject.getString("Status");
ArrayList<String> listInstituteNames = new ArrayList<>();
JSONArray detailsArray = responseObject.getJSONArray("InstituteList");
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i);
listInstituteNames.add(obj.getString("InstituteName"));
}
//Log.i("InstituteName", String.valueOf(listInstituteNames));
myStringArray = listInstituteNames;
AutoCompleteAdapter adapter = new AutoCompleteAdapter(SignUpActivity.this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, listInstituteNames);
autoTextView.setThreshold(1);
autoTextView.setAdapter(adapter);
}
catch (JSONException e1) {
e1.printStackTrace();
}
AutoCompleteAdapter.java
package Adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> fullList;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
public AutoCompleteAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
fullList = (ArrayList<String>) objects;
mOriginalValues = new ArrayList<String>(fullList);
}
#Override
public int getCount() {
return fullList.size();
}
#Override
public String getItem(int position) {
return fullList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
private Object lock;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (lock) {
mOriginalValues = new ArrayList<String>(fullList);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
ArrayList<String> list = new ArrayList<String>(mOriginalValues);
results.values = list;
results.count = list.size();
}
} else {
final String prefixString = prefix.toString().toLowerCase();
ArrayList<String> values = mOriginalValues;
int count = values.size();
ArrayList<String> newValues = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
String item = values.get(i);
if (item.toLowerCase().contains(prefixString)) {
newValues.add(item);
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results.values!=null){
fullList = (ArrayList<String>) results.values;
}else{
fullList = new ArrayList<String>();
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
AutoCompleteTextView Section in XML File..
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/autoCompt"
android:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/instname_field"
android:layout_width="match_parent"
android:hint="Type Institution Name"
android:paddingLeft="10dp"
android:textColor="#fff"
android:background="#b8d1e5"
android:layout_height="40dp"
android:textSize="20dp"
android:ems="10"/>
</LinearLayout>
How can I solve this Issue. Thanks.
You can see #blackBelt comment that is the right way to do that.
But here i am explain you another method which is easy to understand using Hashmap instead of Object class .
HashMap<String, String> map_name_value = new HashMap<String, Stirng>();
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i)
listInstituteNames.add(obj.getString("InstituteName"))
map_name_value.put(obj.getString("InstituteName"),obj.getString("InstituteID"));
}
Then while clicking the item.
Do this:
autoTextView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos,
long id) {
Editable message = autoTextView.getText();
String item_name = message.toString();
String item_id = map_name_value.get(item_name);
//your stuff
}
});
//item_name is name of institute
// item_id is id of institute
I'm a beginner, I'm creating a job search app which shows job infomation as listview where the data is from WAMP server database. I encounter a problem : Cannot resolve method 'getStringArrayList' , when I'm making a search filter for this Listview. Please see line 11 of SearchFilter.java. Could anyone help? thank you very much!
SearchFilter.java
public class SearchFilter extends ListActivity {
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList())); ***<<<<< this line !***
}
private TextWatcher filterTextWatcher = 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) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json_select_all.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info=(HashMap<String, String>)lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
// Phone node is JSON Object
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, infoList,
R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return (super.onCreateOptionsMenu(menu));
}
}
activity_main.xml
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search Jobs"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
getStringArrayList is a method on Bundle (such as savedInstanceState). There's no such method in Activity. Hope that helps.
Currently your infoList is an ArrayList>, something that is harder to pass directly to an activity. So find a way to represent it as an ArrayList, or find a more suitable datatype supported by Intent's putExtra-methods. Here below is a suggested solution using an ArrayList.
Passing the data into the activity with the Intent allows you to get it back in your SearchFilter. In the calling activity put something like this:
Intent i = new Intent(this, SearchFilter.class);
i.putStringArrayListExtra("com.yourpackagename.here.keynamehere", aStringArrayList);
In SearchFilter.java, put something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
Intent startingIntent = getIntent();
ArrayList<String> arrayList = new ArrayList<String>();
if (startingIntent != null) {
arrayList = startingIntent.getStringArrayList("com.yourpackagename.here.keynamehere");
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList));
}
So I have an ArrayList named locationsList. I also have SharedPreferences that hold a city name which was set in the previous activity which i want to add onto my ArrayList. BUT I want to add it with a ">" at the end of it. So for example
SharedPreferences prefs = getActivity().getSharedPreferences("prefs", 0);
locationsList.add(0, prefs.getString("city", "no city") + ">");
However it does not change!!!. the ">" Isn't added. I even tried adding it when i set the text of the textView.
TextView tv...;
tv.setText(locationsList.get(0) + ">");
I dont understand why it cant change. Obviously the array list is holding a reference to the preferences and that cannot change. But I even tried assigning the preferences to a string variable and then iterating it, it doesn't budge. Can anyone help me
Async in activity
class getLocationsUrl extends AsyncTask<String, String, String> {
ArrayList<String> tempList = new ArrayList<String>();
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("city", prefs.getString("city", "durban")));
JSONParser parser = new JSONParser();
JSONObject json = parser.makeHttpRequest(IMAGE_URL + "fetchlocations.php", "POST",
params);
try {
list = json.getJSONArray("posts");
for(int i = 0; i < list.length(); i++) {
JSONObject c = list.getJSONObject(i);
String location = c.getString("location");
tempList.add(location);
Log.d("async trend", trendList.get(0));
}
Log.d("Got list", imageUrl.get(0) + " " + trendList.get(0));
} catch(JSONException je) {
Log.d("json exception", "json exception");
je.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
locationsList = tempList;
locationsFragment.updateAdapter();
feedFragment.updateHeadingAdapter();
}
}
FeedFragment set up in onCreateView
headingPager = (ViewPager) view.findViewById(R.id.headingPager);
headingList = (ArrayList<String>) NightWatch.locationsList.clone();
added = prefs.getString("city", "makaka");
headingList.add(0, added + ">");
headingAdapter = new CustomHeadingPagerAdapter(getChildFragmentManager());
headingPager.setAdapter(headingAdapter);
FeedFragments CustomHeadingAdapter
public class CustomHeadingPagerAdapter extends FragmentPagerAdapter {
public CustomHeadingPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
return HeadingFragment.newInstance(arg0, headingList);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return headingList.size();
}
}
FeedFragment's updateHeadingAdapter() called from the Async
public void updateHeadingAdapter() {
headingList = (ArrayList<String>) NightWatch.locationsList.clone();
headingList.add(0, (prefs.getString("city", "null") + ">"));
headingAdapter = new CustomHeadingPagerAdapter(getChildFragmentManager());
headingPager.setAdapter(headingAdapter);
}
And finally the HeadingFragment that I return in the adapter.
package info.nightowl.nightowl;
import java.util.ArrayList;
import com.example.nightowl.R;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HeadingFragment extends Fragment{
int position;
Typeface font;
ArrayList<String> list;
SharedPreferences prefs;
static HeadingFragment newInstance(int position, ArrayList<String> list) {
final HeadingFragment f = new HeadingFragment();
Bundle args = new Bundle();
args.putInt("position", position);
args.putStringArrayList("list", list);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
position = getArguments().getInt("position");
list = getArguments().getStringArrayList("list");
prefs = getActivity().getSharedPreferences("prefs", 0);
font = Typeface.createFromAsset(getActivity().getAssets(),
"NotCourierSans.ttf");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.heading_viewpage_layout, null);
TextView tv = (TextView) v.findViewById(R.id.headingText);
if(position == 0) tv.setText(">" + list.get(position) + ">");
else tv.setText(list.get(position) + ">");
tv.setTypeface(font);
tv.setTextColor(Color.YELLOW);
tv.setTextSize(30);
return v;
}
}
I got it. Always remember when iterating to a string text vi you set it to be a single line in the xml so...
android:singleLine="true"
Kind of a dumb mistake really