Exact procedure to add an image through json android - android

Hello so I have already an expirience with AsyncTask so I can manage to get some data with PHP scripts from an SQL Server and parsed them with JSON. Now what I would want is to know how can I use the AsyncTask in order to load images to some activities. Also is there anyway that I can call the AsyncTask before the app starts? because that would be really helpful too.
I don't have any adapters I am just using this for the AsyncTask:
// The definition of our task class
private class PostTask extends AsyncTask<String, Integer, String> {
private String postName;
private JSONObject jsonvar = new JSONObject();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
this.postName = params[0];
String status = "";
List<NameValuePair> values = new ArrayList<NameValuePair>();
values.add( new BasicNameValuePair( "username", this.postName ) );
final AndroidHttpClient client = AndroidHttpClient.newInstance( "" );
HttpResponse response = HttpHelper.postResponse( client, Register.phpUrl, values );
String data = HttpHelper.getData( response );
try {
jsonvar = new JSONObject(data);
status=jsonvar.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.close();
return status;
}
// #Override
// protected void onProgressUpdate(Integer... values) {
// super.onProgressUpdate(values);
// }
#Override
protected void onPostExecute(String status) {
String session = "", status_message = " ";
try {
status_message = jsonvar.getString("status_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
super.onPostExecute(status);
}
}
}

As i can tell with information provided, supposing that what you read from your server is the image URL and obtain it in JSON format, what i would do is writing a listener to your AsyncTask, calling it in onPostExecute method, and loading it in your Activity using PicassoImagesLoader
Something like:
private class PostTask extends AsyncTask<String, Integer, String> {
public interface onLoadFinishedListener {
public void onLoadFinished(JSONObject response)
}
protected JSONObject onPostExecute(JSONObject response){
onLoadFinished(response);
}
}
And in your Activity:
public myActivity extends Activity implements PostTask.onLoadFinishedListener {
#Override
onLoadFinished(JSONObject response){
Picasso.with(this).load(response.getString("url")).into(imageView);
}
}
Something like this would help :)

Related

Multiple Async Tasks one after another Android

I'm trying to fetch data from server in saving in SQLite database through Async task on Splash. i have multiple tables on server and need to fetch one after another. I'm trying this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
url = getResources().getString(R.string.url);
db = new SQLCont(context);
new asyn_Task1(Splash.this).execute();
}
public class asyn_Task1 extends AsyncTask<String, Void, Boolean> {
public asyn_Task1(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task2(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....1 /10");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
postParameters.add(new BasicNameValuePair("001", data));
try {
CustomHttpClient.executeHttpGet("001");
} catch (Exception e1) {
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
id = json_data.getString("id");
st_name = " " + json_data.getString("name");
st_contact = json_data.getString("contact");
st_category = json_data.getString("Category");
st_address = json_data.getString("address");
Log.d("favourite_data", "" + id + st_name + st_contact
+ st_category + st_address);
db.adddata_hospital(context, st_name,st_contact,
st_category, st_address);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
return null;
}
}
public class asyn_Task2 extends AsyncTask<String, Void, Boolean> {
public asyn_Task2(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task3(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
public class asyn_Task3 extends AsyncTask<String, Void, Boolean> {
public asyn_blood_Group(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
problem is that data is added for asyn_Task1 it repeated every time
expected out put
abc def ghi
jkl mno pqr
mno pqr stu
But getting output
abc def ghi
abc def ghi
abc def ghi
You will get your data based on your query. If you always execute same query then you will always get same data.
And from my point of view if possible single AsyncTask for that purpose. when all the query is completed then onpostExecute() callback will fired.

error cannot convert from AsyncTask<String,String,String> to String

I want to load a data using JSON from php and then parsing it in android. I'm trying to implement asynctask in this process. And the return is in string. I got an error in
"Type mismatch : cannot convert from AsyncTask<String,String,String> to String in
ProsesTampil p = new ProsesTampil();
xResult = p.execute(urltampil);
The xResult is supposed to be the string value I got from php.
Here's the complete codes :
public void tampilkanData() {
try {
String nama = URLEncoder.encode(Login.usernameP, "utf-8");
urltampil += "?" + "&nama=" + nama;
txtNama.setText("");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ProsesTampil p = new ProsesTampil();
xResult = p.execute(urltampil);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
//jObject = new JSONObject(xResult);
JSONArray menuitemArray = new JSONArray(xResult);
jObject=menuitemArray.getJSONObject(0);
String sret="";
txtBerat.setText(jObject.getString("berat_badan"));
txtNama.setText(jObject.getString("username"));
// txtUsia.setText(jObject.getString("usia"));
txtTinggi.setText(jObject.getString("tinggi_badan"));
//System.out.println(jObject.getString("jenis_kelamin").equalsIgnoreCase("female"));
if(jObject.getString("jenis_kelamin").equalsIgnoreCase("female")){
radioFemale.setSelected(true);
radioMale.setSelected(false);
}else{
radioMale.setSelected(true);
radioFemale.setSelected(false);
}
}
public String getRequestData(String UrlTampil){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(UrlTampil);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"Gagal "+sret, Toast.LENGTH_SHORT).show();
}
System.out.println(sret);
return sret;
}
class ProsesTampil extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
return getRequestData(params[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
I'm sorry for my bad english. thanks in advance
The propose of an AsyncTask is execute some code in a separate thread (different from UI thread), but the result from that code, when ready, will be delivered in onPostExecute.i.e. The method execute returns the AynscTask itself,not String so change your code as
ProsesTampil p = new ProsesTampil();
xResult = p.execute(urltampil);
to
ProsesTampil p = new ProsesTampil();
p.execute(urltampil);
And get xResult in onPostExecute method as
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
xResult = result;
}
First Thing You can not return value from onPostExecute() because return type is void
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
Second Your class doesn't Return any value...
So if you want to get value of result try to get value from onPostExecute().
I mean to say do as follow..
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
xResult = result;
super.onPostExecute();
}
You can't do it because AsyncTask works in background thread.
Your result will come in UI thread after background has done self work:
#Override
protected void onPostExecute(String result) {
//String result - that what you need
}
execute() doesn't return a string. So you can't assign it like that. AsyncTasks are asynchronous- they don't finish until later. Any code you'd want to run on the result of an AsyncTask should be placed in the onPostExecute() function of the AsyncTask.
Yo can use
String results = yourAsyntask.get() instead of using yourAsyntask.execut()e method, it will return you result. same as Result get you in onPostExecute method;
But it will block your main thread.

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.

Can we call two methods at a time in doinbackground method of asynchronous task in android?

I am working on android applications. I need some clarification regarding asynchronous task doinbackground method.
Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LongOperation2 op = new LongOperation2();
op.execute("");
}
public void test1() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("id", id));
try {
res1 = CustomHttpClient.executeHttpPost(
"http://website.com/folder1/firstpage.php",
postParameters);
System.out.println("response in test1" + res1.trim());
}
catch (Exception e) {
e.printStackTrace();
}
}
public void test2() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("value", value));
try {
res2 = CustomHttpClient.executeHttpPost(
"http://website.com/folder1/secondpage.php",
postParameters);
System.out.println("response in test2" + res2.trim());
}
catch (Exception e) {
e.printStackTrace();
}
}
private class LongOperation2 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
test1();
test2();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
dialog1.dismiss();
try {
Test.this.startActivity(new Intent(Page1.this, Page2.class));
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
dialog1 = ProgressDialog.show(Test.this, "Please wait...",
"Retrieving data ...", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
In the above code I have two methods test1() and test2(). In both the methods I am passing parameters to webservice. Now my doubt is can I call both the methods at a time in doInBackground() of asynchronous task? Is that ok? Please let me know or give me suggestion regarding this. Thanks in advance.
There is nothing wrong in calling two or more methods. But they will be executed one after another sequentially. There is no multiprocessing inside doBackground method.

android.os.NetworkOnMainThreadException Sax parsing

This class causing me android.os.NetworkOnMainThreadException,i know that i have to use asyncTask to make it but i can't figure out how because i am using 1 fragments and this make my application very slow especially when i laod bitmaps, can any one help me please.
public class ContainerData {
static public Context context;
public ContainerData() {
}
public static ArrayList<Feed> getFeeds(String feedurl){
SAXParserFactory fabrique = SAXParserFactory.newInstance();
SAXParser parseur = null;
ArrayList<Feed> feeds = null;
try {
parseur = fabrique.newSAXParser();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL(feedurl);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
DefaultHandler handler = new ParserXMLHandler();
try {
parseur.parse(url.openConnection().getInputStream(), handler);
feeds = ((ParserXMLHandler) handler).getData();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return feeds;
}
}
If you use AsyncTask make sure getFeeds is called inside the doInBackground(...) callback
Regardless of whether you use a fragment or not, you're still trying to perform Network activity on the main thread.
Create a generic class that extends AsyncTask which can perform all your parsing.
public class MyTaskHandler extends AsyncTask<String, Integer, Boolean>
{
#Override
protected void onPreExecute()
{
//Could display progress dialog here
}
#Override
protected Boolean doInBackground(String... params)
{
//Implement your parser here
}
#Override
protected void onPostExecute(Boolean result)
{
//Check result, dismiss dialog etc
}
}
Then create a new instance of MyTaskHandler and run it...
MyTaskHandler myTask = new MyTaskHandler();
myTask.execute("http://www.myxmlsite.com/lists.xml");
The execute method can take (String... params) so you can pass for example a URL,and retrieve it in doInBackground(String... params)
#Override
protected Boolean doInBackground(String... params)
{
//Implement your parser here
String urlToParse = params[0];
}
Best of luck.

Categories

Resources