Image Loader with AsyncTask - java

In my main page, I'm calling an AsyncTask that is its own class.
new DownloadFileAsync(context, icon, resultp.get(PublicProfilePage.REVIEWCREATORFBOOKID),"300").execute();
Below is my AsyncTask. I'm reading a JSON trying to get the image's URL. Once I capture that URL I use ImageLoader to cache it, but it does not work.
public class DownloadFileAsync extends AsyncTask<Void, Void, String> {
//private Context context;
CircularImageView bmImage;
ImageLoader imageLoader;
String fbook_id;
String jsonobject;
String image_size;
String size_url;
public DownloadFileAsync(Context context, CircularImageView bmImage, String fbook_id, String size)
{
//this.context = context;
this.bmImage = bmImage;
this.fbook_id = fbook_id;
this.image_size = size;
//Image Loader Initialization
imageLoader = new ImageLoader(context);
if(image_size.equalsIgnoreCase("150")) {
size_url = "https://graph.facebook.com/v2.1/" + fbook_id + "/picture?redirect=0&height=150&width=150";
}else if(image_size.equalsIgnoreCase("300")) {
size_url = "https://graph.facebook.com/v2.1/" + fbook_id + "/picture?redirect=0&height=300&width=300";
}
}
protected String doInBackground(Void... urls) {
String result = null;
String queryResponse = null;
String resultTwo = null;
// Create a new HttpClient and Post Header
HttpClient httpclientBankCheck = new DefaultHttpClient();
HttpGet httppostBankCheck = new HttpGet(size_url);
try {
// Execute HTTP Post Request
HttpResponse responseBankCheck = httpclientBankCheck.execute(httppostBankCheck);
HttpEntity responseText = responseBankCheck.getEntity();
queryResponse = EntityUtils.toString(responseText);
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
jsonobject = queryResponse;
// Locate the array name
JSONObject arr = new JSONObject(jsonobject);
result = arr.getString("data");
JSONObject arrTwo = new JSONObject(result);
resultTwo = arrTwo.getString("url");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultTwo;
}
protected void onPostExecute(String resultTwo) {
//bmImage.setImageBitmap(result);
imageLoader.DisplayImage(resultTwo, bmImage);
}
}
If I hard code the URL into ImageLoader inside my main page, it does work. Is the problem that I'm using an AsyncTask with ImageLoader? It shouldn't be right?
Really appreciate the help!
-M

Related

Nullpointer exception comes in onpostexcute [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Plz help me
When we get data from server and save in a string variable, it is store in a variable but cantnot retrive.
public class Profile extends Activity {
ListView list;
Activity act;
String[] username = { "Pankaj", "Aaa" };
TextView name;
JSONObject object;
String url = "http://thinksl.com/taughtable/profile.php?user_email=pank#gmail.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
list = (ListView) findViewById(R.id.list);
name = (TextView) findViewById(R.id.mailid);
Custom_Profile pro = new Custom_Profile(Profile.this, username);
list.setAdapter(pro);
new Userdata().execute(url);
}
public class Userdata extends AsyncTask<String, Void, String> {
public static final int connection_type = 1500;
Profile p = new Profile();
ProgressDialog dialog;
String resul;
HashMap<String, String> user;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new ProgressDialog(Profile.this);
dialog.setTitle("Processing");
dialog.setMessage("Loading Data.Please wait....");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... url) {
// TODO Auto-generated method stub
Log.e("result", "Do in background");
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, connection_type);
HttpConnectionParams.setSoTimeout(params, connection_type);
HttpClient client = new DefaultHttpClient(params);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_email", "pank#gmail.com"));
HttpGet get = new HttpGet(url[0]);
try {
Log.e("result", "Try");
HttpResponse response = client.execute(get);
Log.e("result", "Response" + response);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Log.e("result", "result" + result);
JSONObject jobject = new JSONObject(result);
object = jobject.getJSONObject("userdetail");
Log.e("result", "result" + object);
String name = object.getString("user_login");
int post = object.getInt("month");
Log.e("name", "name" + name);
Log.e("name", "post" + post);
Log.e("result", "result" + resul);
user = new HashMap<String, String>();
user.put("name", name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
String s = user.get("name").toString();
p.name.setText(s);
}
}
}
The problem is that you are returning always null, after catch you have the only returning.
Look the last line of doinbackground method, "returning null".
So change to this:
HttpGet get = new HttpGet(url[0]);
HttpResponse response = client.execute(get);
Log.e("result", "Response" + response);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
return result;
And in the postexecute method do it:
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jobject = new JSONObject(result);
object = jobject.getJSONObject("userdetail");
Log.e("result", "result" + object);
String name = object.getString("user_login");
int post = object.getInt("month");
Log.e("name", "name" + name);
Log.e("name", "post" + post);
Log.e("result", "result" + resul);
user = new HashMap<String, String>();
user.put("name", name);
dialog.dismiss();
String s = user.get("name").toString();
p.name.setText(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
use this code
JSONObject res = new JSONObject(result);
JSONObject response = res.getJSONObject("userdetail");
String niceName = response.getString("user_nicename");
String displayName = response.getString("display_name");

Displaying database records in android using JAVA RESTful webservice

I am trying to display database record using java restful web service. I have able to create a login form using it but I cannot display the records on the database. I tried this code but its not working at all. When button is pressed nothing happens. Heres my code.
DriverDetails.java
class Details extends Activity {
TextView name1;
TextView plate1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://192.168.254.108:8080/taxisafe/display/taxidetails";
//JSON Node Names
private static final String TAG_USER = "taxi";
private static final String TAG_NAME = "taxi_name";
private static final String TAG_EMAIL = "taxi_plate_no";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
plate1 = (TextView)findViewById(R.id.plate);
}
#Override
protected JSONObject doInBackground(String... args) {
HttpConnection jParser = new HttpConnection();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
name1.setText(name);
plate1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
HttpConnection.java
public class HttpConnection {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public HttpConnection() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
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) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I suggest adding Volley to your project
https://developer.android.com/training/volley/index.html
and following the example here https://developer.android.com/training/volley/request.html#request-json
You will not need to create your own HTTP request. Let Volley handle the network request using JSONObjectRequest

Android java parsing Json from url to object list

I would like to connect to a Api url, retrieve the json and store everything in a object list. Here is an example of what the url can return as Json.
The following code was given to me but it returns a error Cannot resolve method setOnResponse in my activity line 31
This is my activity.java
public class resultOverview_activity extends Activity implements onResponse{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_overview);
Bundle search_activity_data = getIntent().getExtras();
if(search_activity_data == null){
return;
}
String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/Sunrise";
AsyncTask parkingInfoFetch = new AsyncFetch(this);
parkingInfoFetch.setOnResponse(this);
parkingInfoFetch.execute(URL);
//Log.i("gw2Log", parkingInfoFetch.);
}
#Override
public void onResponse(JSONObject object) {
Log.d("Json Response", "Json Response" + object);
ResultClass resultClass = new ResultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray array = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = array.getJSONObject(i);
resultClass.setData_id(resultsObject.getInt("data_id"));
resultClass.setName(resultsObject.getString("name"));
resultClass.setRarity(resultsObject.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject.getString("img"));
resultClass.setType_id(resultsObject.getInt("type_id"));
resultClass.setSub_type_id(resultsObject.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
AsyncFetch.java class
public class AsyncFetch extends AsyncTask<String, Void, JSONObject> {
public AsyncFetch(Context context) {
this.context = context;
}
private Context context;
private JSONObject jsonObject;
private onResponse onResponse;
public onResponse getOnResponse() {
return onResponse;
}
public void setOnResponse(onResponse onResponse) {
this.onResponse = onResponse;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpGet get = new HttpGet(params[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
jsonObject = new JSONObject(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.onResponse.onResponse(result);
}
public interface onResponse {
public void onResponse(JSONObject object);
}
}
And ofcourse the constructur ResultClass which i assume is not necessary to include here as code.
What does this error Cannot resolve method setOnResponse mean and how do i fix this?
Change this line:
AsyncTask parkingInfoFetch = new AsyncFetch(this);
To this:
AsyncFetch parkingInfoFetch = new AsyncFetch(this);
The error means that the line:
parkingInfoFetch.setOnResponse(this);
Is trying to call a method defined in the subclass AsyncFetch, but you have the variable defined as the parent class AsyncTask which has no method setOnResponse.

Json response is very slow android

I'm writing an Android application which will occasionally need to download a json string of around 1MB and containing around 1000 elements, and parse each of these into an SQLite database, which I use to populate a ListActivity.
Even though the downloading and parsing isn't something that needs to be done on every interaction with the app (only on first run or when the user chooses to refresh the data), I'm still concerned that the parsing part is taking too long, at around two to three minutes - it seems like an eternity in phone app terms!
I am using this code... :-
public class CustomerAsyncTask extends AsyncTask<String, Integer, String> {
private Context context;
private String url_string;
private String usedMethod;
private String identifier;
List<NameValuePair> parameter;
private boolean runInBackground;
AsynTaskListener listener;
private Bitmap bm = null;
public ProgressDialog pDialog;
public String entityUtil;
int index = 0;
public static int retry = 0;
private String jsonString = "";
private String DialogString = "";
// use for AsyncTask web services-----------------
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground, String DialogString,
List<NameValuePair> parameter, AsynTaskListener callack) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.DialogString = DialogString;
}
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground,
List<NameValuePair> parameter, AsynTaskListener callack, Bitmap bm) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.bm = bm;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (runInBackground)
initProgressDialog(DialogString);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000; // mili second
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
HttpResponse response = null;
if (usedMethod.equals(GlobalConst.POST)) {
HttpPost httppost = new HttpPost(this.url_string);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
// Customer Login MObile
if (identifier.equals("Customer_Login")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_mob",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
// Customer Verify Code
} else if (identifier.equals("Customer_mob_verify")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_verify",
params[0]));
parameter.add(new BasicNameValuePair("cus_mobile",
params[1]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
} else if (identifier.equals("Dashboard")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_id",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
}
response = (HttpResponse) httpClient.execute(httppost);
} else if (usedMethod.equals(GlobalConst.GET)) {
HttpGet httpput = new HttpGet(this.url_string);
httpput.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = (HttpResponse) httpClient.execute(httpput);
}
// Buffer Reader------------------------
InputStream inputStream = null;
String result = null;
try {
HttpEntity entity1 = response.getEntity();
inputStream = entity1.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
jsonString = result;
} catch (ClientProtocolException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (IOException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (Exception e1) {
e1.printStackTrace();
return AsyncResultConst.EXCEPTION;
} finally {
httpClient.getConnectionManager().shutdown();
}
return AsyncResultConst.SUCCESS;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (runInBackground)
pDialog.dismiss();
if (result.equals(AsyncResultConst.SUCCESS)) {
listener.onRecieveResult(identifier, jsonString);
} else if (result.equals(AsyncResultConst.PARSINGERROR)) {
// showAlertMessage(context, "Error", "Parsing Error", null);
listener.onRecieveException(identifier, result);
} else {
if (retry < 0) {
retry++;
new CustomerAsyncTask(context, url_string, usedMethod,
identifier, runInBackground, DialogString, parameter,
listener).execute("");
} else {
// showAlertMessage(context, "Error", "Connection Error", null);
listener.onRecieveException(identifier, result);
}
}
super.onPostExecute(result);
}
private void initProgressDialog(String loadingText) {
pDialog = new ProgressDialog(this.context);
pDialog.setMessage(loadingText);
pDialog.setCancelable(false);
pDialog.show();
}
}
Don't use Async-task in such case, use native java thread here.
new Thread(new Runnable() {
public void run() {
// Do your work .....
}
}).start();
When need to update UI. Yes! Android won't allow you to do that. so... solution is: USE Handler for that :)
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// Do Update your UI
}
});
Use AsyncTask for:
Simple network operations which do not require downloading a lot of
data Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
You could use Google's GSON as well.
Try to use Jackson Library to manage your JSON. It is really efficient. You can find it here : http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs
I am using it for a 400KB file is less than 1 second.
If you want a tuto this one looks good http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
This is how is read JSON into my listview in my app. The result is processed to my app in an average of 3 seconds on Wi-Fi and 5 seconds on 3G:
public class CoreTeamFragment extends ListFragment {
ArrayList> membersList;
private String url_all_leaders = //URL goes here
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_TEAM = "CoreTeam";
private static final String pid = "pid";
private static final String COL_NAME = "CoreTeam_Name";
private static final String COL_DESC = "CoreTeam_Desc";
private static final String COL_PIC = "CoreTeam_Picture";
JSONArray CoreTeam = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public CoreTeamFragment() {
}
public void onStart() {
super.onStart();
membersList = new ArrayList<HashMap<String, String>>();
new LoadAllMembers().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.leader_id))
.getText().toString();
Intent intent = new Intent(view.getContext(),
CoreTeamDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_coreteam,
container, false);
return rootView;
}
class LoadAllMembers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_leaders,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
CoreTeam = json.getJSONArray(TABLE_TEAM);
// looping through All Contacts
for (int i = 0; i < CoreTeam.length(); i++) {
JSONObject ct = CoreTeam.getJSONObject(i);
// Storing each json item in variable
String id = ct.getString(pid);
String name = ct.getString(COL_NAME);
String desc = ct.getString(COL_DESC);
String pic = ct.getString(COL_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_PIC, pic);
// adding HashList to ArrayList
membersList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(),
membersList,
R.layout.coreteam_item,
new String[] { pid, COL_NAME, COL_DESC, COL_PIC },
new int[] { R.id.leader_id, R.id.leaderName,
R.id.photo });
setListAdapter(adapter);
}
});
}
}
}
Use Volley or Retrofit lib.
Those lib are increasing the speed.
Volley:
JsonObjectRequest channels = new JsonObjectRequest(Method.POST,
Constants.getaccountstatement + Constants.key, statement_object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}

drawable from an url with honeycomb

from the beginning i used this method :
public Drawable createPortrait(String url){
try {
InputStream is = (InputStream)new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "Image");
return d;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
but honeycomb doesn't allow me to do it anymore, what i see in my log is : android.os.networkonmainthreadexception .
the thing is that my url is already taken from json data :
private class GrabURL extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Main.this);
protected void onPreExecute() {
Dialog.setMessage("Downloading source..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(Main.this, Error, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Main.this, "Source: " + Content, Toast.LENGTH_LONG).show();
}
Object o = new Gson().fromJson(Content, Info.class);
Info i = (Info)o;
String d = i.getData().get(0).getLg_portrait();
portrait.setBackgroundDrawable(createPortrait(d));
}
}
and portrait is an ImageView . i don't know what to do .
You need to download the image in Async task as well. Honeycomb simply does not let you run lengthy HTTP operation blocking the UI thread (reading from stream makes HTTP call and waits for the image to be downloaded). You should return some placeholder immediately, trigger AsyncTask and replace the image after it is already downloaded.
Hint "post execute" is run in UI thread....

Categories