I load dynamically the string of my autocomplete with JSON objects, but the list appears only in the next character; How can I make my list appear exactly after the loading?
This process is called from a onTextChanged event. I tried to force display with showDropDown() but didn't work!!!
Any help?
public class HttpConnectionApiActivity extends Activity implements HttpListner, TextWatcher {
.....
AutoCompleteTextView from_txt;
List<String> country_List;
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
from_txt = (AutoCompleteTextView) findViewById(R.id.from_txt);
//from_txt.setThreshold(1);
prepareCountryList();
from_txt.addTextChangedListener( this);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,country_List);
from_txt.setAdapter(adapter);
}
....
public void notifyHTTPRespons(final HttpHandler http) {
public void run() {
String result = http.getResponse();
try {
adapter.clear();
for (int i = 0; i < results_Array.length(); i++) {
JSONObject row = results_Array.getJSONObject(i);
String name=row.getString("name");
adapter.add(name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I could display the dropdown list by adding these 2 lines :
It's very simple hack by resetting text when you get updated data.
try {
adapter.clear();
for (int i = 0; i < results_Array.length(); i++) {
JSONObject row = results_Array.getJSONObject(i);
String name=row.getString("name");
adapter.add(name);
}
//____________________
adapter.notifyDataSetChanged();
from_txt.setText(from_txt.getText());
//____________________
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
Hi I am a beginner for android and in my app I have to show SlidingPaneLayout at right side.
So far everything is OK.
But when I tap on SlidingPaneLayout of any row I want to reload Listview for this I wrote below code.
But here Listview is reloading by default, but when I tap on SlidingPaneLayout it's not reloading.
Below lines are not executing when I call getAllTips() method from MainActivity.
if (friendArrayList.size() != 0) {
Log.d("=======>" ," data Available");
˚
adapter.notifyDataSetChanged();
}else{
Log.d("=======>" ,"No data Available");
}
ListViewFragment:-
public class ListViewFragment extends Fragment implements AsyncTaskClass.BackGroundServiceCall {
private ArrayList<MyTripBean> friendArrayList;
ListViewAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.listview_layout,container,false);
ListView listView = (ListView)view.findViewById(R.id.list_item);
//set ListView header:-
inflater = getActivity().getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview,listView,false);
listView.addHeaderView(header);
//adapter = new ListViewAdapter(getActivity(), R.layout.item_listview, friendArrayList);
friendArrayList = new ArrayList<MyTripBean>();
adapter = new ListViewAdapter(getActivity(),
R.layout.list_item, friendArrayList);
listView.setAdapter(adapter);
getAllTips(getActivity(),9); //Getting friendArrayList data from Services
return view;
}
// get all trips of the User
public void getAllTips(Activity activity,int tripstatus) {
try {
JSONObject json = new JSONObject();
json.put("TripStatus", tripstatus);
json.put("medicaidId", "104584743999");
if (CommonUtilities.isNetWorkStateAvailble(activity)) {
AsyncTaskClass task = new AsyncTaskClass(this, activity,
json);
task.execute(ServiceUrl.GET_ALL_TRIPS, "1",
"Token");
} else {
Log.d("==========>", "There is Network Error");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void doPostExecute(StatusObject statusObject) {
// TODO Auto-generated method stub
if (statusObject != null) {
if (statusObject.getResponseCode() == 401) {
Log.d("==========>", "Session Has been Expired");
} else if (statusObject.getResponseCode() == 200) {
handleResponseData(statusObject.getMessage());
} else {
Log.d("==========>", "Server not responding. Please try again later.");
}
} else {
Log.d("==========>", "Server not responding. Please try again later.");
}
}
// handle the response
public void handleResponseData(String result) {
Log.d("Final Json==========>", result);
try {
Object json = new JSONTokener(result).nextValue();
if (json instanceof JSONObject) {
// you have an object
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.has("Error")) {
if (jsonObject.getString("Error").equalsIgnoreCase("true")) {
if (jsonObject.has("message")) {
Log.d("==========>", "there is erorr mesage coming from server");
}
}
}
} else if (json instanceof JSONArray) {
// you have an array
handleTripsResponse(result);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// handle the json array data
public void handleTripsResponse(String result) {
try {
Type type = new TypeToken<List<MyTripBean>>() {
}.getType();
ArrayList<MyTripBean> newListData = new Gson().fromJson(result, type);
friendArrayList.addAll(newListData);
if (friendArrayList.size() != 0) {
Log.d("=======>" ," data Available");
adapter.notifyDataSetChanged();
}else{
Log.d("=======>" ,"No data Available");
}
} catch (Throwable throwable) {
}
}
}
MainActivity:-
public class MainActivity extends AppCompatActivity {
SlidingPaneLayout mSlidingPanel;
ListView mMenuList;
String [] MenuTitles = new String[]{"First Item","Second Item","Third Item","Fourth Item"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListViewFragment fragment1 = new ListViewFragment();
fragment1.getAllTips(MainActivity.this,8);
}
});
}
The code looks fine. OnItemClickListeners looks fine for the listview and will work correctly.
I doubt if you are getting exception in method handleTripsResponse(). please try printing log in the catch block of this method. then you will come to know the exception and how to resolve it.
Also in your MainActivity, in onItemClickListener, do not create a new instance of the ListViewFragment, instead use the instance of fragment which you attached in fragment transaction.
ListViewFragment fragment1 = new ListViewFragment();
fragment1.getAllTips(MainActivity.this,8);
I have created an adapter and i used Google Places API to show address. I call notifyDataSetChanged(); for update list. When i typed in TextView the list is not change.
Activity
public class SelectAddressActivity extends Activity implements SelectAddressAdapter.OnClickInAdapter {
ArrayList<AddressList> addressList;
SelectAddressAdapter adapter;
EditText addresseEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_address);
final ListView addressListView = (ListView) findViewById(R.id.addressListView);
addresseEditText = (EditText) findViewById(R.id.addressEditText);
//Adapter
adapter = new SelectAddressAdapter(this, android.R.layout.simple_list_item_1, addressList);
addressListView.setAdapter(adapter);
addresseEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(final Editable input) {
scheduler= Executors.newScheduledThreadPool(1);
scheduler.schedule(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
GoogleAPIRequestHandler handler = new GoogleAPIRequestHandler();
String date= handler.execute(input).get();
addressList = new ArrayList<AddressList>();
JSONObject jsonObj = new JSONObject(date);
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
for (int i = 0; i < predsJsonArray.length(); i++) {
AddressList a = new AddressList();
String addressJson = predsJsonArray.getJSONObject(i).toString();
a.Deserialize(addressJson);
addressList.add(a);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();;
}
});
}
}, 300, TimeUnit.MILLISECONDS);
}
});
}
You are not setting the updated address list in the adapter. it still has old data so when you call notifyDataSetChanged() method it does not have any effect.
I want to update my listview during every new item add to my arraylist during progress dialog showing this is my code
public class Load extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(SearchList.this);
progress.setMessage("loading....");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
// do tracks loading process here, don't update UI directly here
// because there is different mechanism for it
//FlowableBookViewer.webview.loadUrl("javascript:(function(){var txt = window.getSelection();window.name= txt;window.cpjs.sendToAndroid(window.name);})()");
for (int i = 0; i < Globals.currenHtmlList.size(); i++) {
try {
String pageText = FunctionsClass
.readTextFromHtml(Globals.currenHtmlList.get(i));
if (pageText.toLowerCase().contains(
Globals.SelectedText.toLowerCase())) {
String pagename = new File(
Globals.currenHtmlList.get(i)).getName();
SearchItem sitem = new SearchItem();
sitem.setTargetList(Globals.currenHtmlList.get(i));
sitem.setPageNumber(i);
if (pagename.endsWith("html")) {
pagename = pagename.substring(0,
pagename.length() - 5);
} else if (pagename.endsWith("htm")) {
pagename = pagename.substring(0,
pagename.length() - 4);
} else if (pagename.endsWith("xhtml")) {
pagename = pagename.substring(0,
pagename.length() - 6);
}
sitem.setTitleList("Page " + pagename);
founded.add(sitem);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
m_adapter = new OrderAdapter(SearchList.this, R.layout.itemview,
founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}
}
in this code the listview items appears after the complete of the for loop which add all the items of sitem object to founded list i want to update listview at every item added to founded .
many thanks
1) Create the adapter before you call the AsyncTask
Move this to your activity/fragment onCreate method:
m_adapter = new OrderAdapter(SearchList.this, R.layout.itemview,
founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
2) After you add an item in your ArrayList call the onProgressUpdate from the AsyncTask
In your doInBackground method add:
founded.add(sitem);
publishProgress();
3) In the onProgressUpdate method call the notifyDatasetChanged method from your adapter
#Override
protected void onProgressUpdate(Void... v) {
super.onProgressUpdate(v);
m_adapter.notifyDataSetChanged();
}
You can read more about notifyDataSetChanged here.
This is a follow up question from my question thread exiting error in android
I created an async task but the values do not show up in the list view....
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{
// TODO Auto-generated method stub
Toast.makeText(this, "u clicked " + listItems.get(position) ,Toast.LENGTH_LONG).show();
}
public void getInfo(){
DownloadInfo task = new DownloadInfo();
task.execute(new String[] { "http://www.vogella.de" });
}
private class DownloadInfo extends AsyncTask<String, Void , ArrayList<String>>{
#Override
protected ArrayList<String> doInBackground(String ... strings) {
ArrayList<String> listItems1;
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems1 = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"URL"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
if ( driver.getString("DATABASE ERROR").equals("False")){
int length = Integer.parseInt( driver.getString("length"));
Log.i(TAG,"length is " + length);
for( int i =0 ; i< length ; i++){
String info = driver.getString(Integer.toString(i));
String[] array = info.split(",");
Log.i(TAG,"array is " + Arrays.toString(array));
Log.i(TAG,"Date "+ array.length);
Log.i(TAG,"DONE WITH THE LOOP");
//listInfo.add(item);
Log.i(TAG,"Date is"+array[0]);
listItems1.add(array[0]);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems1.add("No driver rides created");
}
return listItems1;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.notifyDataSetChanged();
}
}
}
The problem is that the values in the adapter do not get modified...
You initialize your adapter with a empty listItems, after your fill your listItems in AsyncTask. onPostExecute(), your adapter is not get updated, try this:
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.addAll(ListItems);
adapter.notifyDataSetChanged();
}
Hope that help.
listItems = result; won't work, you need to use :
listItems.clear();
listItems.addAll(result);
If you create another list, your adapter won't know it, because it keeps a reference to the old list (which remains the same).
I never got this working in a straightforward manner. Sorry if I'm being a little vague. I'll try to elaborate on what I'm trying to do. I am trying to build a listview that grabs its data from a webservice. Once I initialize a listview, I want to keep polling the webserver periodically and update the contents of the listview. For this I am doing something like this:
public class SampleAutoUpdateList extends Activity {
//Autoupdate handler
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
try {
Log.i("UPDATE", "Handler called");
searchAdapter = getFeed(URL);
searchAdapter.notifyDataSetChanged();
handler.postDelayed(this, Configuration.REFRESH_INTERVAL);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linearmode);
this.context = this;
searchAdapter = getFeed(URL);
LinearLayout l2 = (LinearLayout) findViewById(R.id.secondaryLayout);
ListView list = new ListView(context);
l2.addView(list);
// display UI
UpdateDisplay(list);
updater.run();
}
private SearchAdapter getFeed(String URL) {
try
{
SearchHandler handler = new SearchHandler();
URL url = new URL(URL);
String data = convertStreamToString(url.openStream());
data = data.substring(data.indexOf('['), data.length()-1);
handler.parseJSON(data);
return handler.getFeed();
}
catch (Exception ee)
{
// if we have a problem, simply return null
Log.e("getFeed", ee.getMessage());
return null;
}
}
private void UpdateDisplay(View searchView) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
searchList = (ListView) searchView;
myProgressDialog = ProgressDialog.show(this,
"Please wait...", "Loading search....", true);
new Thread() {
public void run() {
try{
Thread.sleep(2000);
} catch (Exception e) { }
runOnUiThread(new Runnable() {
#Override
public void run() {
if (searchAdapter == null)
{
Log.e("ERROR", "No Feed Available");
return;
}
searchAdapter.setContext(context);
searchList.setAdapter(searchAdapter);
searchList.setSelection(0);
}
});
// Dismiss the Dialog
myProgressDialog.dismiss();
}
}.start();
}
}
And the SearchHandler class is simple:
public class SearchHandler extends DefaultHandler {
SearchAdapter _adapter;
SearchItem _item;
public SearchHandler()
{
}
public SearchAdapter getFeed()
{
return _adapter;
}
public void parseJSON(String data) {
// TODO Auto-generated method stub
_adapter = new SearchAdapter();
JSONArray parseArray;
try {
parseArray = new JSONArray(data);
for (int i=0; i < parseArray.length(); i++) {
SearchItem item = new SearchItem();
JSONObject jsonUser = parseArray.getJSONObject(i);
item.set_from(jsonUser.getString ("from"));
item.set_msg(jsonUser.getString("msg"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
No matter what I do, the handler gets called and the new items are fetched, but the list is never refreshed... Any ideas on what could be going wrong?
Well, it is a little bit difficult to follow your code, since you only have a fragment of it, and few of the really relevant bits. For example, based on your available code, your list should be forever empty, since you never associate the searchAdapter with a ListView...at least in the code you have shown.
That being said, the following lines seem particularly odd:
searchAdapter = getFeed(URL);
searchAdapter.notifyDataSetChanged();
I am going to assume that getFeed() (not shown) creates a new ListAdapter of some sort. If getFeed() is creating a new ListAdapter, there is no need to call notifyDataSetChanged() on it, as its data set hasn't changed -- it's brand new. Moreover, unless you are associating this new ListAdapter to your ListView, the new ListAdapter will have no effect.
If I'm barking up the wrong tree, consider adding lines to your sample showing the implementation of getFeed() and where you are using searchAdapter.