How to debug this Android Studio app - android

I have tried to access a web resource using my second android app, in Android Studio. Im on API 15 as min, target and build. Here is my class. Its not MVC at all, i just threw in all the stuff from the Developing your first Android App tutorial online into the MainActivity Class:
public class MainActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
private static final String MYURL = "http://www.server.com/app/service.php";
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.hello_world);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
//Check connectivity
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//fetch data
new DownloadWebpageTask().execute(MYURL);
textView.setText("Fetching data");
} else {
//show error
textView.setText("No network connection available.");
}
}
//Method to connect to the internet
// Uses AsyncTask to create a task away from the main UI thread. This task takes a
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the webpage as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask's onPostExecute method.
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
//Method to convert url to url object
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
//Convert input stream to string
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
and here is the huge log file:
Well I won't post it, but I have 2 questions:
How can I reduce all the output in log cat. I already switched from verbose to debug but I still get lots of stuff. And in this particular case, because the app crashes, I don't have time to do what another SO post said which is select the running process and hit the 2 green arrow button that filters out only output for the running process. Would I need to get the app to NOT crash before I could filter out the log such that i can SEE what is making it crash? Otherwise its difficult to sort through all the logs. What is the best practice here.
I do get one of my logs; "01-30 10:40:58.665 2047-2072/com.santiapps.downloadwebdata D/HttpExample﹕ The response is: 200" which is in the code but then a few lines down I get the crash:
01-30 10:40:58.710 2047-2047/com.santiapps.downloadwebdata E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException
at com.santiapps.downloadwebdata.MainActivity$DownloadWebpageTask.onPostExecute(MainActivity.java:77)
at com.santiapps.downloadwebdata.MainActivity$DownloadWebpageTask.onPostExecute(MainActivity.java:63)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5071)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
at dalvik.system.NativeStart.main(Native Method) 01-30 10:40:58.717 837-2676/? W/ActivityManager﹕ Force finishing activity com.santiapps.downloadwebdata/.MainActivity
Its a null pointer exception I see. How do I follow it? Sorry, Im new to android. Thanks

You can follow the logcat by clicking on the links, for example MainActivity.java:77.
You can filter the log by creating a new filter, (see image)
There you can filter by Package Name, so only the log of your app will be visible

Your TextView is null ...
You typically initialize it like this :
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.id_of_your_textview);
As for reducing the amount of log, you should filter the log on your app's package name. In Android Studio, this should be located on the right of Log Level in the Android DDMS panel (it probably reads No Filter for now, you will need to create one by clicking Edit Filter Configuration).

Related

Getting the calling fragment within an asynchronous task

Aim
In a fragment, I have a search bar which looks for online news about what the user typed. I would want to display these news (title + description + date of publication + ... etc.) in the GUI, as vertical blocks.
Implementation
Explanations
In the fragment, within the search event handling, I instanciated an asynchronous task and execute it with the good URL REST API I use to do the search.
In the asynchronous task, I make use of this REST API (thanks to the URL and some required parameters as an authorization key, etc.). When my asynchronous task gets answered, it must update the fragment's GUI (i.e.: it must vertically stack GUI blocks containing the titles, descriptions, etc. of the got news).
Sources
You will find sources in the last part of this question.
My question
In the asynchronous task (more precisely: in its function that is executed after having got the answer), I don't know how to get the calling fragment. How to do this?
Sources
Fragment part
private void getAndDisplayNewsForThisKeywords(CharSequence keywords) {
keywords = Normalizer.normalize(keywords, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
new NetworkUseWorldNews().execute("https://api.currentsapi.services/v1/search?keyword=" + keywords + "&language=en&country=US");
}
Asynchronous task part
public class NetworkUseWorldNews extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String[] urls) {
StringBuilder string_builder = new StringBuilder();
try {
URL url = new URL(urls[0]);
HttpsURLConnection https_url_connection = (HttpsURLConnection) url.openConnection();
https_url
_connection.setRequestMethod("GET");
https_url_connection.setDoOutput(false);
https_url_connection.setUseCaches(false);
https_url_connection.addRequestProperty("Authorization", "XXX");
InputStream input_stream = https_url_connection.getInputStream();
BufferedReader buffered_reader = new BufferedReader(new InputStreamReader(input_stream));
String line;
while((line = buffered_reader.readLine()) != null) {
string_builder.append(line);
}
buffered_reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return string_builder.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject news_response_http_call = new JSONObject(result);
switch(news_response_http_call.getString("status")) {
case "ok":
JSONArray news = news_response_http_call.getJSONArray("news");
for(int i = 0; i < news.length(); i++) {
JSONObject a_news = news.getJSONObject(i);
String title = a_news.getString("title");
String description = a_news.getString("description");
String date_of_publication = a_news.getString("published");
String url = a_news.getString("url");
String image = a_news.getString("image");
System.out.println(title + ": " + date_of_publication + "\n" + image + "\n" + url + "\n" + description);
WorldNewsFragment world_news_fragment = ...;
}
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
If I am right, you want to update View of your caller Fragment. if FragmentA called service then FragmentA should be update.
However the approach you are asking is wrong. Instead of getting caller Fragment in your AsyncTask response. You should do it with Callback.
So now you will need to pass callback in AsyncTask. So instead of posting full code, here are already answers with this problem.
Finally your calling syntax will look like.
NetworkUseWorldNews task = new NetworkUseWorldNews(new OnResponseListener() {
#Override
public void onResponse(String result) {
// Either get raw response, or get response model
}
});
task.execute();
Actually I am still very unclear about your question. Let me know in comments if you have more queries.
Must checkout
Retrofit or Volley for calling Rest APIs
Gson for parsing JSON response automatically to models

Calling Async class from Async class in Android not working?

So my goal is to load a random wikipedia page, get the title from it, and then use the wikipedia api to get the correct title to return for display (titles with special characters need "translated" to be able to display them correctly.) My problem comes when I use my JSONRequest class (Async) to try to execute the api url and create a JSON object. When it tries to execute, it freezes and doesn't go any further (but does not crash.) It isn't a problem with the URL, it is valid and works on desktop and mobile. This method was also used in another non-async class so I know it works there. My guess is that it is an async issue. This may be a stupid question with a simple answer, but any help is greatly appreciated!
public class getRandom extends AsyncTask<String, Void, String> {
private static final String REQUEST_METHOD = "GET";
private static final int READ_TIMEOUT = 15000;
private static final int CONNECTION_TIMEOUT = 15000;
String result, rawTitle;
// Gets random wiki page and returns text to be loaded into search bar
#Override
protected String doInBackground(String... params){
String randomUrl = "https://en.wikipedia.org/wiki/Special:Random";
String titleApiUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=";
// Get random title
try {
URL url = new URL(randomUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Set method and timeouts
con.setRequestMethod(REQUEST_METHOD);
con.setReadTimeout(READ_TIMEOUT);
con.setConnectTimeout(CONNECTION_TIMEOUT);
// Get status
int status = con.getResponseCode();
// Check for move or redirect and update url
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
// Get name of page
rawTitle = con.toString();
int temp = rawTitle.indexOf("wiki/") + 5;
rawTitle = rawTitle.substring(temp);
con.disconnect();
}
catch(IOException e){
e.printStackTrace();
rawTitle = "Sailboats"; // Very random, totally not hard coded result.
}
// Ensure correct title format (use wiki api)
try{
// Get json from api
JSONRequest wikiRequest = new JSONRequest();
String wikiApiJsonString = wikiRequest.execute(titleApiUrl + rawTitle).get();
// Create json object with returned string
JSONObject jsonObj = new JSONObject(wikiApiJsonString);
// Get correct title from json
result = jsonObj.getString("title");
}
catch(ExecutionException | InterruptedException | JSONException e){
e.printStackTrace();
result = "Sailboats"; // Very random, totally not hard coded result.
}
return result;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
By default, async tasks all run on the same thread. So it won't actually start a second task until yours finishes. Your options are:
1)Call executeOnExecutor instead of execute and tell it to use a new thread.
2)Architect your code such that you can make the request on this thread directly. You're already on a thread, no reason to launch a new one.
3)Write your code such as you don't need to call .get().

Second HttpURLConnection is failing

I have a ListView that onLongClick it calls a method that is supposed to go out to a website, pull a jsonArray from it and then return information that is pulled from the array. However, when it calls the HttpURLConnection.connect() method it fails and goes to the catch block. When I use the getMessage() message on the exception it only returns Null. This is the second time in this program that I've connected to a URL in this same way and it works the first time perfectly. What could be causing this issue?
Here is the code for when the method is called:
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> a, View v, int pos, long id) {
String trainNum = list.getItemAtPosition(pos).toString();
String info = "hello";
try {
info = getCurrentTrainInfo(trainNum);
}catch(Exception e){
info = e.getMessage();
if(info == null)
info = "info is null";
tv.setText(info);
}
Toast.makeText(getApplicationContext(), info, Toast.LENGTH_LONG).show();
return true;
}
}
);
And here is the method getCurrentTrainInfo that is called in the try block above:
public String getCurrentTrainInfo(String num) throws IOException{
String sURL = "http://www3.septa.org/hackathon/RRSchedules/" + num;
URL url = new URL(sURL);
HttpURLConnection request2 = (HttpURLConnection) url.openConnection();
request2.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray rootArr = root.getAsJsonArray();
int i = 0;
String acTime = "";
String station = rootArr.get(i).getAsJsonObject().get("station").getAsString();
String schTime = rootArr.get(i).getAsJsonObject().get("sched_tm").getAsString();
String esTime = rootArr.get(i).getAsJsonObject().get("est_tm").getAsString();
tv.setText(station);
String info = "Current Station: " + station + "\nScheduled leave time: " + schTime + "\nEstimated leave time: " + esTime;*/
return info;
}
Is there anything I can do to fix this problem?
I see your request is being made ​​in the UI thread, you mentioned that in another moment used this same way and it worked, I believe this may have happened when you ran your application on a device/emulator with a version of Android prior to 3.0.
Within an Android application you should avoid performing long
running operations on the user interface thread. This includes file
and network access. StrictMode allows to setup policies in your
application to avoid doing incorrect things. As of Android 3.0
(Honeycomb) StrictMode is configured to crash with a
NetworkOnMainThreadException exception, if network is accessed in
the user interface thread.
You can create a AsyncTasks class and move the call request to it.

android application hangs when it connects to webservice using 3g connection and works fine with WIFI

I am developing an android application that consumes web service , the service output is XML
I am connecting to the web service using this code
public String converse(String host, int port, String path)
throws IOException, URISyntaxException {
BufferedReader in = null;
String serviceResponse = null ;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
String serviceUrl = "http://"+host+":"+port+path;
System.out.println("service url "+serviceUrl);
request.setURI(new URI(serviceUrl));
System.out.println("Request "+request.toString());
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
serviceResponse = sb.toString();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return serviceResponse;
}
when the application launches with WI-FI every thing works fine and when I restart the application with 3G connection it hangs and displays a the following dialog
In addition to this code I am using this method inside another method
public void fillAdapter() {
//calling web service using the mentioned method
}
And this function used inside an async task to fill ListView adapter
protected class AsyncLoading extends AsyncTask<Void,Void, BaseModel[]>{
#Override
protected void onPreExecute(){
pd =ProgressDialog.show(BaseListActivity.this, "loading in progress", "waiting .");
}
#Override
protected BaseModel[] doInBackground(Void... params) {
fillAdapter();
return listItems;
}
#Override
protected void onPostExecute(BaseModel[] doc){
//list.setAdapter(doc);
if(doc != null) {
if(doc.length > 0 ) {
if(doc[0] instanceof Activity)
adapter = new OffersListAdapter(getApplicationContext(),doc);
else if (doc[0] instanceof Offer)
adapter = new OffersListAdapter(getApplicationContext(),doc);
else if (doc[0] instanceof Branch) {
adapter = new BranchListAdapter(getApplicationContext(),doc);
Log.i("Branch"," Added Branch");
}else if (doc[0] instanceof Consolation) {
adapter = new ListAdapter(getApplicationContext(),doc);
adapter.setDisplayImage(false);
}else if ( doc[0] instanceof Event) {
adapter = new EventListAdapter(getApplicationContext(),doc);
}
else
adapter = new ListAdapter(getApplicationContext(),doc);
}//end if doc != null
list.setAdapter(adapter);
}
handler.sendEmptyMessage(0);
}
I saw this post but I don't have a good result I'm working on this problem for 2 days
with my thanks in advance .
Note : this problem often appears the first time the application connects to the service after that if I pressed wait and the application continued then al other activities consuming the web service will work fine
I think you have low speed connection of 3G compared to Wi-Fi.So Use Asynctask to load data from server in seperate thread rather than main thread.It is good idea to show ProgressDialog while fetching the data.
And In some cases Apis will work in Wi-Fi and may not in 3G connection.So test Your url in Device browser also to make it confirm
You should use an AsyncTask for every task that could take some time to be executed. See http://developer.android.com/reference/android/os/AsyncTask.html
The problem i am seeing with your code is you are not doing network operation in Thread.
So if you perform asynchronous operation on Main thread,application will display above dialog if it don't receive response in 5 seconds.In your case 3g connection may be taking more than 5 seconds to return response.
Best bet is include above code in Thread!!
I have solved the problem , that I have a splash screen activity inside which I use C2DM and register the device in that activity using service
registrationIntent.putExtra("app", PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(), 0));
registrationIntent.putExtra("sender", "someemailaddress#gmail.com");
startService(registrationIntent);
I put this code inside an asyncTask and didn't block the UI
Thanks for every one who tried to help me

Return data from AsyncTask Android

I tried to refer similar question on SO, but didn't got any help.
In my android app, I'm planning to implement Recent Quote the user has visited i.e. similar to recently visited pages on web.
Following are the steps I'm following:
1.) Whenever user opens any company view, fetch the company symbols from database
2.) Then store the current symbol along with dateTime in database.
3.) For all symbols fetched from database, Fetch their current value and %Change and display Company name, current value and %Change in a list.
The problem arises in the ASyncTask class as postExecute method doesn't allow it's return type to be any other than void.
Am I doing anything wrong?
Any help will be life saver !!!
String[] rsym,rcmp,rchg;
rdbM = new RecentDBManager(CompanyView.this);
try {
Calendar date1 = Calendar.getInstance();
SimpleDateFormat dateformatter = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss");
String currentdate = dateformatter.format(date1.getTime());
rdbM.openDB();
//STEP 1
rsym = rdbM.getRecent_sym();
//STEP 2
rdbM.setData(currentsymbol, currentdate);
rdbM.closeDB();
} catch (Exception e) {
throw new Error(" *** ERROR in DB Access *** "+ e.toString());
}
//STEP 3
for(int i=0;i<rsym.length;i++)
{
DownloadRecentQuote quotetask = new DownloadRecentQuote();
recentquotetask
.execute(new String[] { "http://abc.com/stockquote.aspx?id="
+ rsym[i] });
//CURRENT VALUE and %CHANGE which should be returned from ASyncTask class
rcmp[i]=valuearr[0];
rchg[i]=valuearr[1];
}
list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
for (int i = 0; i < limit; i++)
{
addList1 = new HashMap<String, String>();
addList1.put(RecentSym_COLUMN, rsym[i]);
addList1.put(RecentCMP_COLUMN, rcmp[i]);
addList1.put(RecentChg_COLUMN, rchg[i]);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(
CompanyView.this, CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
private class DownloadRecentQuote extends AsyncTask<String, Void, String> {
/* Fetching data for RecentQuote information */
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
arr1 = result.split("#");
if (arr1[0].length() != 0) {
if (arr1[0].equals("1")) {
arr = arr1[1].split(";");
//RETURN 2 STRINGS
String valuearr[];
valuearr[0] = arr[3];
valuearr[1] = arr[6].concat("%");
//return valuearr;
}
}
}
postExecute() can't return a value because who or what would it return to? Your original method that invoked the AsyncTask is gone because your AsyncTask is running in the background. It's asynchronous meaning when AsyncTask.execute() returns it's still running in the background, and hence postExecute() can't return a value because there's nothing to return it to.
Instead your AsyncTask needs a reference back to your Activity or some other object so it can post your values back to it. In your code the lines after you call execute() can't be there because your task hasn't finished. Instead you should create a method called updateSymbol( currentPrice, percentChange), move all that code below execute() in there, and in your AsyncTask you should pass a reference to the Activity. Then call updateSymbol( currentPrice, percentChange ) from the onPostExecute() method.
But, be careful if you have a reference back to an Activity it can be destroyed while your doInBackground() is running, and when postExecute() runs it should just drop the results or not attempt to update the UI. For example, the user rotates their phone causing the Activity to be destroyed. I find it best to hold a reference to the AsyncTask in the activity so it can cancel() it if the Activity is destroyed. You can call AsyncTask.cancel() then check if your task was canceled like:
public void postExecute( String result ) {
if( !isCanceled() ) {
// do your updating here
activity.setSymbol( result );
}
}
It's really easy to create a base class for all Activities so you can easily keep track of AsyncTasks running:
public class BaseActivity extends Activity {
List<AsyncTask> runningTasks;
public void onStop() {
for( AsyncTask task : runningTasks ) {
task.cancel(true);
}
}
public AsyncTask start( AsyncTask task ) {
runningTasks.add( task );
return task;
}
public void done( AsyncTask task ) {
runningTasks.remove( task );
}
}
Some quick pointers. You don't need execute( new String[] { "blah" + blah } ). Varargs in Java allow you to do this. execute( "blah" + blah ). You also are catching exceptions and continuing without really handling them. It will be hard when something really happens because your app catches them, and just continues as if nothing happened. If you get an error you might want to provide some feedback to the user and stop trying to execute that process. Stop, show an error to the user, and let them do the next thing. Move the catch blocks to the bottom of the methods.
Essentially, AsyncTask.onPostExecute() is where you do whatever you want to do after AsyncTask's doInBackground() is executed and the execution result gets returned. This should be considered the best practice.
When AsyncTask().execute() is called from the UI thread (note that this method must be called from the UI thread), the Android framework creates a worker thread and starts running whatever you wrote in AsyncTask.doInBackground() on this worker thread. At this point (after calling new AsyncTask().execute()), the UI thread continues to execute code after new AsyncTask().execute(). So now during run time, you have two threads (UI and worker thread) both running simultaneously.
But where and when does the AsyncTask execution result get returned from the worker thread back to the UI thread?
The point where your worker thread (doInBackground()) finishes and returns to the UI thread is AysncTask.onPostExecute(). This method is guaranteed to be called by the framework on the UI thread as soon as AsyncTask finishes. In other words, we don't care where and when AsyncTask.onPostExecute() gets called at run time, we just need to guarantee it will be called ultimately at some stage in the future. This is the reason why this method does not return an execution result - instead, it requires that the execution result gets passed in as the only method parameter from doInBackground().
In addition, the Android API provides a way to return an AsyncTask execution result at coding time, AsyncTask.get():
MyAsyncTask myAsyncTask = new MyAsyncTask();
// This must be called from the UI thread:
myAsyncTask.execute();
// Calling this will block UI thread execution:
ExecutionResult result = myAsyncTask.get();
Bear in mind that AsyncTask.get() will block the calling thread's execution, and you will probably get an ANR exception if you call it on the UI thread. This is the payload of using AsyncTask.get(), by calling it on the UI thread, you are actually making your AsyncTask (worker thread) run synchronously with UI thread (by making UI thread wait). To sum up, this is doable but not recommended.
Just for future reference, because this post is a little old:
I have created an Activity class which has an onStart() method and a separate class for the AsyncTask. Based on my test, after the doInbackground() method the result will be sent to the activity first and after that onPostExecute() will run. This is because based off of logcat, I have my first response data (sent by server) first, then this response will show again from the activity and the last the message in onPostExecute() will show.
Code for the activity:
#Override
protected void onStart() {
super.onStart();
String str = "***";
if(isConnectedToInternet()){
myAsyncTask.execute();
try {
if(myAsyncTask.get())
str = myAsyncTask.getResponseMsg();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (CancellationException e) {
e.printStackTrace();
}
}
Log.i("Data returned by server2:", str);
}
AsyncTask code:
public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
private URL url;
private HttpURLConnection conn;
private String strResponseMsg;
public MyAsyncTask(String url) throws MalformedURLException{
this.url = new URL(url);
}
#Override
protected void onPreExecute() {
Log.i("Inside AsyncTask", "myAsyncTask is abut to start...");
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(Manager.ConnTimeout);
conn.setReadTimeout(Manager.ReadTimeout);
int responseCode = conn.getResponseCode();
Log.i("Connection oppened", "Response code is:" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// Showing returned message
strResponseMsg = strBuilder.toString();
Log.i("Data returned by server:", strResponseMsg);
status = true;
}
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.i("Inside AsyncTask", "myAsyncTask finished its task. Returning data to caller...");
}
public String getResponseMsg(){
return strResponseMsg;
}
}

Categories

Resources