I have a php/mysql query working that looks up the VIN, if the VIN is in the database it returns "VIN already exists" Where did I screw up in this: Error report say Fatal Exception : AsyncTask #2 (I have code that actually works above this, problem started when I tried to rewrite this to run the php checkVin before launching the Sell page)
11-21 16:34:43.736: E/AndroidRuntime(725): FATAL EXCEPTION: AsyncTask #2
11-21 16:34:43.736: E/AndroidRuntime(725): java.lang.RuntimeException: An error occured while executing doInBackground()
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.lang.Thread.run(Thread.java:856)
11-21 16:34:43.736: E/AndroidRuntime(725): Caused by: java.lang.IllegalArgumentException: Host name may not be null
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:626)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.getServerResopnse(Scan.java:272)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.access$1(Scan.java:260)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:240)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:1)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-21 16:34:43.736: E/AndroidRuntime(725): ... 5 more
private void addSellButtonListener() {
Button sell = (Button) findViewById(R.id.sell_button);
sell.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendDatatoServer();
}
});
}
private String formatDataAsJASON() {
JSONObject root = new JSONObject();
try {
root.put("User", userId.getText().toString());
root.put("Pword", userPass.getText().toString());
root.put("VIN", VINID.getText().toString());
return root.toString();
} catch (JSONException e) {
Log.d("JWP", "Can't format JSON");
}
return null;
}
private void sendDatatoServer() {
final String json = formatDataAsJASON();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
return getServerResopnse(json);
}
#Override
protected void onPostExecute(String result) {
if (result == "VIN already exists") {
Toast.makeText(Scan.this,
getString(R.string.vin_exists), Toast.LENGTH_LONG)
.show();
final Intent i = new Intent(Scan.this, Scan.class);
startActivity(i);
} else {
StartSell();
}
}
}.execute();
}
private String getServerResopnse(String json) {
HttpPost post = new HttpPost("http://" + serverIp.getText().toString()
+ "/chekVIN.php");
try {
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
return response;
} catch (UnsupportedEncodingException e) {
Log.d("JWP", e.toString());
} catch (ClientProtocolException e) {
Log.d("JWP", e.toString());
} catch (IOException e) {
Log.d("JWP", e.toString());
}
return null;
}
private void StartSell() {
final Intent i = new Intent(Scan.this, Sell.class);
EditText editText = (EditText) findViewById(R.id.VIN);
String text = editText.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.Make);
String text2 = editText2.getText().toString();
EditText editText3 = (EditText) findViewById(R.id.Model);
String text3 = editText3.getText().toString();
EditText editText4 = (EditText) findViewById(R.id.Color);
String text4 = editText4.getText().toString();
EditText editText5 = (EditText) findViewById(R.id.Year);
String text5 = editText5.getText().toString();
try {
FileOutputStream fos = openFileOutput(VinHolder,
Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
FileOutputStream fos2 = openFileOutput(MakeHolder,
Context.MODE_PRIVATE);
fos2.write(text2.getBytes());
fos2.close();
FileOutputStream fos3 = openFileOutput(ModelHolder,
Context.MODE_PRIVATE);
fos3.write(text3.getBytes());
fos3.close();
FileOutputStream fos4 = openFileOutput(ColorHolder,
Context.MODE_PRIVATE);
fos4.write(text4.getBytes());
fos4.close();
FileOutputStream fos5 = openFileOutput(YearHolder,
Context.MODE_PRIVATE);
fos5.write(text5.getBytes());
fos5.close();
}
catch (Exception e) {
Log.d("DEBUGTAG", "File Not Saved" + text);
e.printStackTrace();
}
startActivity(i);
}
Because I use a Text file from another page of the app to hold a manually entered ip address, I needed to carry that info over so that the the HttpPost("http://" +serverIp.getText().toString() + "chechvin.php"); would actually have the ip address in it.
After adding:
public static final String SERVERIP= "sinfo.txt";
everything worked just fine.
Related
I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasdasdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}
I got this error whenever I change my URL to my online hosting, but if I change to 10.0.2.2 everything seems fine and running.
LogCat
02-01 23:02:18.302 17643-18052/com.example.jithea.testlogin E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0x40d8d9a8)
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: uncaught exception occurred
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ java.lang.RuntimeException: An error occured while executing doInBackground()
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ Caused by: java.lang.NullPointerException
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ ... 4 more
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: calling UncaughtExceptionHandler
02-01 23:02:18.315 17643-18052/com.example.jithea.testlogin E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.371 17643-17659/com.example.jithea.testlogin I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x528dc150) fps:43.08, dur:1044.57, max:73.51, min:6.02
And here's my NewsActivity.java
public class NewsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParserNews jParser = new JSONParserNews();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://agustiniancampusevents.site40.net/newsDB/get_all_news.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_PID = "pid";
private static final String TAG_NEWSTITLE = "newstitle";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_NEWS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String newstitle = c.getString(TAG_NEWSTITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NEWSTITLE, newstitle);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NewsActivity.this, productsList,
R.layout.news_list_item, new String[]{TAG_PID,
TAG_NEWSTITLE},
new int[]{R.id.pid, R.id.newstitle});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I have the following situation:
private void startConnection() {
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("email","email#example.com");
String URL = "192.168.1.2/test.php";
Db_connection db = new Db_connection(hm,URL,context);
db.startTest();
}
public class Db_connection {
private HashMap<String, String> params;
private String URL;
private ConnectionController CC;
private ToolTip tt;
private Context con;
private ProgressDialog dialog;
public Db_connection(HashMap<String,String> params,String URL,Context con) {
this.params = params;
this.URL = URL;
this.con = con;
this.dialog = new ProgressDialog(con);
this.dialog.setCancelable(true);
this.CC = ConnectionController.getInstance();
}
public void startTest() {
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (dialog.isShowing()) { dialog.dismiss(); }
if (response != null && response.has("result")) {
try {
if (!response.getString("result").matches("error")) {
Toast.makeText(con, "Response: "+response.getString("result"), Toast.LENGTH_LONG).show();
}
else { Toast.makeText(con, response.getString("errmsg"), Toast.LENGTH_LONG).show(); return; }
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ToolTip tt = new ToolTip(con, error.getMessage());
tt.showNow();
Log.e("Error: ", error.getMessage());
}
});
req.setRetryPolicy(rp);
CC.addToRequestQueue(req);
}
}
public class ToolTip {
private Context con;
private PopupWindow pn;
private View layout;
private ImageView cancel;
private TextView mess;
public ToolTip(Context con,String htmlMsg) {
this.con = con;
LayoutInflater inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.tooltip,null);
pn = new PopupWindow(layout,LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,false);
pn.setAnimationStyle(R.style.AnimationToolTip);
cancel = (ImageView)layout.findViewById(R.id.tooltip_imageClose);
mess = (TextView)layout.findViewById(R.id.tooltip_mainText);
mess.setText(Html.fromHtml(htmlMsg));
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pn.dismiss();
}
});
}
public void showNow() {
pn.showAtLocation(/*HERE IS WHERE I DON'T KNOW WHAT TO PASS AS VIEW*/((Activity) con).getActionBar().getCustomView(), Gravity.NO_GRAVITY, 0, 180);
}
}
Everything works but when the volley request throws an error and uses the ToolTip class to show the error:
ToolTip tt = new ToolTip(con, error.getMessage());
tt.showNow();
i get this exception:
11-21 15:08:06.390: E/AndroidRuntime(22448): Process: com.tooltip.test, PID: 22448
11-21 15:08:06.390: E/AndroidRuntime(22448): java.lang.ClassCastException: com.tooltip.test.ConnectionController cannot be cast to android.app.Activity
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.tooltip.test.ToolTip.showNow(ToolTip.java:46)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.tooltip.test.Db_connection$2.onErrorResponse(Db_connection.java:100)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.volley.Request.deliverError(Request.java:577)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.os.Handler.handleCallback(Handler.java:733)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.os.Handler.dispatchMessage(Handler.java:95)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.os.Looper.loop(Looper.java:136)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.app.ActivityThread.main(ActivityThread.java:5139)
11-21 15:08:06.390: E/AndroidRuntime(22448): at java.lang.reflect.Method.invokeNative(Native Method)
11-21 15:08:06.390: E/AndroidRuntime(22448): at java.lang.reflect.Method.invoke(Method.java:515)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
11-21 15:08:06.390: E/AndroidRuntime(22448): at dalvik.system.NativeStart.main(Native Method)
Usually i pass this:
((Activity) con).getActionBar().getCustomView()
as the view to which anchor the popup window and it works but in this particular case, the activity calling the tooltip class, doesn't have an actionbar (it's the only one, all others activity does have the custom actionbar).
I'm here to ask if there is a method to use a dummy, programmatically created view to use in this case.
Or maybe i'm doing it wrong and you have a nice suggestion :)
Thanks in advance
After some try i finally came to a solution: i choose to use two different method, one for activity with action bar, and one for activity without action bar:
public void showNow() { //THIS IS FOR ACTIVITY WITH ACTION BAR
pn.showAtLocation((Activity)con.getActionBar().getCustomView(), Gravity.NO_GRAVITY, 0, 180);
}
public void showNowNoActBar() { //THIS IS FOR ACTIVITY WITHOUT ACTION BAR
pn.showAtLocation(con.findViewById(R.id.dummy_hidden_view), Gravity.NO_GRAVITY, 0, 180);
}
Obviously R.id.dummy_hidden_view is defined in the XML Layout of the activity without the custom action bar like this:
<TextView
android:id="#+id/dummy_hidden_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone" />
I think that both method could be solved with only one method but as of now, i can rely on my "double method" solution for what i need. Hope it helps someone else. Still remain the fact that i will appreciate any better suggestion on how to handle this.
Im doing some database work in my app, i want to pull all the locations from my web database and show it in my listview in the app. Ive created the "API" where the respons is Json.
The link where the json is: http://000100023.host56.com/db_all.php
Using this tutorial: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
The Logcat:
11-14 16:50:21.508: E/AndroidRuntime(22809): FATAL EXCEPTION: AsyncTask #1
11-14 16:50:21.508: E/AndroidRuntime(22809): Process: com.spxc.nightclubratings, PID: 22809
11-14 16:50:21.508: E/AndroidRuntime(22809): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.lang.Thread.run(Thread.java:841)
11-14 16:50:21.508: E/AndroidRuntime(22809): Caused by: java.lang.NullPointerException
11-14 16:50:21.508: E/AndroidRuntime(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.doInBackground(SearchLocationActivity.java:132)
11-14 16:50:21.508: E/AndroidRuntime(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.doInBackground(SearchLocationActivity.java:1)
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$2.call(AsyncTask.java:288)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
11-14 16:50:21.508: E/AndroidRuntime(22809): ... 4 more
11-14 16:50:22.199: E/WindowManager(22809): android.view.WindowLeaked: Activity com.spxc.nightclubratings.SearchLocationActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42313208 V.E..... R......D 0,0-729,192} that was originally added here
11-14 16:50:22.199: E/WindowManager(22809): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
11-14 16:50:22.199: E/WindowManager(22809): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
11-14 16:50:22.199: E/WindowManager(22809): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Dialog.show(Dialog.java:286)
11-14 16:50:22.199: E/WindowManager(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.onPreExecute(SearchLocationActivity.java:119)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.AsyncTask.execute(AsyncTask.java:535)
11-14 16:50:22.199: E/WindowManager(22809): at com.spxc.nightclubratings.SearchLocationActivity.onCreate(SearchLocationActivity.java:59)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Activity.performCreate(Activity.java:5243)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.access$700(ActivityThread.java:135)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.Handler.dispatchMessage(Handler.java:102)
**11-14 16:50:22.199: E/WindowManager(22809): at android.os.Looper.loop(Looper.java:137)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.main(ActivityThread.java:4998)
11-14 16:50:22.199: E/WindowManager(22809): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 16:50:22.199: E/WindowManager(22809): at java.lang.reflect.Method.invoke(Method.java:515)
11-14 16:50:22.199: E/WindowManager(22809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-14 16:50:22.199: E/WindowManager(22809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-14 16:50:22.199: E/WindowManager(22809): at dalvik.system.NativeStart.main(Native Method)
JsonParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
SearchLocationAcitivity:
public class SearchLocationActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://http://000100023.host56.com/db_all.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "locations";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_location);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
//Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
//in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
//startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchLocationActivity.this);
pDialog.setMessage("Loading locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchLocationActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Any help is much appreciated!
your URL string is wrong, you wrote it like:
Private static String url_all_products = "http://http://000100023.host56.com/db_all.php";
it should be:
Private static String url_all_products = "http://000100023.host56.com/db_all.php";
one http:// is enough ;)
initilize jParser in the onCreate
JSONParser jParser;
in onCreate
jParser = new JSONParser();
I'm trying to download strings from a HttpPost and I'm using the Async class to do this. But, when I run the App, it crashes. This is my first time using the Async class and I'm afraid I did some really silly, could you help me to find the error?
Just to note, I also want to update my listview when I get the strings. I tried to do this, buy putting them in a separate method.
Code:
public static final String PREFS_NAME = "MyPrefsFile";
BufferedReader in = null;
String data = null;
String username;
List headlines;
List links;
String password;
ArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// listview method
ContactsandIm();
new loadcontactsandIm().execute(PREFS_NAME);
}
public class loadcontactsandIm extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l ="";
String nl ="";
while ((l =in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
setListAdapter(adapter);
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
}
public void ContactsandIm() {
headlines = new ArrayList();
//get prefs
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String username = settings.getString("key1", null);
String password = settings.getString("key2", null);
if(username.equals("irock97")) {
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.setGravity(Gravity.TOP, -30, 50);
toast.show();
} else {
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.setGravity(Gravity.TOP, -30, 150);
toast.show();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
}
}
LogCat:
03-25 13:47:37.356: E/AndroidRuntime(2484): FATAL EXCEPTION: AsyncTask #1
03-25 13:47:37.356: E/AndroidRuntime(2484): java.lang.RuntimeException: An error occured while executing doInBackground()
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.os.AsyncTask$3.done(AsyncTask.java:200)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.lang.Thread.run(Thread.java:1096)
03-25 13:47:37.356: E/AndroidRuntime(2484): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.ViewRoot.requestLayout(ViewRoot.java:594)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.View.requestLayout(View.java:8125)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.View.requestLayout(View.java:8125)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.View.requestLayout(View.java:8125)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.ViewGroup.removeAllViews(ViewGroup.java:2255)
03-25 13:47:37.356: E/AndroidRuntime(2484): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:196)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.app.Activity.setContentView(Activity.java:1647)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.app.ListActivity.ensureList(ListActivity.java:314)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.app.ListActivity.getListView(ListActivity.java:299)
03-25 13:47:37.356: E/AndroidRuntime(2484): at com.gta5news.bananaphone.ChatService$loadcontactsandIm.doInBackground(ChatService.java:87)
03-25 13:47:37.356: E/AndroidRuntime(2484): at com.gta5news.bananaphone.ChatService$loadcontactsandIm.doInBackground(ChatService.java:1)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
do you job in doInBackground, and use your jobs result on onPostExecute.
example:
public class TestActivity extends Activity
{
private GetTask getTask;
public ListView fList;
#Override
public void onCreate(Bundle savedInstanceState)
{
getTask = new GetTask();
getTask.execute();
fList = (ListView) findViewById(R.id.lstview);
}
public class GetTask extends AsyncTask<Void, Void, List>
{
#Override
protected List doInBackground(Void... params) {
return load();
}
#Override
protected void onPostExecute(List result) {
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
fList.setAdapter(adapter);
}
}
private List load() {
// get your data from http
// add to your list, probably you can use model.
List headlines;
headlines.add(data);
return headlines;
}
}
You set your ListView adapter in doInBackground. Never manipulate the UI outside of UI thread
You can't interact with UI elements from any other thread than the main thread. You'll need to do all of the interaction of the ListView in the onPostExecute method.
Basically you will want to compile all the data from the web request in the doInBackground method, stored on your task instance, then on the onPostExecute get the list view and set the adapter and populate with the data.
Firstly you must not handle any UI related task in doInBackground() to UI related task we have a method call onPostExecute() where we can handle all ui related tasks..
If you still dont want to use these method and handle it in doInBackground() then you do it in the below code::::
runOnUiThread(new Runnable() {
public void run() {
//your UI related code stuff
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
setListAdapter(adapter); //do what you like here
}
});