Load Images Into ImageAdapter through JSON - android

HI I was trying GridView demo form this link
and it work superb but now I want to get the Images for server database.For that I implemented the handler class which will pass my URL and get the response from server. In response the JSON will contains the URLs of images. I also implemented one method which will download the images form that resultant URLs and set them into the Bitmap array..
The Service Handler class work correct but I don't know the changes I made in ImageAdapter class are correct or not..Please tell me where I'm getting wrong..
Following is code for ImageAdapter class..
public class ImageAdapter extends BaseAdapter {
private Context mContext;
Bitmap bm[]=new Bitmap[8];
ImageAdapter img;
public String[] imageurls=null;
// Keep all Images in array
public Integer[] mThumbIds ={
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
img =new ImageAdapter(mContext);
new GetImageUrls(mContext).execute();
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
if(bm[position]==null)
imageView.setImageResource(mThumbIds[position]);
else
imageView.setImageBitmap(bm[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context;
private ProgressDialog pDialog;
// URL to get JSON
private static final String url= "http://192.xxx.x.xxx/Demo_Folder/test.json";
private static final String RESULT = "mainCategory";
private static final String URLS = "mcatimage";
// JSONArray
JSONArray loginjsonarray=null;
//result from url
//public String[] imageurls=null;
public GetImageUrls(Context c) {
this.context=c;
}
protected void onPreExecute() {
// Showing progress dialog
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
//pDialog.show();
}
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.GET, null);
Log.d("Response: ", ">"+jsonstr);
if(jsonstr!=null){
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(RESULT);
for(int i=0;i<loginjsonarray.length();i++){
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(URLS);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
protected void onPostExecute(Integer result) {
// Dismiss the progress dialog
if(pDialog.isShowing()){
pDialog.dismiss();
new ImageDownloader().execute();
}
}
}
private class ImageDownloader extends AsyncTask<Integer, Integer, String>
{
Context context;
private ProgressDialog pDialog;
#Override
public void onPreExecute()
{
// Showing progress dialog
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
//pDialog.show();
}
protected void onPostExecute(String result)
{
pDialog.hide();
}
protected void onProgressUpdate(Integer... progress) {
img.notifyDataSetChanged();
}
protected String doInBackground(Integer... a)
{
for(int i=0;i<4;i++)
{
bm[i]=downloadBitmap(imageurls[i]);
this.publishProgress(i);
}
return "";
}
}
Bitmap downloadBitmap(String url) {
final HttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
//client.
}
}
return null;
}
}
As I run the code it get stop immediately..and gives the error like
FATAL EXCEPTION: main
Process: com.example.androidhive, PID: 1383
java.lang.StackOverflowError
at java.util.AbstractList.<init>(AbstractList.java:376)
at java.util.ArrayList.<init>(ArrayList.java:81)
at android.database.Observable.<init>(Observable.java:34)
at android.database.DataSetObservable.<init>(DataSetObservable.java:24)
at android.widget.BaseAdapter.<init>(BaseAdapter.java:31)
at com.example.androidhive.ImageAdapter.<init>(ImageAdapter.java:40)

remove this line
img =new ImageAdapter(mContext);
from Constructor of ImageAdapter. It is trying to create infinite number of ImageAdapter instances leading to StackOverflowError...
and why do you need another instance of ImageAdapter in ImageAdapter?

Related

JSON POST request for download image from server in android

I need to download image and set it in to imageview . for parsing i use JSON POST request and for this i use base64 . I got base64 type data for the image tag in to log but the problem is that how t separate the value of that image and convert it in to string and then display it in to list view ??is there any alternative way without using base64 to display image then please suggest us.
For parsing of data i use JSON parser with HttpPost .
Now how to get the value of image from response JSON format that i display above that the confusion ??
Thanks in advance ..
You can do like this.
Create folder in server. put images in that folder. get the URL of the image and insert in to db.
then get the JSON value of that url
add this method and pass that url to this method.
Bitmap bitmap;
void loadImage(String image_location) {
URL imageURL = null;
try {
imageURL = new URL(image_location);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
// bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Try below code:
JSONObject res = jsonObj.getJSONObject("root");
JSONObject data = jsonObj.getJSONObject("data");
JSONArray imgs= jsonObj.getJSONArray ("images");
for(int i=0;i<imgs.length();i++){
JSONObject Ldetails = Ldtls.getJSONObject(i);
String img= Ldetails.getString("image");
byte[] decodedString = Base64.decode(img,Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imagevw.setImageBitmap(bitmap);
}
where imagevw is your ImageView.
Use a Gson Parser and then parse the base64 image string to a byte array and apply on the image.
Your model classes will be as follows:
public class JsonWrapper
{
private Root root ;
public Root getroot()
{
return this.root;
}
public void setroot(Root root)
{
this.root = root;
}
}
public class Root
{
private Response response ;
public Response getresponse()
{
return this.response;
}
public void setresponse(Response response)
{
this.response = response;
}
}
public class Response
{
private Message message ;
public Message getmessage()
{
return this.message;
}
public void setmessage(Message message)
{
this.message = message;
}
private Data data ;
public Data getdata()
{
return this.data;
}
public void setdata(Data data)
{
this.data = data;
}
}
public class Message
{
private String type ;
public String gettype()
{
return this.type;
}
public void settype(String type)
{
this.type = type;
}
private String message ;
public String getmessage()
{
return this.message;
}
public void setmessage(String message)
{
this.message = message;
}
}
import java.util.ArrayList;
public class Data
{
private ArrayList<Image> images ;
public ArrayList<Image> getimages()
{
return this.images;
}
public void setimages(ArrayList<Image> images)
{
this.images = images;
}
private String last_synchronized_date ;
public String getlast_synchronized_date()
{
return this.last_synchronized_date;
}
public void setlast_synchronized_date(String last_synchronized_date)
{
this.last_synchronized_date = last_synchronized_date;
}
}
public class Image
{
private String web_id ;
public String getweb_id()
{
return this.web_id;
}
public void setweb_id(String web_id)
{
this.web_id = web_id;
}
private String blob_image ;
public String getblob_image()
{
return this.blob_image;
}
public void setblob_image(String blob_image)
{
this.blob_image = blob_image;
}
}
Once you have the json parse using Gson as follows:
JsonWrapper jsonWrapper = new JsonWrapper();
Gson gsonParser = new Gson();
jsonWrapper = gsonParser.fromJson(data, jsonWrapper.getClass());
Next you can iterate through all the images
ArrayList<Image> images = jsoinWrapper.getRoot().getResponse().getData().getImages();
for(Image image : images)
{
byte[] decodedString = Base64.decode(image.getblob_image(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (decodedString != null) {
imageViewtype.setImageBitmap(decodedByte);
}
}
public class SingleContactActivity extends Activity implements OnClickListener {
private static final String TAG_ImageList = "CatList";
private static final String TAG_ImageID = "ID";
private static final String TAG_ImageUrl = "Name";
private static String url_MultiImage;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
String imagepath2;
Bitmap bitmap;
ImageView image;
SessionManager session;
TextView myprofileId;
TextView pending;
TextView Categories, visibleTo;
int count = 0;
ImageButton btn;
// -----------------------
ArrayList<HashMap<String, String>> ImageList;
JSONArray JsonArray = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
url_MultiImage = "http://test2.sonasys.net/Android/GetpostImg?UserID=1&PostId=80";
new MultiImagePath().execute();
ImageList = new ArrayList<HashMap<String, String>>();
}
private class MultiImagePath extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url_MultiImage,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JsonArray = jsonObj.getJSONArray(TAG_ImageList);
if (JsonArray.length() != 0) {
for (int i = 0; i < JsonArray.length(); i++) {
JSONObject c = JsonArray.getJSONObject(i);
String Img_ID = c.getString(TAG_ImageID);
String Img_Url = c.getString(TAG_ImageUrl);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ImageID, Img_ID);
contact.put(TAG_ImageUrl, Img_Url);
// adding contact to contact list
ImageList.add(contact);
}
}
Log.e("JsonLength", "length is ZERO");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AutoGenImgBtn();
}
}
#SuppressWarnings("deprecation")
public void AutoGenImgBtn() {
int count = ImageList.size();
LinearLayout llimage = (LinearLayout) findViewById(R.id.llimage);
ImageButton[] btn = new ImageButton[count];
for (int i = 0; i < count; i++) {
btn[i] = new ImageButton(this);
btn[i].setId(Integer.parseInt(ImageList.get(i).get(TAG_ImageID)));
btn[i].setOnClickListener(this);
btn[i].setTag("" + ImageList.get(i).get(TAG_ImageUrl));
btn[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
btn[i].setImageDrawable(getResources().getDrawable(drawable.di1));
btn[i].setAdjustViewBounds(true);
// btn[i].setTextColor(getResources().getColor(color.white));
llimage.addView(btn[i]);
}
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btn = (ImageButton) v;
String s = btn.getTag().toString();
new ImageDownloader().execute(s);
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return downloadBitmap(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
pDialog = new ProgressDialog(SingleContactActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.setTitle("In progress...");
// pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setIcon(android.R.drawable.stat_sys_download);
pDialog.setMax(100);
// pDialog.setTitle("Post Details");
pDialog.show();
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
if (bitmap != null) {
btn.setImageBitmap(bitmap);
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
// forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
// check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that
// android understands
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for
// IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while"
+ " retrieving bitmap from " + url + e.toString());
}
return null;
}
}
# Add Service Handler Class#
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
*
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

Passing object model to another AsyncTask from other AsyncTask and adding data to model doesn't render

This is my first async task, which gets called first, it gets data from server and then onPostExecute it executes other async task, which downloads and sets image.
private class GetData extends AsyncTask<String, Void, Void> {
private final HttpClient client = new DefaultHttpClient();
private String content;
private String error = null;
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected Void doInBackground(String... params) {
try {
HttpGet httpget = new HttpGet(params[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;
}
#Override
protected void onPostExecute(Void result) {
if (error == null) {
try {
JSONObject dataDishes = new JSONObject(content);
Log.d("DISHES", dataDishes.toString());
ArrayList<DishModel> dishData = new ArrayList<DishModel>();
for (int i = 0; i < 8; i++) {
DishModel model = new DishModel();
model.setName("Company " + i);
model.setDesc("desc" + i);
//TODO: set data img
new GetImage(model).execute("http://example.com/" + (i + 1) + ".png");
dishData.add(model);
}
ListView listAllDishes = (ListView) getView().findViewById(R.id.listView);
DishRowAdapter adapterAllDishes = new DishRowAdapter(getActivity(),
R.layout.dish_row, dishData);
listAllDishes.setAdapter(adapterAllDishes);
} catch (JSONException e) {
Log.d("DISHES", e.toString());
}
} else {
Log.e("DISHES", error);
}
}
}
This is another async task, it downloads image and onPostExecute it sets image to passed model.
private class GetImage extends AsyncTask<String, Void, Void> {
private DishModel model;
private Bitmap bmp;
public getImage(DishModel model) {
this.model = model;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
Log.d("DISHES", params[0]);
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
Log.d("DISHES", e.toString());
}
} catch (MalformedURLException e) {
Log.d("DISHES", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
model.setPhoto(bmp);
}
}
It works if I do both data/image download proccess in one AsyncTask doInBackground(String... params), but it doesnt when I split data and image downloading into seperate async tasks. Furthermore I dont get any exceptions or errors.
UPDATE: Images shows up when i switch views..
At first, getImage and getData are classes, and classes names in Java are capitalized.
Technically, you can run another AsyncTask from onProgressUpdate() or onPostExecute() - https://stackoverflow.com/a/5780190/1159507
So, try to put the breakpoint in second AsyncTask call and debug is it called.

Need to access AsyncTask value in Main Class

I am facing an issue in Async task, can anyone please suggest me any solution.
I have downloaded this example from this link :
Source
My Current Structure is
Main Class extends MyTask and implements AsyncTaskCompleteListener interface.
AsyncTaskCompleteListener is an Interface contains the onTaskComplete Method .
MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.
Http Class(Utils) contains the Http connection and returns the Result-set to AsyncTaskComleteListner from PostExecute.
I am trying to get my result-set Value in the main class from the interface method to perform my further operation.
I tried to get the value from static variables, static method but non of them worked, and also tried with creating a new class object to send and receive the result but every time it gives me NullPointerException . Because the statement written after the AsyncTask gets executes before getting the result.
I have also tried to get the Status of asyncTask from its method getStaus(), but it returns only Running and dose not notify when the task is completed or finished.
Here is the code sample:
Main Class Code :
package com.example.androidasynctask;
public class MainActivity extends Activity implements AsyncTaskCompleteListener {
public static String[] asyncResult;
String res[] = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnclick(View view) {
/*MyTask asyncTask = new MyTask(this);
String [] asyncTaskResult = asyncTask.execute("fetchCategory.php","1%Id%1");*/
//AsyncTask<String, Void, String[]> asyncTaskRes = new MyTask(this).execute("fetchCategory.php","1%Id%1");
//new MyTask(this).execute("fetchCategory.php","1%Id%1");
MyTask asyncTask = (MyTask) new MyTask(this).execute("fetchCategory.php","1%Id%1");
if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {
Log.v("In Else","Get Value");
}
}
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
}
/*#Override
public void onTaskComplete(String result) {
System.out.println("calling onTaskComplete SIMPLE....");
System.out.println("result :: "+ result);
}*/
public static class GetAsyncResult
{
static String[] returnValues;
public GetAsyncResult()
{}
public GetAsyncResult(String[] res)
{
returnValues = res;
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}
public void getResultSetValues()
{
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}
}
}
Async Task Code :
public class MyTask extends AsyncTask<String, Void, String[]> {
private Activity activity;
private ProgressDialog dialog;
private AsyncTaskCompleteListener callback;
public String[] asyncResultSetValue = null;
public MyTask(Activity act) {
Log.v("MY TASK","ACTIVITY"+act);
this.activity = act;
this.callback = (AsyncTaskCompleteListener)act;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v("MY TASK","in ON PRE EXECUTE");
dialog = new ProgressDialog(activity);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String[] doInBackground(String... params) {
Log.v("MY TASK","DO IN BACKGROUND");
Log.v("PARAMS"," params[0] = "+params[0]+ "| params[1]"+params[1]);
asyncResultSetValue = Utils.process_query(params[0],params[1]);
return asyncResultSetValue;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
Log.v("MY TASK","in ON POST EXECUTE");
if (null != dialog && dialog.isShowing()) {
dialog.dismiss();
}
callback.onTaskComplete(result);
}
}
HTTP CLASS CODE :
public class Utils {
static String result = null;
String endResult;
static java.io.InputStream is = null;
static StringBuilder sb=null;
static String delimiter = "\\|";
static String delimiter1 = "\\%";
static String[] temp = null;
static String[] temp1 = null;
static ArrayList<NameValuePair> nameValuePairs;
static Context context;
static ProgressDialog mDialog;
static HttpResponse response;
static String[] resultset_value = null;
//static String url = "http://fortuneworkinprogress.in/News_App/"; //Global URL
static String url = "http://10.0.2.2/News_App/"; //Global URL
static String query_type,parameter;
/*************** PROCESS QUERY START ***************/
public static String[] process_query(String str_url, String parameter) {
// String strval = select_parameter;
String ret_val[] = null;
String get_sel_val[] = null;
int loopcount =0;
url = url+str_url; //!!!! ######### CONCATINATING AND CREATING FULL URL ######## !!!!!!//
Log.v("PROCESS QUERY PARAMETER","URL = "+url+" | PARAMTER = "+parameter);
nameValuePairs = new ArrayList<NameValuePair>();
//Log.i("STR VAL",""+strval); //To Check which values are recieved
try
{
String strval = parameter;
get_sel_val=strval.split(delimiter1);
for(int i =0; i < get_sel_val.length ; i++)
{
loopcount = Integer.parseInt(get_sel_val[0]); // First Delimeted Value which tells the number of count
Log.i("Loopcount","cnt = "+loopcount);
}
for(int j=1;j<=(loopcount*2);j=j+2) //For Loop for making Name Values Pares Dynamic
{
nameValuePairs.add(new BasicNameValuePair(get_sel_val[j],get_sel_val[j+1]));
//Log.i("J = ["+j+"]","pairvalue1 = "+get_sel_val[j]+"pairvalue2 ="+get_sel_val[j+1]);
}
}
catch(Exception e)
{
Log.w("Exception in the getting value","Exp = "+e);
}
//nameValuePairs.add(new BasicNameValuePair("id","1"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
Log.v("CONNECT URL ","Final url "+url);
Log.w("CONNECTION STATUS ",httppost.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("PAERSE VALUE ",nameValuePairs.toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("1", "Connection establised succesfuly");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
Log.v("SB VALUE = ","sb = "+sb.toString());
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
// Toast.makeText(getBaseContext(), result ,Toast.LENGTH_LONG).show();
Log.w("result", result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(null, "error converting response to string" ,Toast.LENGTH_LONG).show();
}
String[] temp = null;
String[] tempResult = null;
if(result!=null)
{
tempResult = result.split(delimiter); //Split the entire return string into "rows"
for(int i =0; i < tempResult.length-1 ; i++)
{
temp = null;
temp = tempResult[i].split(delimiter1); //Find columns for each row
ret_val = temp;
resultset_value=ret_val;
}
}
else
{
Toast.makeText(null, "Cannot Find Routes" ,Toast.LENGTH_LONG).show();
}
Log.v("BEFORE RETUNR = ","ret_val = "+ret_val.toString());
return ret_val; //Returning the result value array
}
/*************** PROCESS QUERY ENDS ***************/
public static boolean isNetworkAvailable(Activity activity)
{
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
return false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}
Thanks in advance.
Because the statement written after the AsyncTask gets executes before getting the result.
the reason is AsyncTask runs on separate thread,not on your Main(UI) thread.
MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.
you will be getting result values on this method
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
}
Comment following piece of code,
if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {
Log.v("In Else","Get Value");
}
Make change,
public static String[] asyncResult; to public String[] asyncResult = null;
Change following,
asyncResultSetValue = Utils.process_query(params[0],params[1]); to asyncResult = Utils.process_query(params[0],params[1]);
and return asyncResultSetValue; to return asyncResult ;
look at value by adding one more log,you will be getting result values on this method
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
Log.v("IN ON TASK COMPLETE","VALUE = "+asyncResult[1]);
}

Properly Using AsyncTask get()

I am running into a problem. I need to use asynctask to retrieve JSON data and I need that data before I moved to the next part of the program. However, when using the get() method of AsyncTask I have 5 to 8 sec black screen before I see the data is displayed. I would like to display a progress dialog during the data retrieval but I cannot do this due to the black screen. Is there a way to put into another thread? here is some code
AsyncTask
public class DataResponse extends AsyncTask<String, Integer, Data> {
AdverData delegate;
Data datas= new Data();
Reader reader;
Context myContext;
ProgressDialog dialog;
String temp1;
public DataResponse(Context appcontext) {
myContext=appcontext;
}
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(myContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
};
#Override
protected Data doInBackground(String... params) {
temp1=params[0];
try
{
InputStream source = retrieveStream(temp1);
reader = new InputStreamReader(source);
}
catch (Exception e)
{
e.printStackTrace();
}
Gson gson= new Gson();
datas= gson.fromJson(reader, Data.class);
return datas;
}
#Override
protected void onPostExecute(Data data)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
DisplayInfo
public class DisplayInfo extends Activity implements AdverData {
public static Data data;
public ProjectedData attup;
public ProjectedData attdown;
public ProjectedData sprintup;
public ProjectedData sprintdown;
public ProjectedData verizionup;
public ProjectedData veriziondown;
public ProjectedData tmobileup;
public ProjectedData tmobiledown;
public ProjectedAll transfer;
private ProgressDialog dialog;
public DataResponse dataR;
Intent myIntent; // gets the previously created intent
double x; // will return "x"
double y; // will return "y"
int spatial; // will return "spatial"
//public static Context appContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
dialog= new ProgressDialog(DisplayInfo.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
myIntent= getIntent(); // gets the previously created intent
x = myIntent.getDoubleExtra("x",0); // will return "x"
y = myIntent.getDoubleExtra("y", 0); // will return "y"
spatial= myIntent.getIntExtra("spatial", 0); // will return "spatial"
String URL = "Some URL"
dataR=new DataResponse().execute(attUp).get();
#Override
public void onStart()
{more code}
When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.
Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface

How can I remove an alert dialog after a AsyncTask has done it's work

I believe I'm doing this correctly, in my activity class I'm calling execute the alert dialog appears and then the data load but the alert dialog never goes away. Here is my AsyncTask code:
Followed by my activity code.
public class Worker extends AsyncTask<URL, Integer, Long>{
private Activity ne;
private ProgressDialog progressDialog;
private Handler handler;
public Worker(Handler handler, Activity ne){
this.handler = handler;
this.ne = ne;
}
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ne,"", "Retrieving News Events", true);
}
protected void onProgressUpdate(Void... progress) {
}
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Long doInBackground(URL... urls) {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(urls[0].toURI());
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
return null;
}
}
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private TextView selection;
private ProgressDialog progressDialog;
static final int PROGRESS_DIALOG = 0;
public static final String KEYWORDS = "keywords";
private NewsEvents ne;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
selection=(TextView)findViewById(R.id.selection);
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
}
First of all change your onPostExecute to include the #Override:
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
In your class definition include this:
public class Worker extends AsyncTask<Void, Void, Void>
The first parameter is the type of input to the doInBackground method, the second is the type of the input to the onProgressUpdate and the third is the type of the input to the onPostExecute and the result from doInBackground.
It does not look like you are using the input parameter to the doInBackground method, so just change that to Void... and change the return type as well:
protected Void doInBackground(Void... paramArrayOfParams) { ... }
Does this help?
Edit:
I saw you had changed your code to use the parameter of the doInBackground, so the first parameter in your class definition is correct. However, try putting Void as the two last parameters. And change the return type of the doInBackground to Void too.
Like this:
public class Worker extends AsyncTask<URL, Void, Void>{
private Activity ne;
private ProgressDialog progressDialog;
private Handler handler;
public Worker(Handler handler, Activity ne){
this.handler = handler;
this.ne = ne;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ne,"", "Retrieving News Events", true);
}
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(URL... urls) {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(urls[0].toURI());
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
return null;
}
You're not overriding the asynctask method correctly. Take a look at an example
http://developer.android.com/reference/android/os/AsyncTask.html
and note now they declare their asynctask
extends AsyncTask<URL, Integer, Long>

Categories

Resources