I try to update the autocomplete textview data from the web service based text typed in the textbox. It's working fine but i put the progressbar at the time of web service call because it will take some time in this case autocomplete text view is not showing the drop down menu. I guess autocomplete textview is dissmissed at the time of progressbar dissmissed. How should we put the progress bar in this case.
Code
class GetFundNames extends AsyncTask {
ProgressDialog progress = new ProgressDialog(BasicAutoText.this);
#Override
protected void onPreExecute() {
Log.d("TAG", "onPreExecute()");
progress.setMessage("Please wait...");
progress.setCanceledOnTouchOutside(false);
progress.show();
}
#Override
// three dots is java for an array of strings
protected String doInBackground(Void... args) {
try {
response = getNames(strKeyword);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
;
return response;
}
// then our post
#Override
protected void onPostExecute(String response) {
if(progress.isShowing())
{
progress.dismiss();
}
if (ETF_Constants.registerResponsevalue == 200) {
JSONArray arObjects;
try {
arObjects = new JSONArray(response);
arProducts = new ArrayList<ProductData>();
arProducts.clear();
for (int i = 0; i < arObjects.length(); i++) {
JSONObject jOb = arObjects.getJSONObject(i);
ProductData pd = new ProductData();
int fundId = jOb.getInt("fundId");
String con = "" + fundId;
String fundName = jOb.getString("fundName");
String priceAndDate = jOb.getString("priceAndDate");
String recentGain = jOb.getString("recentGain");
String recentGrowth = jOb.getString("recentGrowth");
String tickerName = jOb.getString("tickerName");
pd.fundId = con;
pd.fundName = fundName;
pd.priceAndDate = priceAndDate;
pd.recentGain = recentGain;
pd.recentGrowth = recentGrowth;
pd.tickerName = tickerName;
arProducts.add(pd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// autocomplete
adapter = new ArrayAdapter<String>(BasicAutoText.this,
R.layout.advancelist);
adapter.setNotifyOnChange(true);
AUTO_View.setAdapter(adapter);
System.out.println("adapter" + adapter);
for (int i = 0; i < arProducts.size(); i++) {
adapter.add(arProducts.get(i).fundName);
System.out.println("Fund Name:"
+ arProducts.get(i).fundName);
}
System.out.println("arProducts count:" + arProducts.size());
System.out.println("adapter count:" + adapter.getCount());
adapter.notifyDataSetChanged();
}
}
}
Related
In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}
I have a dialog fragment which consists of an AsyncTask class. I am able to show a progress bar inside the dialogfragment. But unable to stop it after some time. Is there any way?
class GetStatsFromUrl extends AsyncTask<String, String, String> {
//ProgressDialogFragment pf;
ProgressBar p = null;
String info, status;
JSONObject json, json1, json2;
/*String totalquestions, notanswered,
correctanswered, wronganswered;*/
String totalquestions, notanswered,
correctanswered, wronganswered;
#SuppressLint("InlinedApi")
#Override
protected void onPreExecute() {
super.onPreExecute();
//p = new ProgressDialog(getActivity());
//p.setMessage("Loading..");
//p.setIndeterminate(true);
// p.setCancelable(false);
//p.show();
p=new ProgressBar(getActivity());
// p.setVisibility(View.VISIBLE);
//p = (ProgressBar) rootView.findViewById(R.id.loading_spinner);
//p.setVisibility(View.VISIBLE);
// p.setMax(3000 -1);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// try {
String url1 = "http://smarteach.com/questions/questions.svc/Learner_Qbank_Stats_Today/val1="
+ learnerid
+ "/val2="
+ courseid
+ "/val3="
+ session_id + "";
System.out.println("Stats from URL : " + url1);
ServiceHandler sh = new ServiceHandler();
jsonstring = sh.makeServiceCall(url1, ServiceHandler.GET);
System.out.println("Response: " + jsonstring);
if (jsonstring != null && jsonstring.length() > 0) {
try {
JSONObject questionsObject = new JSONObject(jsonstring);
JSONArray questionsArray = questionsObject
.getJSONArray("Table");
if (questionsArray != null && questionsArray.length() > 0) {
for (int i = 0; i < questionsArray.length(); i++) {
JSONObject innerQuestionObject = (JSONObject) questionsArray
.get(i);
String count = innerQuestionObject.getString("Count");
String result = innerQuestionObject.getString("Result");
if (result.equalsIgnoreCase("R")) {
correctanswered = count;
} else if (result.equalsIgnoreCase("Total Questions")) {
totalquestions = count;
} else if(result.equalsIgnoreCase("W")){
// notanswered = count;
wronganswered = count;
}
/* if(result.equalsIgnoreCase("W")){
wronganswered = count;
}*/
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getActivity(), "Please try after some time",
Toast.LENGTH_LONG).show();
}
return url1;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//p.dismiss();
// TODO Auto-generated method stub
System.out.println("In onpostexecute status");
// p.setVisibility(View.GONE);
tvbookmarkcount.setText(totalquestions);
//tvquesunattempted.setText(notanswered);
tvcorrectanswered.setText(correctanswered);
tvwronganswered.setText(wronganswered);
}
}
try below code:-
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
p.dismiss();
}
you must call dismiss when your task is complete (onPostExecute).
AutoCompleteTextView doesn't show any suggestions but data is filled in the adapter
Here is my block of CODE
public class AUTOSuggestion extends AsyncTask<String, String, String> {
String TITLE, id,level;
String response = " ";
ProgressDialog dialogProgress = new ProgressDialog(Home.this);
String tex;
public AUTOSuggestion(String text) {
// TODO Auto-generated constructor stub
tex=text;
}
protected void onPreExecute() {
dialogProgress.setCancelable(true);
dialogProgress.setMessage("Please wait..");
dialogProgress.setIndeterminate(false);
dialogProgress.show();
}
#Override
protected String doInBackground(String... params) {
try {
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("search", tex));
/* param.add(new BasicNameValuePair("catId", id));
param.add(new BasicNameValuePair("level", level));*/
response = CustomHttpClient.executeHttpPost(AUTOSUGGESTION_URL, param);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String response)
{
if (response != "" || response != null) {
try {
ArrayList<String>sug_list=new ArrayList<String>();
JSONObject Obj = new JSONObject(response);
//String status = Obj.getString("TAG_STATUS");
JSONArray jarr=Obj.getJSONArray("0");
for(int i=0;i < jarr.length(); i++){
JSONObject p = (JSONObject) jarr.get(i);
String words = p.getString("title");
sug_list.add(words);
}
item = sug_list.toArray(new String[sug_list.size()]);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e + "", Toast.LENGTH_LONG).show();
finish();
}
}
try {
dialogProgress.dismiss();
} catch (Exception e) {
e.fillInStackTrace();
}
autocomplete = (AutoCompleteTextView) findViewById(R.id.autocomplete);
//Toast.makeText(getBaseContext(), item.toString(), Toast.LENGTH_LONG).show();
adapter = new ArrayAdapter<String>(Home.this,android.R.layout.simple_dropdown_item_1line, item);
// Create adapter
//adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, item);
autocomplete.setThreshold(1);
autocomplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
While debugging it is showing the words
GUYS help me please :'(
As suggested by other guys here this is the changes i have done
MODIFIED CODE
public class AUTOSuggestion extends AsyncTask<String, String, String> {
String TITLE, id,level;
String response = " ";
ProgressDialog dialogProgress = new ProgressDialog(Home.this);
String tex;
public AUTOSuggestion(String text) {
// TODO Auto-generated constructor stub
tex=text;
}
protected void onPreExecute() {
dialogProgress.setCancelable(true);
dialogProgress.setMessage("Please wait..");
dialogProgress.setIndeterminate(false);
dialogProgress.show();
}
#Override
protected String doInBackground(String... params) {
try {
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("search", tex));
response = CustomHttpClient.executeHttpPost(AUTOSUGGESTION_URL, param);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String response)
{
if (response != "" || response != null) {
try {
JSONObject Obj = new JSONObject(response);
//String status = Obj.getString("TAG_STATUS");
JSONArray jarr=Obj.getJSONArray("0");
for(int i=0;i < jarr.length(); i++){
JSONObject p = (JSONObject) jarr.get(i);
String words = p.getString("title");
sug_list.add(words);
}
item = sug_list.toArray(new String[sug_list.size()]);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e + "", Toast.LENGTH_LONG).show();
finish();
}
}
try {
dialogProgress.dismiss();
} catch (Exception e) {
e.fillInStackTrace();
}
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,sug_list);
autocomplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(),sug_list+"",Toast.LENGTH_LONG).show();
}
}
Here is the item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#eaeaea"
android:padding="10dp"
android:textColor="#000"
android:textSize="16sp" >
</TextView>
After spending 6 hours I come to know that I have to add one line
autocomplete.showDropDown();
in onpost of async
check this page
you may need to update the UI.
runOnUiThread(new Runnable(){
public void run(){
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
I use asynctask to show data from json but asynctask show loading never dies, no error but loading and loading this code doInBackground function
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// check for login response
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
//DatabaseHandler db = new DatabaseHandler(
// activity.getApplicationContext());
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL+id_user);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// Getting Array of Following
user = json.getJSONArray(KEY_USER);
// looping through All Following
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
// Storing each json item in variable
nama = c.getString(KEY_NAMA);
instansi = c.getString(KEY_INSTANSI);
status = c.getString(KEY_STATUS);
responseCode = 1;
}
} else{
responseCode = 0;
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
if (responseCode == 1) {
headerNama = (TextView)activity.findViewById(R.id.headerNama);
headerInstansi = (TextView)activity.findViewById(R.id.headerInstansi);
buttonStatus = (Button)activity.findViewById(R.id.buttonStatus);
headerNama.setText(nama);
headerInstansi.setText(instansi);
buttonStatus.setText(status);
}else {
progressDialog.dismiss();
activity.showDashboardError(responseCode);
}
}
i think no probleme in doinbackground, please help thanks
You should dismiss your dialog like:
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}