I am beginner in Android and I need some help. So, I have a procedure with sub-procedures inside. How can I finish one before starting a new one. Here is a code to better understand:
public void onCellLocationChanged(CellLocation lokacija) {
super.onCellLocationChanged(lokacija);
location = (GsmCellLocation) Phone.getCellLocation();
textCellId.setText(String.valueOf(location.getCid() % 65536));
textCellLac.setText(String.valueOf(location.getLac()));
String JSON_URL_string=JSON_URL + "?cellid=" + String.valueOf(location.getCid()%65636);
getJSON(JSON_URL_string);
myJSONString = textCellNameSakriven.getText().toString();
ParseJSON(myJSONString);
}
Problem is that myJSONString is empty, cause textCEllNameSkriven is also empty. That textView textCellNameSkriven is made when getJSON(JSON_URL_string) is finished. If I run debugger and go step by step, app goes directly from getJSON(JSON_URL_string) row to the next one and the next etc
Edit: Maybe the problem is that onPostExecute is not finished before starting ParseJSON. Here is also a code for getJSON:
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textCellNameSakriven.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
Since you are running a async task it practically runs on a different thread, so your getJson method need not wait for post execute and can return after starting the async task, so you can never be sure in this way that parseJson gets executed after textView is populated. You are running into classic race condition issue.
Your issue could be easily solved, if you have a callback which is called after postExecute is done, and you can handle parseJson there
So, something simple like , create interface MyCallback
public interface MyCallback {
public OnReadJsonDone();
}
Let your activity implement this MyCallback
public MainActivity implements MyCallback
{
...........
#Override
public OnReadJsonDone(){
parseJson();
}
Now change signature of getJson to
getJSON(string json, final MyCallback callback) {
Now in onpostexecute
//call OnReadJsonDone
callback.OnReadJsonDone()
So, all you now need is while calling getJSon pass this as second param
getJSON(JSON_URL_string,this);
Haven't tested this but you get the idea
Related
I'm a new Android developer and I have a question. After users login, I need to get some data from an external URL and display them on one of my activities. But I've been reading and found this:
When your activity comes back to the foreground from the stopped state, it receives a call to onRestart(). The system also calls the
onStart() method, which happens every time your activity becomes
visible (whether being restarted or created for the first time).
And this
Caution: Your activity will be destroyed and recreated each time the
user rotates the screen. When the screen changes orientation, the
system destroys and recreates the foreground activity because the
screen configuration has changed and your activity might need to load
alternative resources (such as the layout).
Here and here.
So, it looks like I should not get the data I need on the onCreate method. Then where? In a previous activity and saving the data in the phone memory? That doesn't sound good to me.
Thanks in advance.
edit
I'm using AsyncTask as suggested, but everytime I switch the phone orientation, onCreate method is called.
My MainActivity:
public class MainActivity extends Activity implements AsyncResponse {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadJSONTask jsonTask = new ReadJSONTask();
jsonTask.delegate = this;
jsonTask.execute("http://www.myweb.com/myscript.php");
}
#Override
public void processFinish(String output) {
Toast.makeText(getApplicationContext(), output, Toast.LENGTH_LONG).show();
}
}
ReadJSONTask class:
public class ReadJSONTask extends AsyncTask<String, Void, String> {
public AsyncResponse delegate = null;
public String res;
public Boolean finish = false;
#Override
protected String doInBackground(String... url) {
String response = null;
String adres = url[0];
URL url_HTTPRequest = null;
try {
url_HTTPRequest = new URL(adres);
response = transfer(url_HTTPRequest);
} catch (MalformedURLException e) {
Log.e("URL ERROR", "MalformedURLException");
} catch (Exception e) {
Log.e("URL ERROR", "exc");
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("mylog", "result= " + result);
delegate.processFinish(result);
}
public String transfer(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// inputStream = url.openStream();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = bin.readLine();
StringBuffer sb = new StringBuffer();
while (line != null) {
sb.append(line);
sb.append("\r\n");
line = bin.readLine();
}
inputStream.close();
return sb.toString();
}
}
And the interface is just:
public interface AsyncResponse {
void processFinish(String output);
}
As I said, everytime I switch the phone orientation all the async process is performed (and the Toast shows up). That's exactly what I wanted to avoid in the first place.
you dont need Stop/Resume activities you can use AsyncTask class and doInBackGround method when get data from external url and show to user process Dialog for waiting
Never ever try to get the data from URL on Main thread. Always use AsyncTask for getting the data from URL
You can write in the same activity, but not in the main thread. Maybe AsyncTask will help.
I am new to android development. I have a AsyncTask function in my application. Calling http request from all activities. Now in each activity I am using the following class to connect to server, in some activities I even called twice !!.
Basically I am a web developer and in such cases we use a single class which can be accessed from entire application(web) and use the common function to do the same activity. The only difference is input and out put will be changed.
My doubt is in this case can I use ( convert) this to such a function or class ?
My assume is
Create an android class ( which can be accessed from all the activities )
Just make the JSON string we need with specific server ( for process in server )
Just pass the created json to the created class and then made the http connect )
Process the returned data from server
Pass that to the corresponding activity
So that I can use the same function for all the activities and I can avoid duplicate query
Can I convert this code to such a manner ?
My Code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
LogIN loginUser = new LogIN();
LoginUser.execute("");
}
private class LogIN extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
String path = "http://www.domain_name.com/app/checkSession.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("access_token", "123456");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("result");
if(passedStringValue.equals("1")){
flags=1;
//Log.v("TAGG", "Success");
}
else {
flags=0;
//Log.v("TAGG", "Failed !");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialogue("Login Processing", "Loading");
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
if(flags.equals(1)){
Itent homepage = new Intent(MainActivity.this, RegisterDevice.class);
startActivity(homepage);
finish();
}
else {
Intent homepage = new Intent(MainActivity.this, LoginActivity.class);
startActivity(homepage);
finish();
}
super.onPostExecute(result);
}
}
}
Please any one help/advise
Thanks in advance
Extract your class to a different file and make it public
public class LogIN extends AsyncTask<Object, Integer, String> {
private ILoginListener listener;
#Override
protected String doInBackground(Object... arg0) {
try {
this.listener = (ILoginListener) arg0[0];
//You can also send the url in the obj array
String theUrl = (String) arg0[1];
String path = "http://www.domain_name.com/app/checkSession.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("access_token", "123456");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("result");
if(passedStringValue.equals("1")){
flags=1;
//Log.v("TAGG", "Success");
}
else {
flags=0;
//Log.v("TAGG", "Failed !");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialogue("Login Processing", "Loading");
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
listener.logInSessionCheckListener(flag.equals(1));
super.onPostExecute(result);
}
}
Regarding your other question, I normally have an interface for that, something like this:
public interface ILoginListener {
public void logInSessionCheckListener(SomeNeeded Value);
}
I implement the interface in the class where i need the postExecute result and in the overriden method you can to what you want with the result of your task.
Your class where you user it will look something like this:
public class SomeClass implements ILoginListener {
//Call it like this from any class:
LogIN loginTask = new LogIn();
Object[] someParams = new Object[2];
//add the listener
someParams[0] = SomeClass.this
//add the url
someParams[1] = someUrlString;
loginTask.execute(someParams);
#Override
public void logInSessionCheckListener(SomeNeeded Value){
//do Stuff with your results
}
}
You can do it like make separate class for everything inside doInBackground() method and called it in all activity with passing parameter to
LogIN loginUser = new LogIN(yourparameter);
LoginUser.execute("");
and check parameter in AsyncTask Class constructor like
public LogIN(Myparameter){
// Your data
}
On the other hand you can use this great framework for android : android-query and the async API.
It allows you to perform asynchroneous network tasks from activities and easily work with the results of your requests.
You should use interfaces to implement a callback to your ui activity.
Have a look at this thread, it might be useful:
android asynctask sending callbacks to ui
And your asyntask class should be in a seperate java file with public acces.
And to pass the parametres you simply have to call a new LogIN async Task like this:
new LogIN().execute(urls);
Hope it helped :)
Remember that you can never know when AsyncTask is going to finish. So if you're using this to authenticate users and then perform task X, task Y, or task Z,
then maybe it's better to create a Login helper class
public class LoginHelper {
public boolean login(params){
// Authenticate user and return true if successfull
}
}
and then have in your Activity classes
private class X extends AsyncTask {
#Override
protected String doInBackground(String... sUrl) {
...
boolean authenticated = LoginHelper.login(params...);
if(authenticated == true) {
// Perform task X here...
} else {
// Inform the user that the login failed...
}
}
First of all
You have to pass the context in which you are calling your async task
Sample Code
Login loginTask = new Long(getContext());
loginTask.execute();
You class Login should have a constructor that accepts the Context
Sample Code
public class Login extends AsyncTask<String, Integer, String> {
private Context mContext ;
private ProgressDialog pd;
private Handler handler = new Handler { };
public Login (Context context){
mContext = context ;
}
.....
Then make sure to create the method showDialog inside Login class to show the progress dialog
Note
You can add what ever Constructors you need to customize the behaviour of your Login task
for example : pass boolean parameter to tell that the Login Task is cancelable....
Hope that help you :)
I'm using AsyncTask and all the examples I found about an AsyncTask is inside an activity.
I'm trying to make an application with a lot of activity and some must download a HTML page. I don't really want to copy-paste the same code all the time in every activity. I find this to be dirty.
So I need to do it as a special class Async HttpGet and pass the function with an argument. I will execute after the doinbackground (different for every activity).
Is this possible or do I need to copy-paste my code in every activity and change the do in background to do what I need after downloading the HTML page?
Here's an AsyncTask that will download data from a url and update the calling activity.
Make sure your calling activity implements the interface DownloadDataTask.DownloadCompleteHandler and that it passes itself as parameter to the DownloadDataTask constructor.
public class DownloadDataTask extends AsyncTask<String, Integer, String> {
public interface DownloadCompleteHandler
{
public void handleDownloadComplete(String result);
}
private DownloadCompleteHandler handler;
private String url;
public DownloadDataTask(DownloadCompleteHandler handler, String url) {
this.handler = handler;
this.url = url;
}
/* AsyncTask methods */
#Override
protected String[] doInBackground(String... empty) {
return downloadData(url);
}
#Override
protected void onPostExecute(String result) {
handler.handleDownloadComplete(result);
}
/* Downloading Data */
private String downloadData(String urlStr) {
InputStream is = null;
String result = new String();
try {
is = getInputStream(urlStr);
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
} catch (MalformedURLException ex) {
return "Malformed URL: " + ex.getMessage();
} catch (SocketTimeoutException ex) {
return "Connection timed out";
} catch (IOException ex) {
return "IOException: " + ex.getMessage();
}
finally {
if (is != null)
is.close();
}
return result;
}
private InputStream getInputStream(String urlStr) throws IOException
{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
return conn.getInputStream();
}
}
Just create a class that extends AsyncTask that you can reuse.
public abstract class MyAsyncTask extends AsyncTask<Void, Void, String> {
private final String url;
public MyAsyncTask(String url){
this.url = url;
}
#Override
protected String doInBackground(Void... params){
// get data from url.
return null;
}
}
And then to call it, just create an instance of that class.
new MyAsyncTask("http://www.google.com"){
public void onPostExecute(String result){
// update your views.
}
}.execute();
Well what you can do is create an listener for AsyncTask completion, which listens when your AsyncTask is completed and return you the data. I had created an example to execute database queries in background thread and then returning the data to the Activity. Just check it and you can create similar AsyncTask for your problem.
UPDATE:-
Also you can use BroadCastReceiver as a Listener when your AsyncTask is completed and return the value.
Interface is another option for creating a Listener for AsyncTask.
Here is a demo from my github
I'm trying to use the HTTPClient to get the html code of a website using an AsyncTask and passing back the code to my main Activity.
I used this code in order to (try to) do that :
public class AsyncTaskGet extends AsyncTask<String, String, String>{
String result;
InputStream in;
protected String doInBackground(String... params) {
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet("http://www.google.fr");
HttpResponse response = httpClient.execute(httpRequest);
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(null, result), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
if (response != null) {
in = response.getEntity().getContent();
}
in.close();
result = sb.toString();
}catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}catch(IOException e){
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
//Here is one of my problem, I don't know how to get the returned value result as a string.
}
}
This is my AsyncTaskGet, since I tried lots of fruitless attempts, I erased all my code in the main activity except this part.
new AsyncTaskGet().execute();
So basically, What i'd like to do is getting the result back on my main activity as a string to display it in a TextView.
For now I want my app to be simple so I can understand the basics of using AsyncTasks, I didn't check for internet conectivity or stuff like that, I add the permission on the manifest to use internet (obviously
(Please be a little indulgent since it is one of my first apps)
One last thing, please excuse my poor english, i'm unfortunately not a native english speaker as you must have seen.
In advance, thanks a lot !
Sincerely :)
The easiest thing is to pass the calling activity via a constructor to your AsyncTask and create a method that will take the result as a parameter in the activity itself.
private Activity mActivity;
public AsyncTaskGet(Activity activity) {
mActivity = activity;
}
protected void onPostExecute(String result) {
mActivity.takeItBack(result);
}
There are some limitations: the current code just works with a 1 to 1 relationship between AsyncTask and Activity, means the private member variable type must be the activity from which you call it. If you don't want that you need to implement an interface:
// interface
public interface AsyncTaskCallback {
void takeItBack(String result);
}
// activity
public MyActivity implements AsyncTaskCallback {
#Override
public void takeItBack(String result) {
// do something
}
}
// AsyncTask
public class AsyncTaskGet extends AsyncTask<String, String, String> {
private AsyncTaskCallback mCallback;
public AsyncTaskGet(AsyncTaskCallback callback) {
mCallback= callback;
}
protected void onPostExecute(String result) {
mCallback.takeItBack(result);
}
}
You are already passing result to onPostExecute() as a String. If your AsyncTask is an inner class of your Activity then you can set result to a field variable in your Activity. Otherwise, you can call a function in your Activity from onPostExecute() to do what you want with the data.
Also, your poor English is really not bad at all :)
I'm having a really tough nut to crack with a bug. Api being used is v11, honeycomb 3.0
I have a asynctask inside a fragment downloading from a XML api with basic authentication. It works perfectly even when i change the parameters from the fragment within with the edittexts etc. But when i try to mutate a autocompletetextview from outside the fragment, suddenly i get a "no element at line 1. column 0" exception. I tried the androidhttpclient, fiddled with systemprop(http.keepalive), and completly narrowed it down to this method.
public void setStations(String a, String b){
AutoCompleteTextView fromET = (AutoCompleteTextView ) getView().findViewById(R.id.from);
fromET.setText(a);
AutoCompleteTextView toET = (AutoCompleteTextView) getView().findViewById(R.id.to);
toET.setText(b);
}
When this method executes it botches up my downloadtask somewhere. If i manually edit these textview it works fine.
class LoadDataTask extends AsyncTask<String, Integer, ArrayList<Reisadvies>> {
private Exception ex;
private ProgressDialog pd;
protected void onPreExecute() {
//loadprogressdialog
}
protected ArrayList<Reisadvies> doInBackground(String... params) {
try{
ex = null;
return new APIreader().getRA(params[0], params[1], params[2],params[3],params[4],params[5], params[6]);
}catch (Exception e){
cancel(true);
pd.dismiss();
ex = e;
return null;
}
}
protected void onPostExecute(ArrayList<Reisadvies> ra){
//send list to activity
}
protected void onCancelled() {
super.onCancelled();
showError(ex);
}
}
};
public ArrayList<Reisadvies> getRA(String fromStation, String toStation, String viaStation, String dateTime, String departure, String hslAllowed, String yearCard) throws APIException{
try{
String uri = url(fromStation, toStation, viaStation, dateTime, departure, hslAllowed,yearCard);
URL url = new URL(uri);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if (!url.getHost().equals(uc.getURL().getHost())) {
throw new APIException("HotspotForwadingActive");
}
String basicAuth = "Basic " + "username:password"; //base64 encoded
uc.setRequestProperty ("Authorization", basicAuth);
uc.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
try{
return (ArrayList<Reisadvies>) new XMLParser().parseRP(in);
}finally{
uc.connect();
}
}catch (Exception e){
e.printStackTrace();
throw new APIException(e.getMessage());
}
}
I think there is a problem in doInBackground:
pd.dismiss();
You can do operations on UI element only in UI Thread. It means that you can do this in onPostExecute method, or, if you want, you can use runOnUiThread method:
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
I hope this is helpful...
You are right about that too, but the problem was different. Just found out that it was to urlencoding. Should have figured that out right away but was throw off by the fact that it worked sometimes with a space in it :)