I have implemented AsyncTask like this in my code. Can you tell me if I used AsyncTask correctly? Thanks.
protected class AsyncTranslator extends AsyncTask<String, JSONObject, String>
{
#Override
protected String doInBackground(String... params) {
String mymeaning = null;
RestAPI api = new RestAPI();
try
{
JSONObject jsonObj = api.GetMeaning(params[0]);
mymeaning = jsonObj.toString();
}
catch (Exception e)
{
Log.d("Error", e.getMessage());
}
return mymeaning ;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Please wait.", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String mymeaning) {
Log.d("onPostExecute", null);
Intent i = new Intent(SendMeaningActivity.this, ShowMeaningActivity.class);
i.putExtra("meaning", mymeaning);
startActivity(i);
}
}
Yes you used it correctly.
Fot API call, think to use library like Retrofit. It will make your life easier.
Related
I am trying to get data from server using AsyncTask, on first time result not showing, but its working from second time. I seen so many examples but none of them working for me. please see my code below
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(Void aVoid) {
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
Whenever you want to use onPostExecute() method in AsyncTask, just make sure use String or other type instead of Void as result parameter of AsyncTask<x, y, String> where x,y are any data type(Integer,String,etc..).
Therefore, make changes in code as per below:
Make both AsyncTask<...> like this AsyncTask<Integer,Void,String>
Change return type of doInBackground from Void to String
Change return null; with return ""; at last line in doInBackground.
Change onPostExecute(Void aVoid) to onPostExecute(String s) for override function of onpostexecute.
Then try it.
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,JSONArray> task = new AsyncTask<Integer, Void, JSONArray>() {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
#Override
protected JSONArray doInBackground(Object... integers) {
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
return array;
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(JSONArray array) {
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
I working on android application which post its location to server. Here's one problem.
When I run this application in genymotion, it succesfully send POST requests to server. However, when I installed on samsung galaxy note, it doesn't send these post requests.
Where can be the problem?
EDIT: I successfully can fetch data from internet by GET request
Code:
class Posting extends AsyncTask<Location, String, String>{
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(Location... locations){
RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(RetrofitClient.API_URL2).build();
RetrofitClient.TestRetro retrofit = restAdapter.create(RetrofitClient.TestRetro.class);
IssdDeviceLog body=new IssdDeviceLog();
body.setDeviceNo("hello from SAMSUNG MAIN ACTIVITY service");
body.setLatitude(new BigDecimal(locations[0].getLatitude()));
body.setLongtitude(new BigDecimal(locations[0].getLongitude()));
Date date= new Date();
body.setDate(date.toString());
Gson gson = new Gson();
String json = gson.toJson(body);
Response response=retrofit.sendLocation(json);
Log.d("status code"," "+response.getStatus());
return null;
}
#Override
protected void onPostExecute(String file_url) {
}
}
With regards
can you put your error if you getting any error or you can use volley library i am sharing this code you can use this for your post request
public class send_data extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(main.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle("please wait...");
mProgressDialog.show();
}
protected String doInBackground(String... args) {
String url = "http://your_url";
try {
ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>(
1);
nvp.add(new BasicNameValuePair("key for your data","yourdata"));
String str_responsebody = obj_service.executer(url, nvp);
Log.i("responce", str_responsebody + "===");
return str_responsebody;
} catch (Exception e) {
Log.i("error1", "" + e.toString());
return null;
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i("result", result);
mProgressDialog.dismiss();
}
} catch (Exception e) {
Log.e("error2", "" + e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
}
}
}
download volley lib and add in your project. tutorial [link]: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
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 :)
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.
I'm new to Android development and I'm trying to code a little app which allows me to grab an external JSON file and parse it. I got this to work, however it wont work if I try to execute it in the background as an AsyncTask. Eclipse gives me the error
The method findViewById(int) is undefined for the type LongOperation
in this line:
TextView txtView1 = (TextView)findViewById(R.id.TextView01);
Here is my code:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
}
class LongOperation extends AsyncTask<String, Void, String> {
private final Context LongOperation = null;
#Override
protected String doInBackground(String... params) {
try {
URL json = new URL("http://www.corps-marchia.de/jsontest.php");
URLConnection tc = json.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
JSONObject jo = (JSONObject) ja.get(0);
TextView txtView1 = (TextView)findViewById(R.id.TextView01);
txtView1.setText(jo.getString("text") + " - " + jo.getString("secondtest"));
}
} catch (MalformedURLException e) {
Toast.makeText(this.LongOperation, "Malformed URL Exception: " + e, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this.LongOperation, "IO Exception: " + e, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(this.LongOperation, "JSON Exception: " + e, Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
ProgressDialog pd = new ProgressDialog(LongOperation);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
}
}
Any ideas on how to fix this?
Here is what you should do to make it work as you want. Use onPostExecude()
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation(this).execute();
}
}
class LongOperation extends AsyncTask<String, Void, String> {
private Main longOperationContext = null;
public LongOperation(Main context) {
longOperationContext = context;
Log.v("LongOper", "Konstuktor");
}
#Override
protected String doInBackground(String... params) {
Log.v("doInBackground", "inside");
StringBuilder sb = new StringBuilder();
try {
URL json = new URL("http://www.corps-marchia.de/jsontest.php");
URLConnection tc = json.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
JSONObject jo = (JSONObject) ja.get(0);
Log.v("line = ", "jo.getString() ="+jo.getString("text"));
sb.append(jo.getString("text") + " - " + jo.getString("secondtest")).append("\n");
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.v("Error", "URL exc");
} catch (IOException e) {
e.printStackTrace();
Log.v("ERROR", "IOEXECPTOIn");
} catch (JSONException e) {
e.printStackTrace();
Log.v("Error", "JsonException");
}
String result = sb.toString();
return result;
}
#Override
protected void onPostExecute(String result) {
Log.v("onPostExe", "result = "+result);
TextView txtView1 = (TextView)longOperationContext.findViewById(R.id.textView01);
txtView1.setText(result);
}
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
ProgressDialog pd = new ProgressDialog(longOperationContext);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
}
}
The implementation of AsyncTask in one of the other answers is flawed. The progress dialog is being created every time within publishProgress, and the reference to the dialog is not visible outside the method. Here is my attempt:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
class LongOperation extends AsyncTask<String, Void, String> {
ProgressDialog pd = null;
TextView tv = null;
#Override
protected void onPreExecute(){
tv = Main.this.findViewById(R.id.textvewid);
pd = new ProgressDialog(Main.this);
pd.setMessage("Working...");
// setup rest of progress dialog
}
#Override
protected String doInBackground(String... params) {
//perform existing background task
return result;
}
#Override
protected void onPostExecute(String result){
pd.dismiss();
tv.setText(result);
}
}
}
You are trying to do something which won't work. First of all you are inside of a class that extends AsyncTask so you won't have that method available as it is a method of the class Activity.
The second problem is that you are trying to do UI stuff in a method that is not synchronized with the UI thread. That is nothing you would want to do.
Process your JSON response in the doInBackground method and pass the result to the onPostExecute method where you will be able to handle UI stuff as it is synchronized with the UI thread.
The current setup you have will not make it easier for you to handle what you are trying to do anyway. You could make your LongOperation class a private class of your Activity class and define the TextView as a instance member. Grab it off the layout using findViewById inside of your OnCreate and modify (set text or whatever) inside the onPostExecute method of your AsyncTask.
I hope it is somewhat clear what I meant.
findViewById is method in Activity class. You should pass instance of your activity to your LongOperation when you create it. Then use that instance to call findViewById.