I have seen many answers for this type of question but its not related with my task. I am trying to get gps location in background but i got exception as Cant Create Handler Inside Thread That Has Not Called Looper Prepare in Android in mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);.
public class GPSLocation extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(RoadMaintenanceActivity.this);
progressDialog.setCancelable(true);
progressDialog.setMessage("Getting GPS Location...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(1);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.cancel();
}
#Override
protected Void doInBackground(Void... params) {
boolean isGps = false;
while(!isGps)
{
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if(longitude !=0 && latitude!=0)
{
isGps = true;
sendSMS();
}
}
return null;
}
}
I am not sure why we cant call that inside the doBackground() method.
Thanks for your help guys.
Finally i figured out the problem, I think this will help some one like me
public class GPSLocation extends AsyncTask<Void, Void, Void>
{
boolean running =true;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(RoadMaintenanceActivity.this);
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
getgps.cancel(true);
}
});
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
progressDialog.setCancelable(true);
progressDialog.setMessage("Getting GPS Location...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(1);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.cancel();
}
#Override
protected Void doInBackground(Void... params) {
boolean isDataSubmitted = false;
while(!isDataSubmitted)
{
if(longitude !=0 && latitude!=0)
{
sendSMS();
isDataSubmitted = true;
}
}
return null;
}
}
By having Locationmanager in onPreExecute() the exception get rid out from my application. We can get the gps in onpreexecute rather than doinbackground().
You can't do that.The mlocListener requires a Looper thread to operate.
in doInBackground Call Looper.prepare();
So your code will become something like this.
#Override
protected Void doInBackground(Void... params) {
Looper.myLooper().prepare();
boolean isGps = false;
-----------------
this seems suitable for what I'm trying to do at the moment. Any chance you can show me the full source? I currently have it worked into my code, but I'd like to see how you are getting the GPS co ords and starting the async
ProgressDialog progressDialog;
double longitude, latitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_screen);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Boolean locationCheck = sp.getBoolean("LOCATION", false);
if(locationCheck){
}
else
{
sendEmail();
playSound();
}
}
public class GPSLocation extends AsyncTask<Void, Void, Void>
{
boolean running =true;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(ConfirmScreen.this);
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
getgps.cancel(true);
}
});
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
progressDialog.setCancelable(true);
progressDialog.setMessage("Getting GPS Location...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(1);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.cancel();
}
#Override
protected Void doInBackground(Void... params) {
boolean isDataSubmitted = false;
while(!isDataSubmitted)
{
if(longitude !=0 && latitude!=0)
{
sendEmail();
isDataSubmitted = true;
}
}
return null;
}
}
public void backHome(View view)
{
Intent intent = new Intent (this, MainScreen.class);
startActivity(intent);
}
// Method to start playing and looping a sound.
public void playSound()
{
MediaPlayer clickSound = MediaPlayer.create(this, R.raw.warning);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Boolean soundCheck = sp.getBoolean("SOUND", false);
if (soundCheck)
{
clickSound.start();
}
}// method end
public void sendEmail()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String nameValue = sp.getString("NAME", "failed to get name");
String emailValue = sp.getString("EMAIL", "failed to get email");
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailValue});
i.putExtra(Intent.EXTRA_SUBJECT, "Email sent from DON'T PANIC - A Chris O'Brien Project");
i.putExtra(Intent.EXTRA_TEXT, "Hi there\n" + nameValue + " is in mortal danger. They didn't include co-ords as they assume you know where they are..\nKind Regards\nDon't Panic! \n\n\n");
try
{ startActivity(Intent.createChooser(i, "Send mail...."));
}
catch (android.content.ActivityNotFoundException ex){
Toast.makeText(ConfirmScreen.this, "There are no email clients installed or set up", Toast.LENGTH_SHORT).show();
}
}
public void sendEmail(String a, String b, String c)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String nameValue = sp.getString("NAME", "failed to get name");
String emailValue = sp.getString("EMAIL", "failed to get email");
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailValue});
i.putExtra(Intent.EXTRA_SUBJECT, "Email sent from DON'T PANIC - A Chris O'Brien Project");
i.putExtra(Intent.EXTRA_TEXT, "Hi there\n" + nameValue + " is in mortal danger. Please see the co-ords attached and run to their rescue!" +
" If you don't see any co-ords, they didn't check the box and assume you know where they are.\nKind Regards\nDon't Panic! \n\n\n" +
a + b + c);
try
{ startActivity(Intent.createChooser(i, "Send mail...."));
}
catch (android.content.ActivityNotFoundException ex){
Toast.makeText(ConfirmScreen.this, "There are no email clients installed or set up", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_confirm_screen, menu);
return true;
}
}
Related
My activity keep show the dialog, It seem don't do the doInBackground. It keep should the "Loading" screen .
Here is my code :
private class MapTask extends AsyncTask<Void, Void, Void> {
protected ProgressDialog dialog;
protected Context context;
public MapTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog = new ProgressDialog(context, 1);
this.dialog.setMessage("Loading");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
try {
String countryName=country.getTitle();
List<Address> address = new Geocoder(context).getFromLocationName(countryName, 1);
if (address == null) {
Log.e(null, "Not found");
} else {
Address loc = address.get(0);
Log.e(null, loc.getLatitude() + " " + loc.getLongitude());
LatLng pos = new LatLng(loc.getLatitude(), loc.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 6));
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (Exception e) {
Log.v("ASYNC", "ERROR : " + e);
e.printStackTrace();
}
return null;
}
}
Could somebody help me?
You are not calling dialog.dismiss() anywhere. You should do it in the onPostExecute of your AsyncTask:
#Override
protected void onPostExecute(Void... aVoid) {
dialog.dismiss();
}
In fact it is doing the doInBackground stuff, the problem is that you aren't dismissing the dialog in onPostExecute() method
Just add dialog.dismiss() in onPostExecute method.
I am trying to run a progress dialog while an other process is running, and I can't do it.
the process that I want run is this:
public void Onclick_editar (View view)
{
float porc;
String repre;
try{
porc = Float.parseFloat(edit_porcentaje.getText().toString());
repre = edit_representante.getText().toString();
try
{
Hilo hilo;
hilo = new Hilo(2, "UPDATE eleccion SET porcentaje="+porc+", delegados='"+repre+"' WHERE id="+idd );
hilo.start();
while(hilo.isAlive()){}
hilo = new Hilo(4, idd);
hilo.start();
while(hilo.isAlive()){}
Toast.makeText(this, "¡Actualizada con éxito!", Toast.LENGTH_SHORT).show();
}
catch(SQLException e)
{
Toast.makeText(this, "Error: Fallo en la base de datos", Toast.LENGTH_SHORT).show();
}
}catch(Exception e)
{
Toast.makeText(this, "Rellena todos los campos", Toast.LENGTH_SHORT).show();
}
}
this is launching when I click a button. thanks!
EDIT/////////////
well I solved the problem with this code!!
public void button(View v) {
new waiting().execute();
}
class waiting extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressdialog;
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
progressdialog = new ProgressDialog(Tab_adminver_modificar_eleccion.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch (Exception e) {
}
return null;
}
}
but I don't use a toast in a method doInBackground (FC)
Do you mean you are waiting for hilo to finish in this line : while(hilo.isAlive()){}?
Use AsyncTask instead, make use of its onPostExecute
you can try like this your process will run in background and progress dialog will be executing as well but when process will complete progress dialog will dismiss..
public class asynTask1 extends AsyncTask<String, Void, Boolean> {
public asynTask1 (MainActivity activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
// do process
}
U can call it onclick or also can onCreate.. it better to make separate class for asyntask1 and write
new asynTask1(MainActivity.this).execute(); where you want to call it..
i hope it will helps ...
If your purpose is to show a ProgressDialog, then you can use this function for displaying a progress dialog-
public static void showProgressLoader(Context context, int duration)
{
final ProgressDialog dialog = ProgressDialog.show(context, "", "Loading...");
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
dialog.dismiss();
}
}, duration);
}
In this finction, pass the context and duration in milliseconds for which you want to show, after that duration it will get dissmissed by itself.
public void launchRingDialog(View view) {
final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...", "Downloading Image ...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
**// the MYSql consultation should be here?**
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
I have the following code, and what I'm trying to do is to programmatically check if there is an internet connection or not.
Since I'm getting a NetworkOnMainThreadException, and have been advised to use AsyncTask.
I want to perform network operation on hasActiveInternetConnection(Context context)and return true if connected to a network, else false .
How do I do this using AsyncTask?
public class NetworkUtil extends AsyncTask<String, Void, String>{
Context context;
public NetworkUtil(Context context){
this.context = context;
}
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(context).isNetworkAvailable())
{
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
boolean url= (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException e) {
}
}
// your get/post related code..like HttpPost = new HttpPost(url);
else {
Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
use this class for checking internet connectivity...
public class CheckNetwork {
private Context context;
public CheckNetwork(Context context) {
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
then.....
use the this ASynTask for httppost.
public class NetworkUtil extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) {
// your get/post related code..like HttpPost = new HttpPost(url);
} else {
// No Internet
// Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
There is no way to get an Internet connexion state, you will always have the network connection state.
But I found a pretty nice answer here: you send a request to google.com !! :) you can also try to ping to google by unix commandes if you want !!
here the guy is using a thread , and waiting a little bit for the answer, then returning a boolean . you do your staff in the handler . this is his code :
public static void isNetworkAvailable(final Handler handler, final int timeout) {
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in milliseconds)
new Thread() {
private boolean responded = false;
#Override
public void run() {
// set 'responded' to TRUE if is able to connect with google mobile (responds fast)
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
}
catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0); }
else { handler.sendEmptyMessage(1); }
}
}
}.start();
}
Then, I define the handler:
Handler h = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
...and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
Your AsyncTask should look like this:
private class NetworkUtilTask extends AsyncTask<Void, Void, Boolean>{
Context context;
public NetworkUtilTask(Context context){
this.context = context;
}
protected Boolean doInBackground(Void... params) {
return hasActiveInternetConnection(this.context);
}
protected void onPostExecute(Boolean hasActiveConnection) {
Log.d(LOG_TAG,"Success=" + hasActiveConnection);
}
}
You would then execute it like the following:
NetworkUtilTask netTask = new NetworkUtilTask(context);
netTask.execute();
i've an progress circle that is set inside an AsyncTask. It shows for about a second as the asynctask is executing, then disappears. once the task is completed if i press the back button the circle shows for a long time. why is this?
private class AsyncGetRota extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(NfcscannerActivity.this,
"Connecting to Server"," retrieving rota...", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
[update]
getRota.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "onclicked getRota");
String[] params = new String[]{"36", "18-09-2012"};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
for(int i = 0; i < 60; i++){
if(agr.isCancelled() == true){
Log.e(TAG, "asyncTask is finished");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of for loop
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}// end of onclick
});
...
new MyAsyncTask().execute(string);
...
}
class MyAsyncTask extends AsyncTask<String, Void, Whatever > {
...
#Override
protected Whatever doInBackground(String... params) {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
return rotaArray;
}
#Override
protected void onPostExecute(Whatever result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
Intent intent = new Intent(NfcscannerActivity.this, GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", result);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}
}
You should let the execution continue after you start the AsyncTask, and not block it using some loop or something..
try to implement it like this:
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Processing...");
dialog.show();
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
};
that's always works for me
Couple of problems here, you do not initialize ProgressDialog, initialize a constructor that initializes you ProgressDialog like this...
public AsyncGetRota(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
Then in onPostExecute check if your ProgressDialog is null, like this
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
}
Ok Now i admit that i am new to using progress bar infact i never use it but now i need to use it
I have an activity (Main) and a menu which can start 6 new activity. From these activities there is an activity which load the data in a ListView it take 3-4 second to load .This activity parse the json and pass the data to another activity. How can i show the progress bar as soon as user click the menu option for this activity and disappear it when List will be loaded.
Here is the activiy
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent=new Intent(this ,GetLatAndLng.class);
setContentView(R.layout.listplaceholder);
//ProgressBar pb=(ProgressBar)findViewById(R.id.progressbar);
LocationManager locationManager;
String context=Context.LOCATION_SERVICE;
locationManager=(LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
double geoLat = location.getLatitute();
double geoLng = location.getLongitude();
Bundle b=new Bundle();
//pb.setVisibility(View.VISIBLE);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONFunction.getJSONfromURL(getUrl());
Log.v(TAG, "got the json");
try{
JSONArray JArray = json.getJSONArray("results");
Log.v(TAG, "getting results");
for(int i=0;i<JArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = JArray.getJSONObject(i);
JSONObject location1=e.getJSONObject("geometry").getJSONObject("location");
latitude[i]=location1.getDouble("lat");
longitude[i]=location1.getDouble("lng");
reference[i]=e.getString("reference");
Log.v(TAG, reference[i]);
distance[i]=GetLatAndLng.gps2m(geoLat, geoLng,latitude[i] ,longitude[i]);
map.put("id", String.valueOf(i));
map.put("name", "" + e.getString("name"));
map.put("vicinity", "Address " + e.getString("vicinity")+" "+"Disance:"+distance[i]);
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
// pb.setVisibility(View.GONE);
b.putStringArray("key", reference);
intent.putExtras(b);
Log.v(TAG, ""+reference);
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.listview,
new String[] { "name", "vicinity", },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(JsonExampleActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
intent.putExtra("clickedid",position);
startActivity(intent);
}
});
}
public void updateWithNewLocation(Location location2) {
if(location2!=null) {
double geoLat = location2.getLatitude();
double geoLng = location2.getLongitude();
}
}
Thanks in Advance!!
Use AsyncTask to load data in background while showing loading indicator. In AsyncTask's doInBackground method , process the JSON or anything which is taking time.
public class HeavyWorker extends AsyncTask < String , Context , Void > {
private ProgressDialog progressDialog ;
private Context targetCtx ;
public HeavyWorker ( Context context ) {
this.targetCtx = context ;
this.needToShow = true;
progressDialog = new ProgressDialog ( targetCtx ) ;
progressDialog.setCancelable ( false ) ;
progressDialog.setMessage ( "Retrieving data..." ) ;
progressDialog.setTitle ( "Please wait" ) ;
progressDialog.setIndeterminate ( true ) ;
}
# Override
protected void onPreExecute ( ) {
progressDialog.show ( ) ;
}
# Override
protected Void doInBackground ( String ... params ) {
// Do Your WORK here
return null ;
}
# Override
protected void onPostExecute ( Void result ) {
if(progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss ( ) ;
}
}
}
In your Activity's onCreate() execute AsyncTask
new HeavyWorker().execute();
For this type of operations, you should use AsyncTask with that you can show progress dialog , while it loads.
The official tutorial is pretty helpful. Look into the onPostExecute() method to figure out how to end any sort of progress bar you may have.
Hope it helps
You should do it with an AsyncTask and show a progress dialog in the onPreExecuteMethod and dismiss it on onPostExecute:
class MyAsyncTask extends AsyncTask<String,Void,Object> {
ProgressDialog pd;
Context context;
public MyAsyncTask(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(context, "Loading", "Wait", true, true);
pd.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
}
#Override
protected Object doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(Object result) {
if(pd.isShowing())
pd.dismiss();
}
}
maybe it will help. I use BroadcastReceiver to update ListView in my app.
public static final String UPDATE_HISTORY_LIST = "com.myapp.update_history_list";
onPostExecute AsyncTask
#Override
protected void onPostExecute(JSONObject par) {
Intent intent = new Intent(AppSettings.UPDATE_HISTORY_LIST);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
}
Receiver in Activity
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Action: " + intent.getAction());
if (AppSettings.UPDATE_HISTORY_LIST.equals(intent.getAction())) {
OrderHistoryFragment history = (OrderHistoryFragment)getFragmentManager().findFragmentByTag("history");
if(history != null && history.isVisible()){
history.refresh();
}
}
}
};
#Override
protected void onPause() {
Log.i(TAG, "onPause");
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
#Override
protected void onResume() {
Log.i(TAG, "onResume");
super.onResume();
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
IntentFilter filter = new IntentFilter();
filter.addAction(AppSettings.UPDATE_HISTORY_LIST);
lbm.registerReceiver(mMessageReceiver, filter);
}
Layout
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<ProgressBar
android:id="#android:id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminate="true" />
Activity
mList = (ListView)rootView.findViewById(R.id.listView1);
mList.setEmptyView(rootView.findViewById(android.R.id.progress));
You can do that adding a property to your Activity:
ProgressDialog dialog;
Then just use this code to show your dialog:
dialog = ProgressDialog.show(this, "Title", "Loading", true);
And then add this when you want to delete it:
if(dialog!= null && dialog.isShowing())
dialog.dismiss();
Also add to your onStop those lines (just in case the user exists the Activity):
public void onStop()
{
if(dialog!= null && dialog.isShowing())
dialog.dismiss();
super.onStop();
}