I beginner in android development, getting error in following code. i am calling asyn method for http request.Its giving me java.lang.RuntimeException error occured while executing doInBackground()
private class PostAlert extends AsyncTask<String, Integer, JSONArray>{
private ProgressDialog progressDialog;
#Override
protected JSONArray doInBackground(String... params) {
// TODO Auto-generated method stub
JSONArray menuitemArr = null;
String url=params[0];
System.out.println("fsfsddddf"+params[0]);
ControlDashboard obj = new ControlDashboard();
try{
JSONObject aobj = obj.getJSONFromUrl(url);
JSONObject array = aobj.getJSONObject("alert_list");
menuitemArr = array.getJSONArray("array");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return menuitemArr;
}
#Override
protected void onPostExecute(JSONArray menuitemArr) {
// TODO Auto-generated method stub
super.onPostExecute(menuitemArr);
if (menuitemArr.length() == 0) {
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
//Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
}else{
name = new String[menuitemArr.length()];
alert = new String[menuitemArr.length()];
date = new String[menuitemArr.length()];
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
try {
name[i] = menuitemArr.getJSONObject(i).getString("name").toString();
alert[i] = menuitemArr.getJSONObject(i).getString("message").toString();
date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ListView list = (ListView) findViewById(R.id.listView3);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] {"col1", "col2", "col3"};
int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
for(int i=0; i<name.length; i++)
{
HashMap<String,String> map = new HashMap<String, String>();
map.put("col1", name[i]);
map.put("col2", alert[i]);
map.put("col3", date[i]);
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
list.setAdapter(arrayAdapter);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(Alert.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("please wait...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
//progressDialog.dismiss();
}
}
Error when i run my android application.
12-17 13:22:48.035: W/dalvikvm(1160): threadid=8: thread exiting with uncaught exception (group=0x4001d800)
12-17 13:22:48.045: E/AndroidRuntime(1160): FATAL EXCEPTION: AsyncTask #2
12-17 13:22:48.045: E/AndroidRuntime(1160): java.lang.RuntimeException: An error occured while executing doInBackground()
12-17 13:22:48.045: E/AndroidRuntime(1160): at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
json request class:
public class ControlDashboard extends Activity {
public static DefaultHttpClient httpClient;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
jObj = null;
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
or
ListView list = (ListView) findViewById(R.id.listView3);
here you are trying to access UI elements from Background Thread means from AsyncTask doInBackground which is not possible
solution move all ui related code in onPostExecute for updating ui after doInBackground complete
you can see here how we update UI from onPostExecute after when doInBackground execution complete
EDIT : or just use this PostAlert AsyncTask class :
private class PostAlert extends AsyncTask<String, Integer, JSONArray>{
private ProgressDialog progressDialog;
#Override
protected JSONArray doInBackground(String... params) {
// TODO Auto-generated method stub
JSONArray menuitemArr=null;
String url=params[0];
System.out.println("fsfsddddf"+url);
// System.out.println("fsfsddddfobj"+obj);
try{
JSONObject aobj = obj.getJSONFromUrl(url);
System.out.println("fsfsf"+aobj);
JSONObject array = aobj.getJSONObject("alert_list");
menuitemArr = array.getJSONArray("array");
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return menuitemArr;
}
#Override
protected void onPostExecute(JSONArray menuitemArr) {
// TODO Auto-generated method stub
if (menuitemArr.length() == 0) {
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
//Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
}else{
name = new String[menuitemArr.length()];
System.out.println("name"+name);
alert = new String[menuitemArr.length()];
date = new String[menuitemArr.length()];
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
name[i] = menuitemArr.getJSONObject(i).getString("name").toString();
alert[i] = menuitemArr.getJSONObject(i).getString("message").toString();
date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
}
ListView list = (ListView) findViewById(R.id.listView3);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] {"col1", "col2", "col3"};
int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
for(int i=0; i<name.length; i++)
{
HashMap<String,String> map = new HashMap<String, String>();
map.put("col1", name[i]);
map.put("col2", alert[i]);
map.put("col3", date[i]);
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
list.setAdapter(arrayAdapter);
}
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(Alert.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("please wait...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
System.out.println("fsgsgsg");
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressDialog.setProgress(values[0]);
}
}
}
http://developer.android.com/reference/android/os/AsyncTask.html
You are setting ListAdapter in Background which should not be done as it is UI thread task. Change your entire code in doInBackground() to onPostExecute() except for getJsonFromUrl(url). you can return the jsonobject from doInBackground() which you can get in onPostExecute() as result parameter. Still you get that runtime error in onPostExecute() too then you just right this line listview.setAdapter() in
runOnUIThread(new Runnable(){
public void run()
{
}
});
I hope its clear and it will work for you.
Related
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 created Application on parsing XML data.I want to show loading progress dialog.
I created two class on ListActivity(MainClass) and other is Download(Which execute in background using Asyntask).
I using Following code.
public class ListActivity extends Activity implements AsyncResponse {
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
String url = "http://www.moneycontrol.com/rss/MCtopnews.xml";
Download download = new Download();
download.delegate = this;
download.execute(url);
}
/*
* After background task of download and parsing xml ArrayList received from
* background task and send it to arrayAdapterzz
*/
#Override
public void processFinish(ArrayList<NewsItem> listArrayList) {
ListView newsListView;
newsListView = (ListView) findViewById(R.id.listView1);
NewsListAdapter newsListAdapter = new NewsListAdapter(
ListActivity.this, 0, listArrayList);
newsListView.setAdapter(newsListAdapter);
}
}
public class Download extends AsyncTask<String, Integer, ArrayList<NewsItem>> {
public AsyncResponse delegate;
private InputStream mInStream;
private ArrayList<NewsItem> mNewsList;
ListActivity la = new ListActivity();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
la.progressDialog.setMessage("Loading");
la.progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
la.progressDialog.setProgress(0);
la.progressDialog.show();
}
#Override
protected ArrayList<NewsItem> doInBackground(String... params) {
String urlstr = params[0];
mInStream = downloadFromlUrl(urlstr);
ParseXml parse = new ParseXml();
try {
mNewsList = parse.parseNewsFeed(mInStream);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mNewsList;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(ArrayList<NewsItem> newsList) {
// send back parsed data to ListActivity
delegate.processFinish(newsList);
}
private InputStream downloadFromlUrl(String urlstr) {
try {
URL url = new URL(urlstr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(10 * 1000);
connection.setRequestMethod("GET");
connection.connect();
int response = connection.getResponseCode();
Log.d("debug", "The response is: " + response);
mInStream = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mInStream;
}
}
I am getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rss/com.parse.ui.ListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException
at com.parse.net.Download.onPreExecute(Download.java:33)
at android.os.AsyncTask.execute(AsyncTask.java:391)
at com.parse.ui.ListActivity.onCreate(ListActivity.java:30)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) ... 11 more 08-05 06:08:02.113: I/Process(1852): Sending signal. PID: 1852 SIG: 9
It may not be the answer but a concept. You don't need to add ProgressDialog in ListActivity.
public ProgressDialog progressDialog;
and no need to instantiate it here.
Because you want to show the progress of the AsycTask Do it like this
public class ArticleTask extends AsyncTask<String, Void, JSONObject> {
Activity context;
ListView list_of_article;
public ProgressDialog progressDialog;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
public ArticleTask(Activity coontext, ListView listview) {
this.context = coontext;
this.list_of_article = listview;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(context,
"", "");
}
#Override
protected JSONObject doInBackground(String... params)
{
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]); //url
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", array.getJSONObject(x).getString("title"));
map.put("previewimage", array.getJSONObject(x).getString("previewimage"));
map.put("publishdate", array.getJSONObject(x).getString("publishdate"));
map.put("pagetext", array.getJSONObject(x).getString("pagetext"));
map.put("total_comments", array.getJSONObject(x).getString("total_comments"));
map.put("viewcount", array.getJSONObject(x).getString("viewcount"));
map.put("associatedthreadid", array.getJSONObject(x).getString("associatedthreadid"));
list.add(map);
}
ArticleAdapter adapter = new ArticleAdapter(context, list);
list_of_article.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
Remove ProgressDialog from ListActivity and show it on PreExecute and remove/dismiss it on PostExecute.
Try this in your preExecute() method
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(this_context, "Loading",
"Please wait for a moment...");
}
I'm trying to retrieve data from mysql using asynctask. But I got this
" Type mismatch: cannot convert from AsyncTask
to String"
Though the return from the asynctask process is already string
Here's my codes
public void tampilkanPenyakit() {
try {
String nama = URLEncoder.encode(username, "utf-8");
urltampil += "?" + "&nama=" + nama;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xResult = getRequestTampil(urltampil);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
class ProsesTampil extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String sret = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
try{
HttpResponse response = client.execute(request);
sret = EditPenyakit.request(response);
}catch(Exception ex){
}
return sret;
// TODO Auto-generated method stub
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
public String getRequestTampil(String UrlTampil){
String sret="";
sret= new ProsesTampil().execute(UrlTampil);
return sret;
}
private void parse() throws Exception {
//jObject = new JSONObject(xResult);
jObject = new JSONObject(xResult);
String sret = "";
JSONArray menuitemArray = jObject.getJSONArray("food");
cb_menu1 = (CheckBox) findViewById(R.id.cb_menu1);
cb_menu2 = (CheckBox) findViewById(R.id.cb_menu2);
cb_menu3 = (CheckBox) findViewById(R.id.cb_menu3);
for (int i = 0; i < menuitemArray.length(); i++) {
sret =menuitemArray.getJSONObject(i).getString(
"penyakit").toString();
System.out.println(sret);
if (sret.equals("1")){
cb_menu1.setChecked(true);
}
else if (sret.equals("2")){
cb_menu2.setChecked(true);
}
}
}
Any help would be appreciated. thanks
The AsyncTask execute() method return the Asyntask itself, you cannot convert it to String.
You need to handle the result in the onPostExecute() method.
Other option could be use the AsynTask get method :
sret= new ProsesTampil().execute(UrlTampil).get();
Take in account the doc:
Waits if necessary for the computation to complete, and then retrieves its result.
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();
}
});
what is the correct way of fixing this problem?
This is my activity code
public class MainActivity extends Activity {
JSONParser jsonParser = new JSONParser();
ItemsAdapter adapter;
ListView list;
ListView list2;
HashMap<String, String> map;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://www.*************************************************";
String img_test_url = "http://*************************************************";
ImageView imageView;
String bName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
list2 = (ListView) findViewById(R.id.listView2);
accessWebService();
}
// Async Task to access the web
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar = new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
getImageData();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
LoadData task = new LoadData();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void getImageData() {
map = new HashMap<String, String>();
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
bName = jsonChildNode.optString("id");
//map.put(bName, test1);
listData.add(new Pair<String,String>(bName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
String id = item.first;
Log.d("Bank Name", id);
List<String> cards_name = new ArrayList<String>();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Bank_Name", id));
Log.d("request!", "starting");
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
Log.d("Credite Cards", jsonResponse.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String card = jsonChildNode.optString("name");
Log.d("Card_name", card);
cards_name.add(card);
}
ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
list2.setAdapter(adapter2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
I guess this where you go wrong
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
In onPostExecute you have
getImageData();
In getImageData() you have listview item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
// network operation on main thread
This getting json object must be doen in a background thread
Also you cannot update ui from background thread
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Must be removed
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
//this should be in a separate non ui thread
For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code
Check the following link.
http://loopj.com/android-async-http/
download the jar file and paste in the lib folder and then just write few lines like for simple get methods
});
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});