Content quickly disappears - android

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

Related

Null pointer Exception while calling Asynctask situated inside fragment

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.

How to use If Else Statement for this android weather application

When the code below runs, it shows the temperature in degrees.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String APP_ID = "80e4eede56844462ef3cdc721208c31f";
private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;
private GoogleApiClient googleApiClient;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
PERMISSION_ACCESS_COARSE_LOCATION);
}
googleApiClient = new GoogleApiClient.Builder(this, this, this).addApi(LocationServices.API).build();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_ACCESS_COARSE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good!
} else {
Toast.makeText(this, "Need your location!", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onStart() {
super.onStart();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
Log.i(MainActivity.class.getSimpleName(), "Connected to Google Play Services!");
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
double lat = lastLocation.getLatitude(), lon = lastLocation.getLongitude();
String units = "imperial";
String url = String.format("http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s",
lat, lon, units, APP_ID);
new GetWeatherTask(textView).execute(url);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}
private class GetWeatherTask extends AsyncTask<String, Void, String> {
private TextView textView;
public GetWeatherTask(TextView textView) {
this.textView = textView;
}
#Override
protected String doInBackground(String... strings) {
String weather = "UNDEFINED";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
weather = String.valueOf(main.getDouble("temp"));
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
public void onPostExecute(String temp) {
textView.setText("Weather temperature is: " + temp + "°");
}
}
}
Can someone help me on how to use the if and else statements to make it so that if the temperature is below a certain degree, the user interface will display some text and if it's above that certain degree, it will display a different text?
#Override
public void onPostExecute(String temp) {
textView.setText("Weather temperature is: " + temp + "°");
if (temp < someValue)
//doSomething
else
//doSomethingElse
}
This should be intuitive enough.
first of all you will receive the temp as double value
don't convert it to string, replace this
weather = String.valueOf(main.getDouble("temp"));
to
double weather = main.getDouble("temp");
and do this
#Override
public void onPostExecute() {
if (weather < yourValue)
//yourCode
else
//anthorCode
}
OR if you want to convert the temp value to string just add this
#Override
public void onPostExecute() {
if (weather.equals("yourValue"))
//yourCode
else
//anthorCode
}
and i don't recommended this.

Uploading text messages to google drive from android not working

First time I am using GoogleApiClient and want to upload all the text messages to google drive when the share button in the app is clicked. But the data is not uploading on the drive.
MainActivity :
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
SmsAdapter adapter;
FloatingActionButton fab;
Cursor c;
ExportTask task;
ArrayList<CustomSms> smslistSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
smslistSearch = new ArrayList<>();
rv = (RecyclerView) findViewById(R.id.messages_view);
LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
rv.setLayoutManager(llm);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i =new Intent(MainActivity.this,SendSms.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
final ArrayList<CustomSms> smslist, smsgrouplist;
smslist = new ArrayList<>();
smsgrouplist = new ArrayList<>();
//Fetch inobx sms message
c = getContentResolver().query(SmsApplication.INBOX_URI, null, null, null, null);
while (c.moveToNext()) {
String address = c.getString(c.getColumnIndexOrThrow("address"));
String date = c.getString(c.getColumnIndexOrThrow("date"));
String body = c.getString(c.getColumnIndexOrThrow("body"));
smslist.add(new CustomSms(address, date, body));
}
smslistSearch = smslist;
Map<String, CustomSms> map = new LinkedHashMap<>();
for (CustomSms ays : smslist) {
CustomSms existingValue = map.get(ays.address);
if(existingValue == null){
map.put(ays.address, ays);
}
}
smsgrouplist.clear();
smsgrouplist.addAll(map.values());
adapter = new SmsAdapter(MainActivity.this);
adapter.updateList(smsgrouplist);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Handle item click
ArrayList<CustomSms> smsinsidegroup = new ArrayList<CustomSms>();
String n = smsgrouplist.get(position).address;
for (int i = 0; i < smslist.size(); i++) {
if(smslist.get(i).address.equals(n))
smsinsidegroup.add(smslist.get(i));
}
Intent i = new Intent(MainActivity.this, ReadAllSms.class);
i.putParcelableArrayListExtra("messages", smsinsidegroup);
startActivity(i);
}
})
);
}
catch (Exception e)
{
e.printStackTrace();
}
}
class ExportTask extends AsyncTask<Void, Integer, Uri> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Exporting to file ...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(0);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Uri doInBackground(Void... params) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
fos = new FileOutputStream(f);
int count = c.getCount(), i = 0;
StringBuilder sb = new StringBuilder();
if (c.moveToFirst()) {
do {
sb.append(c.getString(c.getColumnIndex("address")))
.append("\n");
sb.append(c.getString(c.getColumnIndex("body")))
.append("\n");
sb.append("\n");
publishProgress(++i*100/count);
} while (!isCancelled() && c.moveToNext());
}
fos.write(sb.toString().getBytes());
return Uri.fromFile(f);
} catch (Exception e) {
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {}
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Uri result) {
super.onPostExecute(result);
pDialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "Export task failed!",
Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
Intent i = new Intent(MainActivity.this,SearchActivity.class);
i.putParcelableArrayListExtra("search", smslistSearch);
startActivity(i);
return true;
}
if (id == R.id.action_share) {
/*Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);*/
task = new ExportTask();
task.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
if (task != null) {
task.cancel(false);
task.pDialog.dismiss();
}
super.onPause();
}
}
UploadData :
public class UploadData extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "upload_file";
private static final int REQUEST_CODE = 101;
private File textFile;
private GoogleApiClient googleApiClient;
public static String drive_id;
public static DriveId driveID;
FrameLayout rl;
TextView success;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_data);
rl = (FrameLayout) findViewById(R.id.frame);
success = (TextView) findViewById(R.id.success);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBackOrig));
textFile = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "connecting...");
googleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (googleApiClient != null) {
Log.i(TAG, "disConnecting...");
googleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Log.i(TAG, "In onActivityResult() - connecting...");
googleApiClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "in onConnected() - connected");
Drive.DriveApi.newDriveContents(googleApiClient)
.setResultCallback(driveContentsCallback);
}
#Override
public void onConnectionSuspended(int cause) {
switch (cause) {
case 1:
Log.i(TAG, "Connection suspended - Cause: " + "Service disconnected");
break;
case 2:
Log.i(TAG, "Connection suspended - Cause: " + "Connection lost");
break;
default:
Log.i(TAG, "Connection suspended - Cause: " + "Unknown");
break;
}
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Error creating the new file of contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
new Thread() {
#Override
public void run() {
OutputStream outputStream = driveContents.getOutputStream();
addTextfileToOutputStream(outputStream);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("SmsBackup")
.setMimeType("text/plain")
.setDescription("This is a text file uploaded from device")
.setStarred(true).build();
Drive.DriveApi.getRootFolder(googleApiClient)
.createFile(googleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
private void addTextfileToOutputStream(OutputStream outputStream) {
byte[] buffer = new byte[1024];
int bytesRead;
try {
BufferedInputStream inputStream = new BufferedInputStream(
new FileInputStream(textFile));
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(UploadData.this,
"Error adding file to Drive", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(UploadData.this,
"File successfully added to Drive", Toast.LENGTH_SHORT).show();
showProgress(false);
rl.setBackgroundColor(getResources().getColor(R.color.colorBack));
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBack));
success.setVisibility(View.VISIBLE);
final PendingResult<DriveResource.MetadataResult> metadata
= result.getDriveFile().getMetadata(googleApiClient);
metadata.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
Metadata data = metadataResult.getMetadata();
drive_id = data.getDriveId().encodeToString();
driveID = data.getDriveId();
}
});
}
};
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
}
}
private void buildGoogleApiClient() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
progressBar.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
}
You might want to check on how you work with File Contents, first you might want to check if there is a value on the variable textFile that you have set.
The example below illustrates how to append "hello world" to the DriveContents.
try {
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
} catch (IOException e) {
e.printStackTrace();
}
There is a related SO question - Upload text file to Google Drive using Android that you might want to check out. The answer in the question reminds the OP regarding how to feed the file with contents.
Lastly, you might want to check this github. This code show how to insert the content of the chat into a file and save it to the drive.
Hope this helps.

Drive Android Api. How to get notified or invoke listner when something has changed in the folder from web?

I want to get File Or Folder ID when that file is changed from the web. I gone through Documentation Listening for Change Events Git Hub Demo But i am not able to implement it.
In my app i am trying to listen to changes and modify those changes to local files also (sync).
In this test code i am just creating a folder and attaching a listner to the folder.
but when i rename folder from web Listner in not listening why?
1>I tried with this code
DriveId ddid = sky.getDriveFolder().getDriveId();
DriveFolder df = Drive.DriveApi.getFolder(mGoogleApiClient, ddid);
df.addChangeListener(getGoogleApiClient(), changeListener2);
2> And also with this line
DriveFolderResult sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
sky.getDriveFolder().addChangeListener(getGoogleApiClient(), changeListener2);
class file.
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private static final int PICKFILE_RESULT_CODE = 1;
private ContentsResult contentsresult;
private GoogleApiClient mGoogleApiClient;
String EXISTING_FILE_ID = "";
int folderCreated = 0;
SharedPreferences prefs;
ArrayList<String> dbfileid = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
String fdd="";
DriveFolderResult sky;
private DriveId mFolderDriveId;
String isfolder;
SharedPreferences sp;
String Shared="Shared";
String folderid="";
int j=0;
String songfileid="";
String realid ="";
#Override
protected void onResume() {
super.onResume();
initDrive();
}
private void initDrive() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName("shivrajp130#gmail.com")
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error" + e.toString());
}
}
#Override
public void onConnected(Bundle connectionHint) {
showToast("Inside Connected");
sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showToast("Thread Started");
createSkyFolder();
}
});
t.start();
}
private void createSkyFolder()
{
// TODO Auto-generated method stub
try
{
showToast("creating Folder");
if(!sp.getString(isfolder, "false").contains("created"))
{
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().
setTitle("Sky folder").build();
sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
sky.getDriveFolder().addChangeListener(getGoogleApiClient(), changeListener2);
showToast("folder created");
sp.edit().putString(isfolder, "created").commit();
// To store secret ID string of file or folder so that we can later get a DriveId object.
realid = sky.getDriveFolder().getDriveId().encodeToString();
sp.edit().putString(folderid, realid).commit();
showToast("Real== "+realid);
}
Status s = Drive.DriveApi.requestSync(mGoogleApiClient).await();
if(s.isSuccess())
{
showToast("Success");
}
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
final private Listener<ChangeEvent> changeListener2 = new Listener<ChangeEvent>() {
#Override
public void onEvent(ChangeEvent event) {
showToast("Listening now");
showToast(String.format("The New Id Is %s", event.hasMetadataChanged()));
}
};
#Override
public void onConnectionSuspended(int cause) {
showToast("GoogleApiClient connection suspended");
}
}
Please provide any code snippet for the same.

Showing progress bar while loading a List

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

Categories

Resources