Retrieve context in an abstract, non activity class - java

I'm trying to build my abstract implementation of AsyncTask and I would like to insert a custom ProgressDialog. How can I get the context outside of an Activity Class?
abstract public class DataPoller extends AsyncTask<Void, Void, Void> {
Context mContext = getApplicationContext();
ProgressDialog dialog = new ProgressDialog(mContext);
#Override
protected void onPreExecute() {
dialog.setMessage("Polling data...");
dialog.show();
}
#Override
protected void onPostExecute(Void unused) {
if ( dialog.isShowing() ) {
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params) {
int tmp=0;
for (int ii = 0; ii<1000; ii ++) {
for (int jj = 0; jj<1000; jj ++) {
tmp = ( tmp + 3 ) % 167;
}
}
return null;
}
}

You could pass it into the constructor:
abstract public class DataPoller extends AsyncTask<Void, Void, Void> {
...
Context mContext;
...
DataPoller(Context context){
super();
this.mContext = context;
}
...
}

Related

How do I call notifyDataSetChanged() from a AsyncTask that is in another class

So I am trying to call notifyDataSetChanged() to update the ArrayList on completion of OnPostExecute However I am finding it quite hard to do with the AsyncTask being in another class. I also cannot call it in setpagecontent as it is a static method.
I appreciate all the help provided :)
PostListActivity.java
public class PostListActivity extends AppCompatActivity {
ArrayList<String> Posts_Array_List = new ArrayList<String>();
// private RequestQueue mQueue;
ArrayAdapter<String> PostsAdaptor;
ListView lv;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_list);
mContext=PostListActivity.this;
lv = (ListView) findViewById(R.id.LV_Post_list);
PostsAdaptor = new ArrayAdapter<String>(PostListActivity.this, android.R.layout.simple_list_item_1, Posts_Array_List);
PostsAdaptor.notifyDataSetChanged();
lv.setAdapter(PostsAdaptor);
String stringUrl = "https://www.reddit.com/r/cars/hot.json?limit=1";
new DownloadAsyncTask(mContext,stringUrl).execute();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String myParam = extras.getString("paramPosition");
// Get the URL from the UI's text field.
}
}
public void setPageContent(String thePageContent) {
System.out.println("Got: " + thePageContent);
String jsonFromReddit = thePageContent;
//ArrayList<String> posts = RedditPostHelper.getRedditPostsFromJSON(jsonFromReddit);
// Posts_Array_List.addAll(posts);
Posts_Array_List.add(thePageContent);
System.out.println("result==="+thePageContent);
PostsAdaptor.notifyDataSetChanged();
}
}
DownloadAsyncTask.java
public class DownloadAsyncTask extends AsyncTask<Void,Void,String>{
private Context context;
private String url;
DownloadAsyncTask(Context mContext, String stringUrl)
{
super();
this.context=mContext;
this.url=stringUrl;
}
#Override
protected String doInBackground(Void... voids) {
String result="testing";
return result;
}
#Override
protected void onPostExecute(String result) {
if (!result.isEmpty() && result !=null){
PostListActivity pla = (PostListActivity) context;
pla.setPageContent(result);
}
}
Output:
}
There would be some changes to be made to the code but for inter class communication you can use an interface and use its functions as callbacks

Android - Get object from AsyncTask result

I want to create 10 Employee objects in an AsyncTask and return the result back to the MainActivity class to print it on a ListView with the 3 attributes of an Employee object.
This is what i have so far, but it just crashes after running
Menu class
public class Menu
{
public Employee person;
public void onButtonClick(View v) {
new setEMPInfo() {
protected void onPostExecute(Employee person)
{
doSomething(person);
}
}.execute();
}
public void doSomething(Employee person) {
//use person object to print on TextView
}
}
setEMPInfo class
public class setEMPInfo extends AsyncTask<Void, Void, Employee>
{
Public Employee person;
protected Bus doInBackground(String... params) {
String id = "100A";
String Fname = "John";
String Lname = "Smith";
for (int i = 0; i < 10; i++) {
person = new Employee(id, Fname, Lname);
}
return person;
}
}
Try this :
public class TestActivity extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = (ListView) findViewById(R.id.list_item);
setEMPInfo task = new setEMPInfo().execute();
}
private class setEMPInfo extends AsyncTask<Void, Void, ArrayList<Employee>> {
#Override
protected ArrayList<Employee> doInBackground(Void... params) {
String id = "100A";
String Fname = "John";
String Lname = "Smith";
ArrayList<Employee> employees = new ArrayList<>();
for (int i = 0; i < 10; i++) {
person = new Employee(id, Fname, Lname);
employees.add(person);
}
return employees;
}
#Override
protected void onPostExecute( ArrayList<Employee>result)
//print it on a ListView
list.setAdapter(new YourAdapret(getApplicationContext(), result));
}
}
}
when your doInBackground done , its return some value to onPostExecute . then you can do anything (save in database , save in SDcard , etc) in this method .
You have here an example of a complete asyncTask (by google docs).
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
You can create a static object in your caller class and change it in onPostExecute for example.
The problem is that your class setEMPInfo extends AsyncTask<Void, Void, Employee> and not AsyncTask<String, Void, Bus>
The fix is to change (inside your setEMPInfo class)
protected Bus doInBackground(String... params) { ... }
to
protected Employee doInBackground(String... params) { ... }
and
public class setEMPInfo extends AsyncTask<Void, Void, Employee>
to
public class setEMPInfo extends AsyncTask<String, Void, Employee>
Also, don't forget the #Override annotation.
Finally, I recommend you use an IDE to automatically fix your code spelling and other common mistakes. This problem wouldn't happen in Android Studio or Eclipse. :)
So basically, your code should look like that :
SetEMPInfo.java
public class SetEMPInfo extends AsyncTask<String, Void, Employee>
{
public Employee person;
#Override
protected Employee doInBackground(String... params)
{
String id = "100A";
String Fname = "John";
String Lname = "Smith";
person = new Employee(id, Fname, Lname);
return person;
}
}
Menu.java
public class Menu
{
public Employee person;
public void onButtonClick(View v)
{
new SetEMPInfo()
{
#Override
protected void onPostExecute(Employee employee)
{
doSomething(employee);
}
}.execute();
}
public void doSomething(Employee person)
{
//use person object to print on TextView
}
}
Try this
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new setEMPInfo() {
protected void onPostExecute(Employee person) {
doSomething(person);
}
}.execute();
}
}
);
here just for testing add all employee to list-
public void doSomething(Employee person) {
eList.add(person);
Log.e("Emp->", eList.toString());
}
Your AsyncTask should look like this-
class setEMPInfo extends AsyncTask<Employee, Void, Employee> {
Employee person;
#Override
protected Employee doInBackground(Employee... params) {
String id = "100A";
String Fname = "John";
String Lname = "Smith";
for (int i = 0; i < 10; i++) {
person = new Employee(id, Fname, Lname);
}
return person;
}
}

Passing multiple values to AsyncTask class

I am having some problem when trying to pass a String and object to AsyncTask class. So when my button on click, it should pass in a String and an EventReview object into the AsyncTask class:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
//Get the values returned from AsyncTask and pass it to another activity
}
}).execute(String.valueOf(eventIDTV.getText()));
}
});
And inside my AsyncTask class, I am getting String as the parameter:
public static class GetEventDetailAsyncTask extends AsyncTask<String, Integer, Double> {
EventController eventCtrl = new EventController();
Context context;
public interface OnRoutineFinished { // interface
void onFinish();
}
private OnRoutineFinished mCallbacks;
public GetEventDetailAsyncTask(OnRoutineFinished callback) {
mCallbacks = callback;
}
public GetEventDetailAsyncTask() {
} // empty constructor to maintain compatibility
public GetEventDetailAsyncTask(Context context){
this.context = context;
}
#Override
protected Double doInBackground(String... params) {
try {
eventCommentModel = eventCtrl.getEventCommentByID(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
if (mCallbacks != null)
mCallbacks.onFinish(); // call interface on finish
}
protected void onProgressUpdate(Integer... progress) {
}
}
So I wonder is there any possible way to pass in a String and EventReview object to the execute() and then when doInBackground(), each execute each method. Any guides?
Thanks in advance.
You can pass String and your custom class' object in Object[] in asynctask.
Object[] obj = new Object[2];
obj[0] = "my data";
obj[1] = myEventReviewObj;
new GetEventDetailAsyncTask().execute(obj);
AsyncTask:
public static class GetEventDetailAsyncTask extends AsyncTask<Object, Integer, Double> {
#Override
protected Double doInBackground(Object... params) {
String paramStr = "";
EventReview eventReview = null;
if(params[0] instanceof String && params[1] instanceof EventReview) {
paramStr = (String) params[0];
eventReview = (EventReview) params[1];
}
else {
eventReview = params[0];
paramStr = params[1];
}
try {
//perform operation using String and Object as per your need
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Hope this helps.
You can change the class to accept Objects as input:
public static class GetEventDetailAsyncTask extends AsyncTask<Object, Integer, Double>
and check if the object is an instance of String or of EventReview
#Override
protected Double doInBackground(Object... params) {
if(params[0] instanceof String) // it is String
else if(params[0] instanceof EventReview) // it is EventReview
}
Create custom constructor and save the passed variables in your AsyncTask:
public static class GetEventDetailAsyncTask extends AsyncTask<String, Integer, Double> {
EventReview eventReview;
private OnRoutineFinished mCallbacks;
String string;
Context context;
public GetEventDetailAsyncTask(OnRoutineFinished callback, String str, EventReview review) {
mCallbacks = callback;
string = str;
eventReview = review;
}
...
}
And then call the AsyncTask by passing your vars:
public void onClick(View v){
new GetEventDetailAsyncTask(
new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Get the values returned from AsyncTask and pass it to another activity
}
},
String.valueOf(eventIDTV.getText(),
eventReview).execute());
}

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!!

progress dialog not working

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();

Categories