progress dialog not working - java

I am trying to display a progress dialog in java 'A'. At the moment that am calling from 'A' a class from java 'B' which the certain java it download data from a webservice and save the data to a file. The progress dialog it does not show. The code I am using is:
ProgressDlg= ProgressDialog.show(Doctor.this, "","Loading. Please wait...", true);
String time_batch=mDataIntent.getExtras().getString("TIME_BATCH");
String patientid=mDataIntent.getExtras().getString("PatientId")
mGetHeartRate = new GetHeartRate(Doctor.this, mHandler);
mgetEcgAnalized = new getEcgAnalized(Doctor.this, mHandler);
mGetHeartRate.getHeart(patientid,time_batch);
mgetEcgAnalized.getECG(patientid, time_batch, "I".toString());
ProgressDlg.dismiss();

Are you executing the ProgressDialog in a AsyncTask? Something like this:
public class ExampleTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progressDlg;
private Context context;
private Handler progressHandler;
public ExampleTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
progressHandler = new Handler();
}
#Override
protected String doInBackground(String... params) {
//to do
}
#Override
protected void onPostExecute(String filePath) {
if (progressDlg != null) {
progressDlg.dismiss();
progressDlg = null;
}
}
#Override
protected void onProgressUpdate(final Integer... values) {
final int progress = values[0] / 1000;
if (progressDlg == null) {
progressHandler.post(new Runnable() {
#Override
public void run() {
final int max = values[1] / 1000;
progressDlg = new ProgressDialog(context);
progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDlg.setMessage("Message");
progressDlg.setMax(max);
progressDlg.show();
}
});
} else {
progressDlg.setProgress(progress);
}
}
}

This works for me.
ProgressDialog dialog = ProgressDialog.show(activity, "", PopUpHelper.LOADING, true);
dialog.show();

Related

How to properly pass context to AsyncTask and then to another class?

I'm working on app that will use biometric as an option to login. Before I use the actual biometric prompt I need to check one thing from server - I use AsyncTask to do it. So, to sum up - I invoke AsyncTask from Parent Activity (login.java), and then AsyncTask uses biometricUtils.java class, that makes biometric prompt. The point is, I keep passing null instead of context to biometricUtils.java:
Attempt to invoke virtual method 'java.util.concurrent.Executor android.content.Context.getMainExecutor()' on a null object reference at biometricUtils.<init>(biometricUtils.java:34)
I have no idea to pass the context correctly.
Here's my code:
login.java
public class login extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Bundle bundle = getIntent().getExtras();
final boolean flag = false;
final String androidID = bundle.getString("androidID");
final Activity thisActivity = this;
final Context context = getApplicationContext();
// login using biometrics
Button btnBiometricLogin = findViewById(R.id.btnBiometricLogin);
btnBiometricLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAndroidID async = new checkAndroidID(context);
async.getParentActivity(thisActivity);
async.setFlag(flag);
async.execute(androidID);
}
});
}
}
checkAndroidID.java
public class checkAndroidID extends AsyncTask <String, Void, String> {
openHTTP openHTTP = new openHTTP();
requestHTTP requests = new requestHTTP();
Activity parentActivity;
private WeakReference<Context> contextRef;
Boolean flag;
public checkAndroidID(Context context){
contextRef = new WeakReference<>(context);
}
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
public void setFlag (Boolean flag){
this.flag = flag;
}
#Override
protected String doInBackground(String... strings) {
try {
HttpURLConnection httpConn = openHTTP.prepareConnection("url");
String json = "{ \"androidID\": \"" + strings[0] + "\" }";
requests.sendData(json, httpConn);
return requests.receiveData(httpConn);
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
String[] result = s.split(";");
Context ctx = contextRef.get();
if (result[0].equals("TRUE")) flag = true;
if (!flag) Toast.makeText(parentActivity, "Biometric authentication is now unavailable." +
" Please login using username and password", Toast.LENGTH_SHORT).show();
else {
biometricUtils biometrics = new biometricUtils(ctx);
biometrics.getParentActivity(parentActivity);
biometrics.getUsername(result[1]);
biometrics.inovkeBiometricPrompt();
}
super.onPostExecute(s);
}
}
and biometricUtlis.java
public class biometricUtils {
Activity parentActivity;
String username;
Context context;
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
public void getUsername(String s){
this.username = s;
}
public biometricUtils(Context context){
this.context = context;
}
// creating a variable for our Executor
Executor executor = ContextCompat.getMainExecutor(context); // LINE 34
// this will give us result of AUTHENTICATION
final BiometricPrompt biometricPrompt = new BiometricPrompt((FragmentActivity) parentActivity, executor, new BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
}
// THIS METHOD IS CALLED WHEN AUTHENTICATION IS SUCCESS
#Override
public void onAuthenticationSucceeded(#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Intent intent = new Intent(parentActivity.getApplicationContext(), tmp.class);
intent.putExtra("username", username);
parentActivity.startActivity(intent);
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
});
// creating a variable for our promptInfo
// BIOMETRIC DIALOG
final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder().setTitle("Biometrical login")
.setDescription("Place your fingerprint on scanner to proceed").setNegativeButtonText("Cancel").build();
public void inovkeBiometricPrompt() {
biometricPrompt.authenticate(promptInfo);
}
}

Passing a variable between functions

I'm new to android studio and Java. My app uses jsoup to pass the contents of a website into an array where each element gets displayed on swipable flashcards (like tinder)
I've got a problem where my app crashes when I try to pass the result of the variable 'words' from onPostExecute() (line 123) to String num on line 49. I want to take the output of the function in onPostExcecute and set it as String num but I'm not sure how to do it.
public class AppHome extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
TextView texx;
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
String words;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_home);
texx= findViewById(R.id.text1);
new doit().execute();
String num = words;
String str[] = num.split(",");
final ArrayList al = new ArrayList<String>(Arrays.asList(str));
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al );
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
registerForContextMenu(flingContainer);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(AppHome.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(AppHome.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
}
public class doit extends AsyncTask<Void,Void,Void> {
//String words;
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words=doc.text();
}catch(Exception e){e.printStackTrace();}
return null;
}
#Override
public void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
}
public class doit extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... voids) {
String words = "";
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words = doc.text();
} catch(Exception e) {
e.printStackTrace();
}
return words;
}
#Override
public void onPostExecute(String words) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
It should be fine now.
The problem is, you are not returning anything from the doInBackground method and hence you are not getting anything in the onPostExecute function.
You might consider checking the documentation for AsyncTask here.
In doInBackgroud() return the string(make sure it never beacome null) you want to use it on PostExecute()
also changed the data type of Parameter in onPostExecute method
onPostExecute(String Strs)
Then pass it to supper.OnPostExecute().
then u can use it.

Keep UI responsive while fetch data from internet alternative of Handler postDelayed

I have a ArrayList that I fetch from internet. Now I am performing the list retrieval using Handler postdelayed. Like below in the onCreate of the activity.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
lis_dat.remove(lis_dat.size() - 1);
if (gri_not_lis) {
rv_3r_ada.notifyItemRemoved(lis_dat.size());
} else {
rv_3r_2c_ada.notifyItemRemoved(lis_dat.size());
}
List<String> lis_of_dat;
int cou = 0, pos = lis_dat.size();
String gen_sta, gen_end, gen_mon;
if (yea) {
String[] mon_sym = new DateFormatSymbols().getMonths();
lis_of_dat = Arrays.asList(mon_sym);
} else {
int how_man;
if (lis_is_new) {
how_man = 500;
} else {
how_man = 15;
}
if (day_in_bet(sta, end) <= how_man) {
gen_sta = sta;
gen_end = end;
} else {
gen_sta = sta;
Calendar cal = Calendar.getInstance();
cal.setTime(db_han.con_dat(sta));
cal.add(Calendar.DATE, how_man);
gen_end = USE_DAT.format(cal.getTime());
}
lis_of_dat = gen_dat_in_bet(gen_sta, gen_end);
}
for (String dat : lis_of_dat) {
if (yea) {
Date date = get_mon_dat(dat, YEA.format(db_han.con_dat(sta)));
gen_sta = get_mon_fir_or_las_dat(date, true);
gen_end = get_mon_fir_or_las_dat(date, false);
gen_mon = dat;
} else {
gen_sta = dat;
gen_end = null;
gen_mon = mon;
}
add_to_lis(gen_sta, gen_end, gen_mon, pos, gri_not_lis);
pos++;
}
pos_f[0] = pos;
cou_f[0] = cou;
is_loa = false;
}
}, 1000);
Now my question is this 1000 milliseconds here may vary in different devices. On whom the UI will stay frozen. So what's the alternative of this. Instead of waiting for 1 sec how can I wait till the UI loading is complete and then I do the retrieval?
I could use AsyncTask but then the task will stay running till the task is complete even if I go to another activity. but i don't need the task running after onPause is called. So how do I do it?
You can use AsyncTask which running in separate thread, your keeps UI responsive . You can cancel it in onPause of Activity by calling **asyncTaskRunner.cancel(true) **
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
return resp;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
You can save instance of handler and then remove all call backs in
onPause of the activity.
private Handler handler = new Handler();
handler.postDelayed(() -> {
// do you task here
},1000);
#Override
public void onPause() {
super.onPause();
handler.removeCallbacksAndMessages(null); // this is important
}
And if you want something which do not freeze UI without any delay,
there you go
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Executors.newSingleThreadExecutor().submit(() -> {
// Do you task here without any delay it will not freeze the UI
});
}
You can also try this,
class MyThread implements Runnable{
#Override
public void run() {
// Your Task Here, put your all calculations Here
}
}
and then in onCrate()
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new MyThread());
and then in onPause() or onDestory()
executor.shutdownNow();// this will stop the thread instantly

Implement AsyncTask when adding rows of data to multiple tables

I have created a screen that show a TextView and a ProgressBar. The ProgressBar represent to database creation and adding 1000++ data into SQLite using GSON. In order to achieve this, I have created three different files, LocalDBHelper (which is my db setup), GSONHandler (convert my JSON file into SQLite) and Loading (for my AsyncTask).
My problem is, that my ProgressBar is static, and it didn't show the progress of adding the data. I'm new to android development and clueless in proceeding with my code.
MainActivity.java
public class MainActivity extends AppCompatActivity implements Loading.LoadingTaskFinishedListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setupdb_delete);
LocalDBHelper mydb = LocalDBHelper.newInstance(this);
//check if db exist, delete db if exist
if (doesDatabaseExist(mydb.getDatabaseName()))
this.deleteDatabase(mydb.getDatabaseName());
ProgressBar progressBar = findViewById(R.id.progressBar);
new Loading(progressBar, this, this).execute("");
}
#Override
public void onTaskFinished() {
finish();
}
public boolean doesDatabaseExist(String databaseName) {
File dbFile = this.getDatabasePath(databaseName);
return dbFile.exists();
}
}
Loading.java
public class Loading extends AsyncTask<String, Integer, Integer> {
public interface LoadingTaskFinishedListener {
void onTaskFinished();
}
private LocalDBHelper mydb = null;
private final ProgressBar progressBar;
private Context mContext;
private final LoadingTaskFinishedListener finishedListener;
public Loading(ProgressBar progressBar, LoadingTaskFinishedListener finishedListener, Context context) {
this.progressBar = progressBar;
this.finishedListener = finishedListener;
this.mydb = LocalDBHelper.newInstance(context);
mContext = context;
}
#Override
protected Integer doInBackground(String... params) {
SQLiteDatabase sqLiteDatabase = mydb.getWritableDatabase();
GSONHandler.newInstance(mContext, sqLiteDatabase);
return 1234;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
finishedListener.onTaskFinished();
}
}
GSONHandler.java
public class GSONHandler {
static final String TAG = GSONHandler.class.getSimpleName();
private Context context;
private LocalDBHelper mydb;
private SQLiteDatabase sqLiteDatabase;
private static GSONHandler mGsonHandler = null;
public static GSONHandler newInstance(Context context, SQLiteDatabase sqLiteDatabase){
if (mGsonHandler == null){
mGsonHandler = new GSONHandler(context.getApplicationContext(), sqLiteDatabase);
}
return mGsonHandler;
}
private GSONHandler(Context context, SQLiteDatabase sqLiteDatabase) {
this.context = context;
this.sqLiteDatabase = sqLiteDatabase;
onCreate();
}
//assign json data to tables
private void onCreate() {
//get local json and save it to db
premiseCategoryMasterSetup();
premiseCategorySetup();
inspcTypeSetup();
inspcStatusSetup();
stateSetup();
areaSetup();
districtSetup();
analysisGroupSetup();
analysisSubGroup();
parameterSetup();
subParameterSetup();
identificationSetup();
premiseCertliSetup();
txn_premiseSetup();
prosecutionOtherSetup();
txn_layoutSectionSetup();
txn_layoutCardSetup();
txn_layoutInputFieldSetup();
}
private void areaSetup() {
Log.d(TAG, "areaSetup");
InputStream inputStream = context.getResources().openRawResource(R.raw.ref_area);
String jsonString = readJsonFile(inputStream);
Gson gson = new Gson();
List<Area> areaList = Arrays.asList(gson.fromJson(jsonString, Area[].class));
for (Area area : areaList)
{
if(sqLiteDatabase != null) {
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_AREA_ID, area.getAreaId());
values.put(Constants.COLUMN_AREA_CODE, area.getAreaCode());
values.put(Constants.COLUMN_AREA_NAME, area.getAreaName());
values.put(Constants.COLUMN_ACTIVE, area.getActive());
values.put(Constants.COLUMN_FK_STATE_ID, area.getFk_stateId());
long id = sqLiteDatabase.insertOrThrow(Constants.REF_AREA_TABLE,
null, values);
}
}
}
....
private String readJsonFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte bufferByte[] = new byte[1024];
int length;
try {
while ((length = inputStream.read(bufferByte)) != -1) {
outputStream.write(bufferByte, 0 , length);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toString();
}
}
You are setting the progress of the progress bar inside onProgressUpdate method but it is never called. To call onProgressUpdate method, you need to call publishProgress method inside doInBackground method. The onProgressUpdate method is invoked on the UI thread after the call to publishProgress method.
In doInBackground() call publishProgress(); method to display and update progressbar. Hope this will Help.

Get array from BackgroundTask method to another Activity

I'm newbie in Java/ADT and I'm trying to get an array from "Activity A" to "Activity B". The app takes information from a webpage, and then saves it in a pair of arrays and show the information. I want to click a "go to graph" button (calls to viewallday()) to redirect to Activity B who will show a graphic with all this information.
The problem is that they're a self refresh array (1sec refresh) and don't want to loose this feature when the app It's on graphic mode (Activity B). Any ideas about how to do that?
Thank all of you in advance, I'm learning a lot from this site.
UPDATE: I'm trying to do this with a Singleton pattern. But LogCat says:
02-26 22:21:59.300: E/AndroidRuntime(2677): FATAL EXCEPTION: main
02-26 22:21:59.300: E/AndroidRuntime(2677): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.Chispa/com.example.Chispa.Activity_allday}: android.os.NetworkOnMainThreadException
02-26 22:21:59.300: E/AndroidRuntime(2677): Caused by: android.os.NetworkOnMainThreadException
UPDATE 2: Finally got it!! Here's the code I used:
Here's the code for Activity A:
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view) {
Intent intent = new Intent(MainActivity.this, Activity_allday.class);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
public Document getUrl(){
try {
URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?FECHA=20140226");
/*URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?lang=es&frameId=4064&segmento=1&promocion=");*/
Document doc = Jsoup.connect(url.toString()).get();
return doc;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
GlobalVariables gs = (GlobalVariables) getApplication();
gs.setBar(getValuesGraph(getUrl()));
p.bar = getValuesGraph(getUrl());
p.values = getValuesFooter(getUrl());
return p;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
And here's the code for Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
And here's a GlobalVariable class who captures the array I want to send to Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
That's all! hope It'll help to future users.
Thanks all for your help.
Here is something you could try:
Inside your AsyncTask, define an interface and a method inside it that will pass back the data to the calling activity and inside that method, call the next activity and set the data as an extra.
This is the simplest way.
In your AsyncTask, inside onPostExecute(result), use a try block to call the method which belongs to the above mentioned interface which must be implemented by the calling activity.
HomeActivity.java
/public class SampleActivity extends Activity implements SampleAsyncTask.OnUpdateListener{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
executeAsync();
}
public void executeAsync(){
new SampleAsyncTask(this).execute("someFlagToCheck");
}
#Override
public void onDataProcessed(String result){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("data", result);
startActivity(intent);
}
}
SampleAsyncTask.java
public class SampleAsyncTask extends AsyncTask<Void, Void, String>{
Context context;
//constructor
SampleAsyncTask(Context context){
this.context = context;
}
#Override
public void doInBackground(String... params){
//do something depending on the arguments in params
return "data";
}
#Override
public void onPostExecute(String result){
try{
((OnUpdateListener) context).onDataProcessed(result);
}catch(Exception e){
e.printStackTrace();
}
}
public interface OnUpdateListener{
public void onDataProcessed(String data);
}
}
Follow this example. The calling activity implements the AsyncTask's interface and overrides its method which will be called when the async task is done with the result.
I hope this helped.
SOLUTION:
Here's the code for Activity A:
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view) {
Intent intent = new Intent(MainActivity.this, Activity_allday.class);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
public Document getUrl(){
try {
URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?FECHA=20140226");
/*URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?lang=es&frameId=4064&segmento=1&promocion=");*/
Document doc = Jsoup.connect(url.toString()).get();
return doc;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
GlobalVariables gs = (GlobalVariables) getApplication();
gs.setBar(getValuesGraph(getUrl()));
p.bar = getValuesGraph(getUrl());
p.values = getValuesFooter(getUrl());
return p;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
Global variable class who captures the array I want to send to Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
Thanks all for your help!!

Categories