Piccaso not loading Image on First Attempt android - android

In my application I have a fragment which loads image from remote server to set background of FrameLayout using AsynTask and in onPostExeccute() method I am trying to render Bitmap images using Picasso. But as my Fragment starts first time no image is loaded in the background of FrameLayout but as I refresh the particular fragment then I can see the Image as background.
Updated Code segment inside AsyncTask
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String responseBody = "";
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(ctx, "Server connection failed", Toast.LENGTH_LONG).show();
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == -1){
Toast.makeText(ctx, "Sorry No Places Found", Toast.LENGTH_LONG).show();
}
if(jsonResult == 1){
//Toast.makeText(ctx, "", Toast.LENGTH_LONG).show();
try {
JSONObject jsonObj = new JSONObject(result);
// Getting JSON Array node
places = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < places.length(); i++) {
JSONObject place = places.getJSONObject(i);
// String slot = c.getString(TAG_SLOT);
// serverReturn.add(slot);
UserPlaces placeFroServer = new UserPlaces();
placeFroServer.setId(place.getString(TAG_PID));
placeFroServer.setName(place.getString(TAG_PNAME));
placeFroServer.setDescription(place.getString(TAG_DESC));
placeFroServer.setImg(place.getString(TAG_IMG));
placeFroServer.setLat(place.getString(TAG_LAT));
placeFroServer.setLng(place.getString(TAG_LNG));
placesList.add(placeFroServer);
}
UserPlaces myPlace = placesList.get(counter);
pid=myPlace.getId();
lat = myPlace.getLat();
lng = myPlace.getLng();
Picasso.with(ctx).load(myPlace.getImg()).into(new Target() {
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
// TODO Auto-generated method stub
Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
pImg.invalidate();
}
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
}
});
pname.setText(myPlace.getName());
pdes.setText(myPlace.getDescription());
rl.setVisibility(View.VISIBLE);
counter++;
} catch (JSONException e) {
String ex = e.getMessage();
e.printStackTrace();
}
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}

For particular problem of week reference try creating a global Target object. As demonstrated in the code below.
Code Sample:
Target target;
target = new Target(){
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
//Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
pImg.invalidate();
}
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
}
};
Picasso.with(ctx).load(myPlace.getImg()).into(target);

You should call invalidate() on pImg after setting the background.

You can use the alternative of it Univerasal Image Loader

Related

On scroll listener calling asynctask twice thrice or some times more on scrolling once on listview

As i am loading data from web through an api as user scrolls to bottom in listview but When i scroll on listview for once it calls asynctask for many times in my activity which causes duplicate data in listview and in case of exception lots of dialog and toast on activity and when i scrolled to bottom and simply just touch my listview on scroll method get fires which calls asynctask again for many time so please tel me how to prevent this.
here is my code of onscroll method.
listView.setOnScrollListener(new OnScrollListener() {
// boolean mIsScrollingUp;
// int mLastFirstVisibleItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
if(scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL)
userscrolled=true;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
int lasinscren = firstVisibleItem + visibleItemCount;
if(userscrolled&&(lasinscren==totalItemCount)&&!lodinmore&&(visibleItemCount<totalItemCount)&&havedata)
{
progress = true;
if(Search_API==false){
if(connectionDetector.isConnectintoInternet()){
System.out.println("inside listview on scroll function");
darList_task = new DAR_list_task(DAR_Activity.this).execute();
lodinmore = true;
}else
{
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_SHORT).show();
}
}else
{
new search_task(DAR_Activity.this).execute();
}
}
}
});
here's my asynctask
public class DAR_list_task extends AsyncTask<Void, Void, Void>
{
Context activity;
public DAR_list_task(Context activity) {
// TODO Auto-generated constructor stub
this.activity = activity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if(progress==true){
if(limit==0)
{
dialog = new Dialog(DAR_Activity.this);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
LinearLayout linearLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.dialog_progress, null);
dialog.setContentView(linearLayout);
ProgressBar progressBar1 = (ProgressBar)findViewById(R.id.progress_dialog);
dialog.setCancelable(false);
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
dialog.getWindow().setGravity(Gravity.CENTER);
}else
{
progressBar.setVisibility(View.VISIBLE);
}
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
response=null;
lodinmore = true;
URL Url;
try {
byte[] data;
data = login_id.getBytes("UTF-8");
String login_base_64 = Base64.encode(data);
data = gcm_id.getBytes("UTF-8");
String gcm_base64= Base64.encode(data);
if(url.contentEquals(""))
{
Url = new URL(getResources().getString(R.string.dar_list_view));
}else
{
Url = new URL("http://"+url+"/smart_oms/dar_app/view_dar.php");
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("login_id", login_base_64));
nameValuePairs.add(new BasicNameValuePair("gcm_id", gcm_base64));
nameValuePairs.add(new BasicNameValuePair("limit", String.valueOf(limit)));
HttpURLConnection httpURLConnection = (HttpURLConnection)Url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(getQueryString(nameValuePairs));
bufferedWriter.flush();
bufferedWriter.close();
os.close();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
response = BufferReaderMaker.readContentFromIS(inputStream);
}catch( final UnknownHostException ex)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}catch (final ConnectTimeoutException e) {
// TODO: handle exception
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Object json = null;
try {
if(response!=null)
{
if(progress==false)
{
dar_List_Items.clear();
dar_Aadapter = new DAR_Aadapter(DAR_Activity.this, dar_List_Items);
listView.setAdapter(dar_Aadapter);
dar_Aadapter.notifyDataSetChanged();
}
try {
json = new JSONTokener(response).nextValue();
} catch (JSONException e1) {
// TODO Auto-generated catch block
ErrorDialog errorDialog = new ErrorDialog();
errorDialog.Dialog(activity, statusCode, response, login_id, "", new DAR_list_task(activity));
}
if(json instanceof JSONArray)
{
havedata=false;
Toast.makeText(getApplicationContext(), "No More DAR", 0).show();
}else if(json instanceof JSONObject)
{
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("view_dar_detail");
for(int i =0 ;i<jsonArray.length();)
{
JSONObject json_data = jsonArray.getJSONObject(i);
String dar_id = json_data.optString("customer_id");
String Customer_name = json_data.optString("customer_name");
String Contacted= json_data.optString("contact_person_name");
String product = json_data.optString("product");
String status = json_data.optString("dar_status");
String Contact_type = json_data.optString("contact_type");
String created_date = json_data.optString("dar_created_date");
String request_date = json_data.optString("requeste_date");
DAR_List_Item dar_List_Item = new DAR_List_Item(dar_id,Customer_name, Contacted, Contact_type, product, status, created_date, request_date,"abcd");
dar_List_Items.add(dar_List_Item);
i++;
}
int index = listView.getFirstVisiblePosition();
View v= listView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
listView.setAdapter(null);
DAR_Aadapter aadapter = new DAR_Aadapter(DAR_Activity.this, dar_List_Items);
listView.setAdapter(aadapter);
aadapter.notifyDataSetChanged();
listView.setSelectionFromTop(index, top);
}else
{
ErrorDialog errorDialog = new ErrorDialog();
errorDialog.Dialog(activity, statusCode, response, login_id, "", new DAR_list_task(activity));
}
lodinmore = false;
}
lodinmore = false;
} catch (JSONException e) {
// TODO Auto-generated catch block
ErrorDialog errorDialog = new ErrorDialog();
errorDialog.Dialog(activity, statusCode, response, login_id, "", new DAR_list_task(activity));
}
if(progress==true){
if(limit==0)
{
dialog.dismiss();
}else{
progressBar.setVisibility(View.GONE);
}
}
if(json instanceof JSONObject)
limit = limit +10;
}
}
pLease help me in this i have tried a lot of things like using flag value and many more but non of them working for me.
How to prevent calling asynctask calling many time?
how to prevent asynctask to fired when i scrolled to bottom and just touch the list?
There is a work around for this:
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount) {
if(lastLastitem !=lastItem){ //to avoid multiple calls for last item, declare it as a field in your Activity
lastLastitem = lastItem;
// Your async task here
}
An easy way is define a boolean param:
if(view.getLastVisiblePosition() == totalItemCount-1 && isLoadMore){
isLoadMore = false;
pageNum++;
loadMoreData(searchStr, donViID, pageNum, Constant.RECORD_PER_PAGE);
}

Dismiss Progress Dialog and handle exception in AsyncTask

I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?
Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}
You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}
#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}
first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions
private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}

how to fix getDataTask method error?

below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.

Fetching and setting images in listView via HTTP

I am making an app that loads images via internet to a ListView. It is built on sdk 15 with an minimum of 8. Everything works fine if i run it on an emulator with version 8, but if i run it on anything with an sdk of 11 and up the app fails to set the images in the ListView and it then only displays an empty list. Logcat doesn't give anything on this.
I haven't had any succes finding an article addressing this issue, but i think it most be something with the HTTP that is suppose to get the images from the internet, but i don't understand why they don't work on the newer versions of android.
My code looks like this.
EDIT UPDATED CODE:
public class MainActivity extends Activity {
static ArrayList<Tumblr> tumblrs;
ListView listView;
TextView footer;
int offset = 0;
ProgressDialog pDialog;
View v;
String responseBody;
HttpResponse r;
HttpEntity e;
String searchUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
setContentView(R.layout.main);
try {
tumblrs = getTumblrs();
listView = (ListView) findViewById(R.id.list);
View v = getLayoutInflater().inflate(R.layout.footer_layout,
null);
footer = (TextView) v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
new GetChicks().execute();
footer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new loadMoreListView().execute();
}
});
} else {
setContentView(R.layout.nonet);
}
}
public class UserItemAdapter extends ArrayAdapter<Tumblr> {
public UserItemAdapter(Context context, int imageViewResourceId) {
super(context, imageViewResourceId, tumblrs);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tumblr tumblr = tumblrs.get(position);
if (tumblr != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(GetImage_usingURl(urls[position]));
}
}
return v;
}
}
String[] urls = new String[] { "url1", "url2", "url2" };
public Bitmap GetImage_usingURl(String BitmapUrl) {
try {
Log.d("Image Download State", " Open Stream For : " + BitmapUrl);
InputStream in = new java.net.URL(BitmapUrl).openStream();
Log.d("Image Download State", " Start Decode");
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", "" + e.getMessage());
return null;
}
}
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
IOException, JSONException {
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=rTZsymOWtMudbb5tql2U20qQ5ooYLPYVNnL3COPpO2qBHDxJUu&limit=2&offset=0";
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
return tumblrs;
}
private class GetChicks extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Chicks coming up..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpGet get = new HttpGet(searchUrl);
HttpResponse r = null;
try {
r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
e = r.getEntity();
responseBody = EntityUtils.toString(e);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray(
"photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// Setting new scroll position
listView.setSelectionFromTop(0, 0);
pDialog.dismiss();
}
}
public class Tumblr {
public String image_url;
public Tumblr(String url) {
this.image_url = url;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("More chicks coming up..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
// increment current page
offset += 2;
// Next page request
tumblrs.clear();
String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=rTZsymOWtMudbb5tql2U20qQ5ooYLPYVNnL3COPpO2qBHDxJUu&limit=2&offset="
+ offset;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
HttpResponse r = null;
try {
r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
responseBody = EntityUtils.toString(e);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray(
"photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// Setting new scroll position
listView.setSelectionFromTop(0, 0);
pDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.aboutUs:
Intent i = new Intent("com.example.example.ABOUT");
startActivity(i);
break;
case R.id.refresh:
Intent f = new Intent(MainActivity.this, MainActivity.class);
startActivity(f);
finish();
break;
case R.id.exit:
finish();
break;
}
return false;
}
}
LOG
10-09 13:21:57.923: D/Image Download State(888): Open Stream For : url1
10-09 13:21:57.923: E/Error(888): Protocol not found: url1
10-09 13:21:58.013: D/Image Download State(888): Open Stream For : url2
10-09 13:21:58.033: E/Error(888): Protocol not found: url2
10-09 13:21:58.113: D/Image Download State(888): Open Stream For : url1
10-09 13:21:58.123: E/Error(888): Protocol not found: url1
10-09 13:21:58.153: D/Image Download State(888): Open Stream For : url2
10-09 13:21:58.153: E/Error(888): Protocol not found: url2
For Images From internet Try this Could Help you:
if you want to download when you create adapter .
String[] urls=new String[]{"url1","url2","url2"}
public Bitmap GetImage_usingURl(String url){
try {
Log.d("Image Download State", " Open Stream For : "
+ url);
InputStream in = new java.net.URL(url).openStream();
Log.d("Image Download State", " Start Decode");
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
return null;
e.printStackTrace();
}
}
And When You Create Adapet Just Use :
image.setImageBitmap(GetImage_usingURl(urls[position]);
Important Thing For Your Project You Have To Get Policy When You using HTTP its Only For API 9 or higher so i check VERSION.SDK_INT First .
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if you don't set StrictMode you program maybe crash.
Set This Code Before Everything .
Your Errors Its :
In getView You Try To Check img!=null but you forget its create now and its already null
so compiler never get in and set your images , This is first thing .

populating listview through a fragment

I have a class extending listFragment. I have written code for fetching json response in a method which is called in oncreate of the class. For fetching json in background I have created new inner class which extends asyncTask. I can get the jsonarrays and strings in the json response in the logcat. But when I try to save them in a string array and pass them my custom baseadapter, I get a nullpointer exception.
public class OnlineInfo extends ListFragment {
public static String result;
public String[] Technologies1;
public String[] TechnologyDescription1;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
downloadjsonresponse();
}
public class Download extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
StringBuilder stringbuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet url = new HttpGet(params[0]);
try
{
Log.d("in background", "in background");
HttpResponse response = client.execute(url);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line ;
while((line = reader.readLine()) != null)
{
stringbuilder.append(line);
}
}
catch(ClientProtocolException e)
{
Log.d("error in clientprotocol", "error");
e.printStackTrace();
}
catch(IOException e)
{
Log.d("error in IO", "error");
e.printStackTrace();
}
return stringbuilder.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
OnlineInfo.result = result;
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray raja = jsonobject.getJSONArray("Technologies");
//String raja = jsonobject.getJSONArray("Technologies").getJSONObject(0).getString("desc");
//Log.d("desc:", raja);
for(int i=0; i<raja.length();i++)
{
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Log.d("technology :", raja.getJSONObject(i).getString("name"));
Log.d("technologydescription :", raja.getJSONObject(i).getString("desc"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("desc:", "error");
}
getListView().setAdapter(new AdapterForOnlineInfo(getActivity(), OnlineInfo.this.Technologies1, OnlineInfo.this.TechnologyDescription1));
}
}
public void downloadjsonresponse()
{
Download jsonresponse = new Download();
jsonresponse.execute("http://www.avantajsoftwares.com/result.json");
}
}
I could get the results in logcat whenever I comment these two lines in for-loop:
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Don't know what's going wrong. Please somebody provide me some insight....:-(
I think you need to allocate space in your string arrays to hold the new strings.
Just before your for loop, try putting something like this:
Technologies1 = new String[raja.length()];
TechnologyDescription1 = new String[raja.length()];

Categories

Resources