Blank/black screen on app startup due data downloading? - android

The app i'm developing downloads a JSON file from remote address at every startup and then it parses the JSON Object and copies data to SQLite on the phone.
This operation is the cause for which the app hangs for some seconds on every startup showing blank screen (or sometime blank and then black screen), in fact if i tried to disable this part of code the app starts quickly, with no hang.
So, how could i do it better?
Here is the code (DataHandler class) related to file download, parsing and writing to local SQLite db:
public class DataHandler {
public DataHandler() {
}
public int storeData(Database db, int num) throws JSONException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.example.com/data.json");
request.addHeader("Cache-Control", "no-cache");
long id = -1;
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStreamReader in = new InputStreamReader(entity.getContent());
BufferedReader reader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=reader.readLine()) != null) {
stringBuilder.append(line);
}
JSONArray jsonArray = new JSONArray(stringBuilder.toString());
SQLiteDatabase dbWrite = db.getWritableDatabase();
ContentValues values = new ContentValues();
if (jsonArray.length() == num && num != 0)
return num;
SQLiteDatabase dbread = db.getReadableDatabase();
dbread.delete("mytable", "1", null);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = (JSONObject) jsonArray.getJSONObject(i);
values.put("_id", jObj.optString("id").toString());
values.put("city", jObj.optString("city").toString());
values.put("country",jObj.optString("country").toString());
values.put("addr", jObj.optString("addr").toString());
values.put("title", jObj.optString("title").toString());
values.put("lon", jObj.optString("lon").toString());
values.put("email", jObj.optString("email").toString());
values.put("phone", jObj.optString("phone").toString());
values.put("web", jObj.optString("web").toString());
values.put("lat", jObj.optString("lat").toString());
values.put("desc", jObj.optString("desc").toString());
values.put("icon", jObj.optString("icon").toString());
values.put("category", jObj.optString("category").toString());
id = dbWrite.insert("merchants", null, values);
}
num = jsonArray.length();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (id > 0)
return num;
else
return -1;
}
}

You should probably to the download and parsing in the background and display some kind of splashscreen with progress information in the meantime.
To avoid an annoying splash screen, you could also cache the data and display your app normally on startup, and only refresh the data once the bakground update is finished.
There are several options to do the download and parse operations in the background :
use an AsyncTask
use a service
I cannot say what's the best solution in your specific case, but I would recommend reading the Processes and Threads and service documentation.

Her goes your Async Task Class
class AsyncClass extends AsyncTask<String,Void,String>
{
int result;
Context context;
ProgressDialog bar;
AsynclassListener<String> listener;
public AsyncClass(Context context, AsynclassListener listener) {//add more parameter as your method body has (i.e Database db, int num) . Don't forget to initialize them.
this.context=context;
this.listener=listener;
bar = new ProgressDialog(context);
bar.setIndeterminate(false);
//make your progressBar here I have just given a simple example for above PB there are more parameters to set.
}
protected String doInBackground(String... Param){
try{
result = storeData();//call your method here
}catch(Exception e){
// Do something when crash
}
return ""+result;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
bar.show();// By the time your data fetching and parsing will go on you this progress bar will be visible.
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
bar.dismiss();//As soon as the work is complete the this method is called.
listener.onTaskComplete(""+result);
/**
* In your case you can later typecast back in integer once you recieve the result.
* this listener will post the result to your main activity.
*/
}
}
Here is your Interface
public interface AsynclassListener<T>{
public void onTaskComplete(T result);
}
Now Let your Activity (Splash Class) implement the interface
This will implement the method as :
#Override
public void onTaskComplete(String result) {
// here the asynclass will post the result as 1 or -1 whatever you want.
//After that you may proceed with your next part i.e switching to next activity or so.
}
Edit: I forgot to mention about how this will be called :
new AsyncClass(getApplicationContext(), this).execute("");// here you have to enter the database and other parameter values that will be required to run the method. Change it accordingly.
As you can see here in your method you are fetching the data from net and parsing also :
There is again a second approach in which you can call the network cal in a separate thread and later the parsing can be done further on UIthread.
Also read about the Async Task Class so as to know about the arguments and the working of class.

Related

While sending Spinner Value to php file first time only its working

I want to pass the Spinner value to php and get some result and display into my TextView. when i use Toast to display the Selected value its working perfect.but while pass the value to the php file i am struck. I tried some ways. can some to fix my problem.
java file:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); //<< this for hide title bar
setContentView(R.layout.sales_order);
fg.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
if(goods_name1.getSelectedItem() !=null && goods_name1.getSelectedItem() !=""){
// WebServer Request URL
String serverURL = "http://IP/fs/getProductOneStock.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Spinner1: unselected");
}
});
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Sales_Order.this);
String data ="";
int sizeData = 0;
TextView pro_stock1 = (TextView)findViewById(R.id.tv_stock1);
Spinner fgStock = (Spinner)findViewById(R.id.spinner1);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8") + "="+fgStock.getSelectedItem();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
pro_stock1.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
pro_stock1.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Finish_goods_mas");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String Stock1 = jsonChildNode.optString("Finish_goods_mas").toString();
OutputData += Stock1;
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
my php file
<?php
require "db_config.php";
$Goods_name=$_POST['Goods_name'];
$sql = "select goods_min_level from Finish_goods_mas where Goods_name='".$Goods_name."'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
//echo $row['cus_id']."<br />";
$json['Finish_goods_mas'][]=$row;
}
sqlsrv_free_stmt( $stmt);
echo json_encode($json);
?>
after make changes of doInBackground and onPreExecute() the Spinner value not pass to php file also i cannot get back result from php
When an asynchronous task is executed, the task goes through 4 steps:
1.onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
so textView.setText(strOrderNo); do it in onPostExecute(Result) override method

Checking the AsyncTask status seems not working correctly (log doesn't appear on log cat)

I'm trying to see how works an Asynctask class in android. In particular i want reveal in real time the status of the class for see when it is running and when it has finished. For do this, i have created a class that extend the main activity and another class that is the asynctaks class.
This is my main class:
public class PhotoManagement extends Activity{
private String numberOfSelectedPhotos;
private Bitmap currentImage;
private String initConfiguration = "http://www.something.com";
private String response;
private ArrayList<String> formatPhotoList = new ArrayList<String>(); //create a list that will contains the available format of the photos downloaded from the server
private ArrayList<String> pricePhotoList = new ArrayList<String>(); //create a list that will contains the available price for each format of the photos
DownloadWebPageTask webPage = new DownloadWebPageTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
if(webPage.getStatus() == AsyncTask.Status.PENDING){
Log.i("STATUS","PENDING");
}
if(webPage.getStatus() == AsyncTask.Status.RUNNING){
Log.i("","RUNNING");
}
if(webPage.getStatus() == AsyncTask.Status.FINISHED){
Log.i("","FINISHED");
}
}
}
As you can see i want only see the passages of the status with a simple log.
And here there is the asynctask class.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient(); //create a new http client
HttpGet httpGet = new HttpGet(url); //create a new http request passing a valid url
try {
HttpResponse execute = client.execute(httpGet); //try to execute the http get request
InputStream content = execute.getEntity().getContent(); //prepare the input stream to read the bytes of the request
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s; //until is present a line to read, the response variable store the value of the lines
}
} catch (Exception e) {
Log.i("MyApp", "Download Exception : " + e.toString()); //Print the error if something goes wrong
}
}
return response; //return the response
}
#Override
protected void onPostExecute(String result) {
result = doInBackground(initConfiguration); //take the result from the DownloadWebPageTask class
result = result.replace("null", "");
Log.i("RESULT",""+result);
//find the price and format value from the result using XmlPullParser
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( result ) );
int attributeNumber = xpp.getAttributeCount();
int eventType = xpp.getEventType();
String currentTag = null;
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
if (currentTag.equals("product")){
xpp.getAttributeValue(null, "name");
formatPhotoList.add(xpp.getAttributeValue(null, "name"));
Log.i("FORMAT PHOTO",""+xpp.getAttributeValue(null, "name"));
}
}
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.i("","ERROR XML PULL PARSER");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("","ERROR IOEXCEPTION");
}
}
}
}
As you can see i have implemented also the method onPostExecute that should be called when the asynctask method has finished to execute the instructions right?
So at this point i don't understand why my log RUNNING and my log FINISHED never appear on the log cat.
What i'm doing wrong?
I'm tried to follow this topic Android, AsyncTask, check status? but in my case it isn't working.
Thanks
Problem :
You are creating object like
DownloadWebPageTask webPage = new DownloadWebPageTask();
But you are calling asynctask on different object,
new DownloadWebPageTask().execute(initConfiguration);
Solution :
It should be like
webPage.execute(initConfiguration);
#Override
protected void onResume(){
super.onResume();
new DownloadWebPageTask().execute(initConfiguration);
here do like this
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
You didn't implement webPage.execute(), add it
Most probably the task hasn't finished or even started yet. As you probably know the AsyncTask is doing it's (background) work on a different thread, so your onResume is running in parallel with it. You can either use the task's get() method to wait for it to finish and get the result of the doInBackground() method and then query for it's status or notify your activity from the task's onPostExecute() method to let it know (and log) that it has finished. I don't recommend you the first option because it will actually block the UI thread and will make your usage of AsyncTask pointless.

Multiple Async Tasks for post in same activity

i wrote those threads:
How to manage multiple Async Tasks efficiently in Android
Running multiple AsyncTasks at the same time -- not possible?
but didnt find answer for my question, maybe someone can help..
I have android app which makes Login POST and getting json response,
if the Json is OK i need to POST another data to get another response.
i have extends Async Class which doing the post to the URL:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
private HashMap<String, String> mData = null;
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
return null;
}
return str;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray Loginjson = new JSONArray(result);
strStt = Loginjson.getJSONObject(0).getJSONObject("fields").getString("status");
if (strStt.equals("ERR")) {
ErrorMsg("Authentication failed");
} else if (strStt.equals("OK")) {
ErrorMsg("Login OK!!!");
ClientPage();
} else {
ErrorMsg("Connection Error");
}
} catch (JSONException e) {
ErrorMsg("Connection Error");
}
}
}
Now - i need to get another POST if the status is Error. do i need to make another Async class? with the same all procedures ? the issue is only the onPostExecute part is different.. actually the "doInBackground" will be always the same..
any idea how can i easily do multiple posts in the same activity?
Firstly, since your doInBackground() code will always stay the same, I recommend you move it into a general utility class.
Beyond that, you can go one of two ways:
Create a new AsyncTask for each type of request that can call your utility class, and have its own onPostExecute()
Create one AsyncTask that has a flag in it, which can be checked in the onPostExecute() method to see what code needs to be executed there. You will have to pass the flag in in the constructor or as a parameter in execute.
You can use a parameter at AsyncHttpPost constructor/execute or global variable to indicate if it is first or second POST (by other words - a flag). Then just create and execute another instance of AsyncHttpPost in onPostExecute (only if parameter/variable is set as "first POST").

Passing functions into a global AsyncTask Android

I'm trying to create a global actions file in which i can call certain functions globally anywhere within the app. so far i have got it working with functions etc but now what i'm wanting to do is put a standard AsyncTask into my global actions and pass it functions/voids from my Activity so i'd want to pass it a function to run in background and a function to run once finished. does anyone know how do this? and also advise me on running multiple functions on a background thread do i create one AsyncTask and feed in multiple functions or do i create multiple AsyncTasks?
heres an example of what i have managed to do globally so far and how i'm currently implementing my Asynctask. Just to reiterate i'm trying to move the asynctask into a global actions and make it as reusuable as possible
in my Global Actions im creating a function that formulates a URL and sends post variables to that url which then feedsback a JSON response. then in my Activity i have created a function to both call that request and then Log the response
My Global Actions
public final static JSONObject startAPICallRequest(Context activityContext, String requestReference, String callLocation, Map<String, String> postVarsMap, Map<String, String> getVarsMap){
long unixTimeStamp = System.currentTimeMillis() / 1000L;
StringBuilder extraGetVarsString = new StringBuilder();
if(getVarsMap != null){
Map<String, String> map = (Map)getVarsMap;
for (Entry<String, String> entry : map.entrySet()) {
extraGetVarsString.append("&" + entry.getKey() + "=" + entry.getValue());
extraGetVarsString.toString();
}
}
String appVersion = null;
try {
appVersion = activityContext.getPackageManager().getPackageInfo(activityContext.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
appVersion = activityContext.getResources().getString(R.string.appVersion);
}
String getVarsString = "?timestamp=" + unixTimeStamp + "&app_version=" + appVersion + extraGetVarsString;
String apiLocation = activityContext.getResources().getString(R.string.apiLocation);
String fullAPIURL = apiLocation + callLocation + getVarsString;
Log.v("globals", "fullAPIURL=" + fullAPIURL);
String api_key = activityContext.getResources().getString(R.string.apiKey);
String api_user = activityContext.getResources().getString(R.string.apiUser);
String request_token = returnSHAFromString(api_key, fullAPIURL);
String device_id = returnStringFromPreference(activityContext,"device_id");
String user_token = returnStringFromPreference(activityContext,"user_token");
List<NameValuePair> postVarsList = new ArrayList<NameValuePair>();
postVarsList.add(new BasicNameValuePair("request_token", request_token));
postVarsList.add(new BasicNameValuePair("api_user", api_user));
postVarsList.add(new BasicNameValuePair("device_id", device_id));
postVarsList.add(new BasicNameValuePair("user_token", user_token));
if(postVarsMap != null){
Map<String, String> map = (Map)postVarsMap;
for (Entry<String, String> entry : map.entrySet()) {
postVarsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
JSONObject responseJSON = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(fullAPIURL);
post.setEntity (new UrlEncodedFormEntity(postVarsList));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResponse = reader.readLine();
Log.v("globals", "postList =" + postVarsList );
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseJSON;
}
MY Activity
public void apiCall(){
responseJSON = GlobalActions.startAPICallRequest(this, "login", "my-network/", null, null);
}
public class PostTask extends AsyncTask<Void, String, Boolean> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
apiCall();
boolean result = false;
publishProgress("progress");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
checkLoginData();
}
}
public void checkLoginData(){
Log.v("IntroLoader", "responseJSON = " + responseJSON);
Intent register = new Intent(getApplicationContext(), LoginForm.class);
startActivity(register);
}
Using AsyncTask for calling REST API methods is not really correct approach. Your code has 2 problems:
There is no guarantee that your API call will be finished when Activity is closed because process can be killed
You have memory leak because PostTask can hold Activity reference even while Activity can be already destroyed
Consider using IntentService for making background requests and e. g. ResultReceiver for handling results in your Activity.
It looks like you need a Handler and a Looper. You will be able to post() and postDelayed(). http://developer.android.com/reference/android/os/Handler.html
See also:
Is AsyncTask really conceptually flawed or am I just missing something?
I'm no Java expert but I don't think you pass functions around in Java. To simplify the matter, what you want to do is call a function in your Activity class when AsyncTask is complete?

Getting a hold of doInBackground(String... params)

In some way I do understand the Handler, but I'm not sure what to do with the params and how to let the code wait until the job is done in the background. I want the UI to be normally working and in the background I want to do an exchange rate calculation.
I have the following:
I call new getOnlineExchangeRate().execute(""); //Get Exchange Rate in BG
After that I want to have a result=amount*exchangerate, but the code is not waiting for the result.
Can somebody tell me how the calculation waits till we have an exchangerate. Do I have to send some params and how would that look?
.
.
.
.
.
public double getYahooExchangeRate(String ER){
double exchangerate=0;
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+ER+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
//s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
exchangerate=Double.parseDouble(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ALS.Toast(myContext.getString(R.string.conversionerror), false);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ALS.Toast(myContext.getString(R.string.conversionerror), false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ALS.Toast(myContext.getString(R.string.conversionerror), false);
}
return exchangerate;
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class getOnlineExchangeRate extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
ALS.Toast(myContext.getString(R.string.exchangeratesupdated), true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// perform long running operation operation
getYahooExchangeRate(USDEUR);
return null;
}
I think your problem is in this line:
#Override
protected String doInBackground(String... params) {
getYahooExchangeRate(USDEUR);
return null;
You want to return the result of getYahooExchangeRate and not null :)
So change this and the return-value should be a double. So change this to:
#Override
protected Double doInBackground(String... params){
return getYahooExchangeRate(USDEUR);
}
You also have to change your class header:
public class getOnlineExchangeRate extends AsyncTask<String, Void, Double> {
AsyncTask<Params, Progress, Result>
The generic part tells the AsyncTask which Informationstypes are handled.
The first is the type for the params of doInBackground(Params... )
The second is the type of the progress-Information
The last explains which type is returned by doInBackground(), so it changes the method-header from
protected Result doInBackground(Params... params){ };
to
protected double doInBackground(Params... params){};
To bring back the Result i would use and Observer oder Callback-Pattern.
Edit: changed double to Double, because primitives cannot be used for Generics.
the code is not waiting for the result. Can somebody tell me how the calculation waits till we have an exchangerate. Do I have to send some params and how would that look?
You could use AsyncTask#get() to force the code to wait, but this blocks the main thread until the AsyncTask completes which defies the purpose of using an asynchronous task.
It is best to design your Activity to proceed without the exchange rate, just like my mail app loads allowing me to compose messages and read old messages while the new messages are being fetched. When the asynchronous data loads then you can update your UI with the new information. (I believe this is what you are trying to do.)
To add on to user1885518 code, you should use your AsyncTask as a subclass in your Activity like this:
public class MainActivity extends Activity {
private class getOnlineExchangeRate extends AsyncTask<Void, Void, Double> {
#Override
protected Double doInBackground(Void... params) {
return getYahooExchangeRate(params[0]);
}
#Override
protected void onPostExecute(Double rate) {
// Do something with rate
}
}
...
}
Once you know which exchange rate you want, call:
new getOnlineExchangeRate().execute(USDEUR); //Get Exchange Rate in BG
Now when you have gotten the rate from online, the code calls onPostExecute() with your desired rate. Inside on onPostExceute() you can call whatever method you want in your ACtivity to calculate result=amount*exchangerate and display result wherever it is appropriate.

Categories

Resources