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();
}
Related
I am facing a Null pointer Exception while calling Create report (which in turns calls its Asynctask "createReportTask" situated inside the Activity) But the application crashes giving NPE in the other fragment's Asynsc task (situated inside fragment) , I have tried passing context in constructor etc getContext(), getAcitivity() etc but all in vain. I am attaching Logs and Code please help!!
Logs:
05-24 12:56:11.505 14632-14632/com.example.aiousecurityapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aiousecurityapplication, PID: 14632
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.widget.Toast.<init>(Toast.java:121)
at android.widget.Toast.makeText(Toast.java:291)
at android.widget.Toast.makeText(Toast.java:281)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:439)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:377)
at android.os.AsyncTask.finish(AsyncTask.java:727)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:744)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Create Report Code:
public class CreateReport extends AppCompatActivity {
public EditText eventDate;
public EditText eventTime;
EditText reporterName;
EditText reporterCnic;
int flag = 0;
public static Calendar userCalendar;
private String Lat, Long;
private static final String[] BLOCK = new String[]{"Block 1", "Block 2", "Block 3", "Block 4", "Block 5"};
private static final String[] sampleDesc = new String[]{"Aag Lagi ha", "Darwaza Khula h", "Tala Ni Laga", "Lights / Fan On hain"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_report);
Button createReport = (Button) findViewById(R.id.createReport);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ActionBar ab = getSupportActionBar();
ab.setTitle("Create Report");
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Lat = bundle.getString("lat");
Toast.makeText(getContext(), "Latitude" + Lat, Toast.LENGTH_LONG).show();
Long = bundle.getString("Long");
}
createReport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (eventDescription.getText().toString().length() < 3) {
eventDescription.setError("Minimum 5 Letters");
Toast.makeText(getApplicationContext(),
"Please some Description", Toast.LENGTH_SHORT)
.show();
} else {
// creating new product in background thread
String blockname = blockName.getSelectedItem().toString().trim();
String eventEsc = eventEsclation.getSelectedItem().toString().trim();
String eventdesc = eventDescription.getText().toString().trim();
String cnic = reporterCnic.getText().toString().trim();
String userLat = Lat;
String userLong = Long;
String date = eventDate.getText().toString().trim();
String time = eventTime.getText().toString().trim();
new createReportTask().execute(blockname, eventEsc, eventdesc, cnic, userLat, userLong, date, time);
}
}
});
}
public class createReportTask extends AsyncTask<String, String, JSONObject> {
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Creating Report", "in Pre Execute");
pDialog = new ProgressDialog(CreateReport.this);
pDialog.setMessage("Creating Report");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
pDialog.dismiss();
Toast.makeText(CreateReport.this, "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 2) {
Toast.makeText(CreateReport.this, message, Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Creating product
*/
protected JSONObject doInBackground(String... args) {
String blockName = args[0] != null ? args[0] : "";
String eventEscalation = args[1];
String eventDesc = args[2];
String userCnic = args[3];
String userLat = args[4];
String userLong = args[5];
String date = args[6];
String time = args[7];
if (blockName.trim().length() != 0 && eventEscalation.trim().length() != 0
&& eventDesc.trim().length() != 0 && userCnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
//db field name in value side
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("page", "datasync"));
params.add(new BasicNameValuePair("blockName", blockName));
params.add(new BasicNameValuePair("eventEscalation", eventEscalation));
params.add(new BasicNameValuePair("eventDesc", eventDesc));
params.add(new BasicNameValuePair("userCnic", userCnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
// getting JSON Object
// Note that create product url accepts POST method
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} else {
return null;
}
}
}
}
Fragment Code:
public class EventsReportFragment extends Fragment {
static final int REQUEST_AUTHORIZATION = 1001;
private RecyclerView recyclerView;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private boolean mAlreadyStartedService = false;
private TextView mMsgView;
View rootView;
String latitude;
String longitude;
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm:ss";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
public EventsReportFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mMsgView = (TextView) rootView.findViewById (R.id.msgView);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateReport.class);
intent.putExtra("lat", latitude);
intent.putExtra("long", longitude);
startActivity(intent);
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
startStep1();
}
/**
* Step 1: Check Google Play services
*/
private void startStep1() {
//Check whether this user has installed Google play service which is being used by Location updates.
if (isGooglePlayServicesAvailable()) {
//Passing null to indicate that it is executing for the first time.
startStep2(null);
} else {
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
}
}
/**
* Step 2: Check & Prompt Internet connection
*/
private Boolean startStep2(DialogInterface dialog) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
promptInternetConnect();
return false;
}
if (dialog != null) {
dialog.dismiss();
}
if (checkPermissions()) { //Yes permissions are granted by the user. Go to the next step.
startStep3();
} else { //No user has not granted the permissions yet. Request now.
requestPermissions();
}
return true;
}
/**
* Show A Dialog with button to refresh the internet state.
*/
private void promptInternetConnect() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("title_alert_no_intenet");
builder.setMessage("msg_alert_no_internet");
String positiveText = "Refresh Button";
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Block the Application Execution until user grants the permissions
if (startStep2(dialog)) {
//Now make sure about location permission.
if (checkPermissions()) {
//Step 2: Start the Location Monitor Service
//Everything is there to start the service.
startStep3();
} else if (!checkPermissions()) {
requestPermissions();
}
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Step 3: Start the Location Monitor Service
*/
private void startStep3() {
//And it will be keep running until you close the entire application from task manager.
//This method will executed only once.
if (!mAlreadyStartedService && mMsgView != null) {
mMsgView.setText("Location_service_started");
//Start location sharing service to app server.........
Intent intent = new Intent(getContext(), LocationMonitoringService.class);
getActivity().startService(intent);
mAlreadyStartedService = true;
//Ends................................................
}
}
/**
* Return the availability of GooglePlayServices
*/
public boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(getContext());
if (status != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(getActivity(), status, 2404).show();
}
return false;
}
return true;
}
/**
* Return the current state of the permissions needed.
*/
private boolean checkPermissions() {
int permissionState1 = ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
int permissionState2 = ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;
}
/**
* Start permissions requests.
*/
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
boolean shouldProvideRationale2 =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION);
// Provide an additional rationale to the img_user. This would happen if the img_user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale || shouldProvideRationale2) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale,
android.R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
});
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the img_user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
/**
* Shows a {#link Snackbar}.
*
* #param mainTextStringId The id for the string resource for the Snackbar text.
* #param actionStringId The text of the action item.
* #param listener The listener associated with the Snackbar action.
*/
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(
rootView.findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If img_user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission granted, updates requested, starting location updates");
startStep3();
} else {
showSnackbar(R.string.permission_denied_explanation,
R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
#Override
public void onDestroy() {
//Stop location sharing service to app server.........
getActivity().stopService(new Intent(getActivity(), LocationMonitoringService.class));
mAlreadyStartedService = false;
//Ends................................................
super.onDestroy();
}
public class MakeRequestTask extends AsyncTask<String, String, JSONObject> {
private Exception mLastError = null;
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
public MakeRequestTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
String cnic = args[0];
String userLat = args[1];
String userLong = args[2];
String date = args[3];
String time = args[4];
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (cnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
params.add(new BasicNameValuePair("page", "locationUpdate"));
params.add(new BasicNameValuePair("cnic", cnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
}
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} catch (Exception e) {
e.printStackTrace();
mLastError = e;
cancel(true);
return null;
}
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
Toast.makeText(getContext(), "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 1) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
} else if (success == 2){
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCancelled() {
}
}
}``
In onPostExecute check for activity is running before doing any work.
because onPostExecute may be called if activity was running not more
Try this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
//your remaining code here
}
Use following line:
String message = result.optString("message");
// it will returns the empty string ("") if the key you specify doesn't exist
instead of using
String message = result.getString("message");
// it will throws exception if the key you specify doesn't exist
replace getContext() with getActivity() inside your fragment
e.g replace
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
with
`Toast.makeText(getActivity(), "no_google_playservice_available", Toast.LENGTH_LONG).show();`
and
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
with
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
and so on if any.
Working on building my first android app, and I have a simple button that should get the location of the user(and save it in a DB). When I click this, the page I want to load does but it quickly disappears after the information is saved in the DB. I'm sure this is something simple, but for the life of me I can't get the new activity to stay put. The basic question is how do I get the textview with ACTIVE to stay on screen after the button is clicked from the first bit of code below.
Here is the button in the java class to start the activity:
public class WalkerMain extends ActionBarActivity implements View.OnClickListener{
private Button mActive;
public String user = null;
public Integer user_id = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.walker_app);
Bundle extras = getIntent().getExtras();
if (extras != null) {
user = extras.getString("user");
user_id = extras.getInt("user_id");
Log.d("In WalkerMain!", user);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
mActive = (Button) findViewById(R.id.go_active);
// register listeners
mActive.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(this, WalkerActive.class);
i.putExtra("user", user);
i.putExtra("user_id", user_id);
startActivity(i);
}
}
And the activity that updates the user information and should just display a simple textbox on the contentview.
public class WalkerActive extends ActionBarActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private ProgressDialog pDialog;
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public Double lat, lon;
public Integer radius = 0;
public String user = null;
public Integer user_id = null;
public JSONParser jsonParser = new JSONParser();
private static final String UPDATE_URL = "...";
private final String TAG = "APP";
private TextView mLocationView;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.walker_active);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
// Connect the client.
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
// Disconnecting the client invalidates it.
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
// Display the connection status
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
if (l != null) {
lat = l.getLatitude();
lon = l.getLongitude();
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
user = extras.getString("user");
user_id = extras.getInt("user_id");
Log.d("In WalkerActive", user);
}
String ret_value = null;
try {
ret_value = new UpdateActive().execute().get();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "GoogleApiClient connection has been suspend");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "GoogleApiClient connection has failed");
}
#Override
public void onLocationChanged(Location location) {
mLocationView.setText("Location received: " + location.toString());
}
class UpdateActive extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(WalkerActive.this);
pDialog.setMessage("Going Active...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", user_id.toString()));
params.add(new BasicNameValuePair("radius", radius.toString()));
params.add(new BasicNameValuePair("lat", lat.toString()));
params.add(new BasicNameValuePair("lon",lon.toString()));
Log.d("request!", "starting");
Log.d("params",params.toString());
JSONObject json_update = jsonParser.makeHttpRequest(
UPDATE_URL, "POST", params);
//Log.d("completed",json.toString());
// full json_update response
Log.d("Updated Activity", json_update.toString());
// json_update success element
success = json_update.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Updated Activity!", json_update.toString());
finish();
return json_update.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json_update.getString(TAG_MESSAGE));
return json_update.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
}
walker_active.xml is very simple
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="ACTIVE"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
oka after looking at your code you got the
if (success == 1) {
Log.d("Updated Activity!", json_update.toString());
finish();
return json_update.getString(TAG_MESSAGE);
}
in this if statement what finish(); does is that this code is running in background so the Finish();statement simply stops ur current running function and stop the view .
try removing the Finish(); statement
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'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();
}
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;
}
}