I have a saved geo location(latitude,longitude).when a user presses a action button in app, the current location is recorded.
I want to check if the current latitude,longitude(which I have) falls
in a circular geofence (who's center geo point I have ).
I don't want to create a geofence on Google map. I just want to check if a geolocation falls in a geofence.
The code I use to get current geolocation when the accuracy is less than 20 :
public class CreatePlaceActivity extends Fragment implements
OnClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Button cancelBtn, submitBtn;
public boolean geoLocationCheck = false;
private String TAG = "CreatePlaceActivity";
public CreatePlaceActivity() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.create_place_screen,
container, false);
submitBtn = (Button) rootView.findViewById(R.id.submit_btn_id);
submitBtn.setTypeface(typeface);
submitBtn.setOnClickListener(this);
cancelBtn = (Button) rootView.findViewById(R.id.cancel_btn_id);
cancelBtn.setOnClickListener(this);
setlocationClient();
return rootView;
}
private void setlocationClient() {
int resp = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getActivity());
if (resp == ConnectionResult.SUCCESS) {
locationclient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
locationclient.connect();
} else {
GooglePalyErrorDialogIsShowing = true;
Toast.makeText(getActivity(),// CreatePlaceActivity.this,
"Google Play Service Error " + resp, Toast.LENGTH_LONG)
.show();
if (alert == null) {
onLocationChangedbuilder = new AlertDialog.Builder(
getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else if (alert.isShowing()) {
alert.dismiss();
onLocationChangedbuilder = new AlertDialog.Builder(
getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
}
onLocationChangedbuilder
.setTitle("Alert!")
.setMessage("Google Play Service Error " + resp)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
locationLockDialogIsShowing = false;
GooglePalyErrorDialogIsShowing = false;
((MenuActivity) getActivity())
.removeFragment(CreatePlaceActivity.this);
}
});
alert = onLocationChangedbuilder.create();
alert.setCancelable(false);
try {
alert.show();
} catch (Exception e) {
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_btn_id:
Log.i(TAG, "lat=" + currentGeoLocation.getLatitude() + "lon="
+ currentGeoLocation.getLongitude() + "acc="
+ currentGeoLocation.getAccuracy() + "alt="
+ currentGeoLocation.getAltitude());
validatePlace();
break;
case R.id.cancel_btn_id:
// finish();
((MenuActivity) getActivity())
.removeFragment(CreatePlaceActivity.this);
break;
default:
break;
}
}
#Override
public void onLocationChanged(Location location) {
float accuracy = 50;
// DateTime dt1 = new DateTime();
// DateTimeFormatter fmt1 = ISODateTimeFormat.dateTime();
Time time = new Time();
time.setToNow();
String strdt = String.valueOf(time.toMillis(false));
if (location != null) {
accuracy = location.getAccuracy();
locationLockDialogIsShowing = true;
if (globalAccuracy - location.getAccuracy() >= 20
|| globalAccuracy - location.getAccuracy() >= -20) {
globalAccuracy = location.getAccuracy();
}
}
if (alert == null) {
onLocationChangedbuilder = new AlertDialog.Builder(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else if (alert.isShowing()) {
alert.dismiss();
onLocationChangedbuilder = new AlertDialog.Builder(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
}
final float accr = accuracy;
onLocationChangedbuilder
.setTitle("Alert!")
.setMessage(
"Getting the best possible location..Please wait.\nCurrent Accuracy is "
+ accuracy)
.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
locationLockDialogIsShowing = false;
if (locationclient != null) {
locationclient.disconnect();
}
Time time = new Time();
time.setToNow();
String strdt = String.valueOf(time
.toMillis(false));
if (alert == null) {
} else if (alert.isShowing()) {
alert.dismiss();
}
if (locationLockAlert == null) {
} else if (locationLockAlert.isShowing()) {
locationLockAlert.dismiss();
}
// setResult(RESULT_OK);
// finish();
((MenuActivity) getActivity())
.removeFragment(CreatePlaceActivity.this);
}
});
alert = onLocationChangedbuilder.create();
alert.setCancelable(false);
try {
alert.show();
} catch (Exception e) {
}
if (location.getAccuracy() <= 16) {
DateTime dt = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String str1 = fmt.print(dt);
locationLockDialogIsShowing = false;
Time timeNow = new Time();
timeNow.setToNow();
String str = String.valueOf(timeNow.toMillis(false));
// locationLockTimestamp = str1;
// TODO
currentGeoLocation = location;
if (locationclient != null) {
if (locationclient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
locationclient, this);
locationclient.disconnect();
}
}
if (alert.isShowing()) {
alert.dismiss();
}
if (locationLockAlert != null) {
if (locationLockAlert.isShowing()) {
locationLockAlert.dismiss();
}
}
showDialog("Alert!",
"GPS Location locked.. You can now continue to create place");
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
final float accuracy = 250;
if (locationclient != null && locationclient.isConnected()) {
if (geoLocationCheck == false) {
locationrequest = LocationRequest.create();
locationrequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationrequest.setInterval(100);
// locationclient.requestLocationUpdates(locationrequest, this);
LocationServices.FusedLocationApi.requestLocationUpdates(
locationclient, locationrequest, this);
locationLockDialogIsShowing = true;
if (alert == null) {
onLocationChangedbuilder = new AlertDialog.Builder(
getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else if (alert.isShowing()) {
alert.dismiss();
onLocationChangedbuilder = new AlertDialog.Builder(
getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
}
onLocationChangedbuilder
.setTitle("Alert!")
.setMessage(
"Getting the best possible location..Please wait.\nCurrent Accuracy is "
+ accuracy)
.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
locationLockDialogIsShowing = false;
if (locationclient != null) {
locationclient.disconnect();
}
Time time = new Time();
time.setToNow();
String strdt = String.valueOf(time
.toMillis(false));
if (alert == null) {
} else if (alert.isShowing()) {
alert.dismiss();
}
if (locationLockAlert == null) {
} else if (locationLockAlert
.isShowing()) {
locationLockAlert.dismiss();
}
// setResult(RESULT_OK);
// finish();
((MenuActivity) getActivity())
.removeFragment(CreatePlaceActivity.this);
}
});
alert = onLocationChangedbuilder.create();
alert.setCancelable(false);
try {
alert.show();
} catch (Exception e) {
}
}
}
}
#Override
public void onConnectionSuspended(int arg0) {
Log.i("fused", "loc client onConnectionSuspended");
}
public Dialog showDialog(String title, String msg) {
locationLockAlert = new AlertDialog.Builder(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
locationLockAlert.setTitle(title);
locationLockAlert.setMessage(msg);
locationLockAlert.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
locationLockAlert.dismiss();
}
});
try {
locationLockAlert.show();
} catch (Exception e) {
}
return locationLockAlert;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
Link I have referred is Android Geofencing (Polygon)
Thanks!
If you know the radius of the circle and its center point, you know if any other point is inside the circle by using the following formula:
which is the distance formula.
Also, if both points are Location objects. you can use Location.distanceTo
Related
I have created a timer that starts timing on a handleClick() and continues timing throughout the app. When I return to the firstActivity I would like the timer to stop in the onResume(). however whenever I return to the firstActivity I get the following error below. How do I solve this?
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.warrenedy.julyfinal.TimeTracker2.isTracking()' on a null object reference
Code Below
#Override
protected void onResume() {
super.onResume();
prepareActivityTextsAndButtons();
prepareTimingButtons();
mTimeTracker2.stopTracker();
Toast.makeText(this, "Onresume call", Toast.LENGTH_SHORT).show();
}
public void handleClick(View v) {
if (DBG) Log.d(LOG_TAG, "handleClick()..");
if (!mServiceBound) return;
switch (v.getId()) {
case R.id.button_activity_start_stop:
onActivityButtonClick(v);
break;
}
}
private void onActivityButtonClick(View v) {
if (DBG)
Log.d(LOG_TAG, "onMeditateButtonClick().. tracking " + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (mTimeTracker2.isTracking()) {
if (mCurrentTrackingActivity == null) return;
if (button == mButtonActivityTimers[mCurrentTrackingActivity.ordinal()]) {
mTimeTracker2.stopTracker();
Utils2.playStopAudio(getApplicationContext());
// button.setText(R.string.str_start);
mCurrentTime.setText(Utils2.secToString(0));
button.setChecked(false);
}
}
}
Code Continued
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DBG) Log.d(LOG_TAG, "onCreate()..");
setContentView(R.layout.activity_meditation_tracker);
getSupportActionBar().hide();
mContext = getApplicationContext();
mSharedpreferences = getSharedPreferences(Utils.MyPREFERENCES, Context.MODE_PRIVATE);
exercise_star = sharedpreferences.getInt("exercise_star", 0);
meditation_star = sharedpreferences.getInt("meditation_star", 0);
study_star = sharedpreferences.getInt("study_star", 0);
isAlarmSet = sharedpreferences.getBoolean("isAlarmSet", false);
/* Retrieve a PendingIntent that will perform a broadcast */
mActivity = MeditationTrackerActivity.this;
mButtonSavePoints = (Button) findViewById(R.id.btn_save_points);
mButtonRestorePoints = (Button) findViewById(R.id.btn_restore_points);
btnHelpBut = (Button) findViewById(R.id.btnHelp);
ACTIVITY_NAMES = getResources().getStringArray(R.array.activity_names);
mCurrentTime = (TextView) findViewById(R.id.tv_current_time);
mCurrentTime.setText(Utils2.secToString(0));
if (!isAlarmSet) {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAlarmSet", true);
ed.commit();
startAlarmService();
}
isAuthenticated = sharedpreferences.getBoolean("isAuth", true);
if (Build.VERSION.SDK_INT < 23) {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
insertPermissionWrapper();
}
}
### StartAlarmService
public void startAlarmService() {
Intent alarmIntent = new Intent(MeditationTrackerActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MeditationTrackerActivity.this, 0, alarmIntent, 0);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 23); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 45); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(this, "Main Alarm Set", Toast.LENGTH_SHORT).show();
}
### CancelAlarm
public void cancelAlarmService() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
### StartService
private void startService() {
Intent serIntent = new Intent(this, TimeTrackingService2.class);
startService(serIntent);
bindService(serIntent, mServiceConnection, BIND_AUTO_CREATE);
}
### UpdateCurrentTime
private void updateCurrentTime() {
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
mCurrentTime.setText(sdf.format(date));
}
### ClientAuthenticationFromServer
private void clientAuthenticationFromServer() {
if (Utils2.getConnectivityStatus(mContext)) {
new Auth(mContext, mActivity).execute(Utils2.URL_VALIDATE_CLIENT);
} else {
Utils2.alertPopup(mContext, "You are not connected to internet.kindly connect with internet and try again.The internet is needed only first time for the authentication of client.After authentication no need of internet.", mActivity);
}
}
###Task Complete
#Override
public void onTaskComplete(boolean result) {
if (!result) {
Utils2.alertPopup(mContext, "You are not a valid client.Contact with the owner of the App.", mActivity);
return;
} else {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAuth", true);
ed.commit();
startService();
}
}
### OnStart
#Override
protected void onStart() {
super.onStart();
// updateCurrentTime();
// IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
// registerReceiver(mTimeTickReceiver, filter);
}
###OnStop
#Override
protected void onStop() {
super.onStop();
// unregisterReceiver(mTimeTickReceiver);
}
### onDestroy
#Override
protected void onDestroy() {
super.onDestroy();
if (mServiceBound) {
unbindService(mServiceConnection);
}
}
### onTimeButtonClick
private void onTimeButtonClick(View v) {
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. tracking" + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. checked ? " + button.isChecked());
if (mTimeTracker2.isTracking()) {
showStopToast();
Utils2.playStopAudio(getApplicationContext());
button.setChecked(false);
return;
} else {
Utils2.playStartAudio(getApplicationContext());
if (button.isChecked()) {
if (mCurrentCheckedButton != null) mCurrentCheckedButton.setChecked(false);
int time = (Integer) v.getTag();
mCountDownSecs = time;
mCurrentCheckedButton = button;
} else {
mCountDownSecs = 0;
mCurrentCheckedButton = null;
}
}
}
###ShowStopToast
private void showStopToast() {
Toast.makeText(this, "Please stop running activity..", Toast.LENGTH_SHORT).show();
}
### onTimerProgress
#Override
public void onTimerProgress(int sec, ACTIVITIES activity) {
if (mCurrentTrackingActivity == null) {
mCurrentTrackingActivity = activity;
}
mCurrentTime.setText(Utils2.secToString(sec));
if (activity == ACTIVITIES.STUDY) {
if (sec == 3600) {
mTimeTracker2.stopTracker();
}
}
}
### onTimerFinish
#Override
public void onTimerFinish(int end, ACTIVITIES activity) {
mCurrentTime.setText(Utils2.secToString(end));
mButtonActivityTimers[activity.ordinal()].setChecked(false);
mCurrentTrackingActivity = null;
Utils2.playStopAudio(getApplicationContext());
}
private void prepareActivityTextsAndButtons() {
for (int i = 0; i < ACTIVITY_COUNT; i++) {
View parent = findViewById(ACTIVITY_LAYOUT_IDS[i]);
mTextActivityNames[i] = (TextView) parent.findViewById(R.id.tv_activity_name);
mTextActivityNames[i].setText(ACTIVITY_NAMES[i]);
//mTextActivityTimers[i] = (TextView) parent.findViewById(R.id.tv_timer_progress);
mRatingBars[i] = (RatingBar) parent.findViewById(R.id.ratingBar);
mButtonActivityTimers[i] = (ToggleButton) parent.findViewById(R.id.button_activity_start_stop);
mButtonActivityTimers[i].setText(null);
mButtonActivityTimers[i].setTextOn(null);
mButtonActivityTimers[i].setTextOff(null);
mButtonActivityTimers[i].setTag(ACTIVITIES.values()[i]);
}
}
private void prepareTimingButtons() {
mTimingButtons = new ToggleButton[7];
mTimingButtons[0] = (ToggleButton) findViewById(R.id.button_timer_0);
addTextToTimingButtons(5, mTimingButtons[0]);
}
private void addTextToTimingButtons(int min, Button button) {
// button.setText(min + " " + getString(R.string.str_min));
button.setTag(min * 60);
}
public void onCustomTimeStarted(int secs) {
if (DBG) Log.d(LOG_TAG, "onCustomTimeStarted : secs " + secs);
if (mTimeTracker2.isTracking()) {
showStopToast();
} else {
int oneday = 24 * 3600;
if (secs > oneday) {
Toast.makeText(this, "Adjusted to 24 hrs", Toast.LENGTH_SHORT).show();
secs = oneday;
} else if (secs < 60) {
Toast.makeText(this, "Should be at least a minute.", Toast.LENGTH_SHORT).show();
return;
}
mTimingButtons[6].setChecked(true);
mTimingButtons[6].setTag(secs);
onTimeButtonClick(mTimingButtons[6]);
//mTimeTracker2.startTracker(secs, this);
//mButtonMeditate.setText(R.string.meditate_stop);
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
}
return true;
}
private void insertPermissionWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add("READ_PHONE_STATE");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
return;
} else {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
}
// insertDummyContact();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.app.AlertDialog.Builder(MeditationTrackerActivity.this)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
) {
// All Permissions Granted
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
// Permission Denied
Toast.makeText(MeditationTrackerActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void setBootReceiverEnabled(int componentEnabledState) {
ComponentName componentName = new ComponentName(this, DeviceBootReceiver.class);
PackageManager packageManager = getPackageManager();
packageManager.setComponentEnabledSetting(componentName,
componentEnabledState,
PackageManager.DONT_KILL_APP);
};
TimeTracker2.class
public class TimeTracker2 {
private static final int MSG_TRACKER_STOPPED = 1;
private static final int MSG_TRACKER_PROGRESS_UPDATE = 2;
private Context mContext;
private boolean mIsTrackingInProgress;
private TrackerServiceCallback mServiceCallback;
private TimerProgressCallback2 mProgressCallback;
private Timer mTimer = new Timer();
private TimerHandler mTimerHandler = new TimerHandler();
private TimerTask mIncrementTask, mDecrementTask;
private int mCounter;
private int mMaxCounter;
private MeditationTrackerActivity.ACTIVITIES mCurrentTrackingActivity;
private class IncrementTask extends TimerTask {
IncrementTask() {
mCounter = 0;
}
#Override
public void run() {
mCounter++;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
private class DecrementTask extends TimerTask {
DecrementTask(int sec) {
mCounter = sec;
}
#Override
public void run() {
if (mCounter == 0) {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_PIP, 500);
cancel();
mTimerHandler.sendEmptyMessage(MSG_TRACKER_STOPPED);
return;
}
mCounter --;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
public interface TimerProgressCallback2 {
void onTimerProgress(int sec, MeditationTrackerActivity.ACTIVITIES activity);
void onTimerFinish(int end, MeditationTrackerActivity.ACTIVITIES activity);
}
public TimeTracker2(Context context, TrackerServiceCallback serviceCallback) {
mContext = context;
mServiceCallback = serviceCallback;
}
public void startTracker(int time_secs, TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = time_secs;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mDecrementTask = new DecrementTask(time_secs);
mTimer.scheduleAtFixedRate(mDecrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void startTracker(TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = 0;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mIncrementTask = new IncrementTask();
mTimer.scheduleAtFixedRate(mIncrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void setTimerProgressCallback(TimerProgressCallback2 callback) {
if (!mIsTrackingInProgress) return;
mProgressCallback = callback;
}
public void removeTimerProgressCallback() {
mProgressCallback = null;
}
public void stopTracker() {
if (!mIsTrackingInProgress) {
Log.i(LOG_TAG, "stopTracker().. Tracker NOT started!!");
return;
}
mIsTrackingInProgress = false;
mServiceCallback.onTrackerStarted(false);
if (mProgressCallback != null) mProgressCallback.onTimerFinish(mCounter, mCurrentTrackingActivity);
mProgressCallback = null;
if (mIncrementTask != null) mIncrementTask.cancel();
if (mDecrementTask != null) mDecrementTask.cancel();
updateDb();
mCurrentTrackingActivity = null;
}
public boolean isTracking() {
return mIsTrackingInProgress;
}
public MeditationTrackerActivity.ACTIVITIES getCurrentTrackingActivity() {
return mCurrentTrackingActivity;
}
private class TimerHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if (DBG) Log.d(LOG_TAG, "handleMessage()..");
switch (msg.what) {
case MSG_TRACKER_PROGRESS_UPDATE:
if (mProgressCallback != null) mProgressCallback.onTimerProgress(mCounter, mCurrentTrackingActivity);
break;
case MSG_TRACKER_STOPPED:
default:
stopTracker();
break;
}
}
}
private void updateDb() {
final int secs = mMaxCounter > 0 ? mMaxCounter - mCounter : mCounter;
final MeditationTrackerActivity.ACTIVITIES activity = mCurrentTrackingActivity;
AsyncTask.execute(new Runnable() {
#Override
public void run() {
TrackerDb3.insertOrUpdateMeditation(mContext, secs, activity);
}
});
}
}
why is that when i make a touched pinpoint, it only takes the last pinpoints in the arraylist. When i measure the arraylist size, it says that the size is 1 even though I am saving 2 or more pinpoints.
GoogleMaps Class.
public class GoogleMaps extends MapActivity implements LocationListener {
public void addLocation() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setTitle("What do you want to call the location?");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString().trim();
checklocationTitle();
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
public void checklocationTitle() {
if (value.length() > 3) {
Toast.makeText(this, "Name of the locations is know " + value,
Toast.LENGTH_LONG).show();
try {
markedpinpoint = true;
midllat = touchedPoint.getLatitudeE6() / 1E6;
midlongi = touchedPoint.getLongitudeE6() / 1E6;
Geocoder geocoder = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> adress = geocoder.getFromLocation(
touchedPoint.getLatitudeE6() / 1E6,
touchedPoint.getLongitudeE6() / 1E6, 1);
if (adress.size() > 0) {
String display = "";
for (int i = 0; i < adress.get(0).getMaxAddressLineIndex(); i++) {
display += adress.get(0).getAddressLine(i) + "\n";
OverlayItem overlayitem = new OverlayItem(touchedPoint,
value, display);
custom = new Location_Service(d, GoogleMaps.this);
custom.insertLocation(overlayitem);
overlayList.add(custom);
}
} else {
Toast.makeText(
this,
"There where a problem to locate the selected adresse",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
}
} else {
Toast.makeText(this,
"Please provide a least 3 cifre Title for your location.",
Toast.LENGTH_LONG).show();
addLocation();
}
}
public void buttonLocations(View view) {
// stopLocationListner();
// stopBackgroundService();
Intent intent = new Intent(this, PinPoints.class);
startActivity(intent);
// Toast.makeText(this, "Gemte steder: " + custom.size(),
// Toast.LENGTH_LONG).show();
}
}
Location_Service Class
public class Location_Service extends ItemizedOverlay<OverlayItem> {
public ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
public Location_Service(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
// TODO Auto-generated constructor stub
}
public ArrayList<Locations> getData() {
Locations hej = new Locations();
ArrayList<Locations> tt = new ArrayList<Locations>();
for (OverlayItem test : pinpoints) {
hej.setAdress(test.getSnippet());
hej.setMidlat(test.getPoint().getLatitudeE6());
hej.setMidlong(test.getPoint().getLongitudeE6());
hej.setTitle(test.getTitle());
tt.add(hej);
}
return tt;
}
public Location_Service(Drawable m, Context context) {
this(m);
}
#Override
protected OverlayItem createItem(int i) {
return pinpoints.get(i);
}
#Override
public int size() {
return pinpoints.size();
}
public void insertLocation(OverlayItem item) {
pinpoints.add(item);
this.populate();
}
}
You're adding the same Locations object to the list repeatedly in getData()... you're not instantiating a new object.
You probably really meant
ArrayList<Locations> tt = new ArrayList<Locations>();
for (OverlayItem test : pinpoints) {
Locations hej = new Locations(); //instantiate each time!
hej.setAdress(test.getSnippet());
hej.setMidlat(test.getPoint().getLatitudeE6());
hej.setMidlong(test.getPoint().getLongitudeE6());
hej.setTitle(test.getTitle());
tt.add(hej);
}
return tt;
I am using SIPDEMO application . when i am login by username , domain, and password . it give me "Registration fail error" ..
I have checked in my iphone and working well . so there is not any problem in my sip accounts.
i have also read the completed code but unable to find any error
please expert help me
this is code:-
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.walkietalkie);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(this);
Log.v("sip_test", "manager: " + manager.toString());
Log.v("sip_test", "isApiSupported: " + new Boolean(SipManager.isApiSupported(this)).toString());
Log.v("sip_test", "isSipWifiOnly: " + new Boolean(SipManager.isSipWifiOnly(this)).toString());
Log.v("sip_test", "isVoipSupported: " + new Boolean(SipManager.isVoipSupported(this)).toString());
}
initializeLocalProfile();
}
/**
* Logs you into your SIP provider, registering this device as the location to
* send SIP calls to for your SIP address.
*/
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String username = prefs.getString("namePref", "");
String domain = prefs.getString("domainPref", "");
String password = prefs.getString("passPref", "");
System.out.println("username " +username);
System.out.println("domain " +domain);
System.out.println("password " +password);
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
showDialog(UPDATE_SETTINGS_DIALOG);
return;
}
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
me = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
System.out.println("local profile uri " + localProfileUri);
System.out.println("error code" + errorCode);
System.out.println("error message " +errorMessage);
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
System.out.println("parse exception"+pe.getMessage());
} catch (SipException se) {
updateStatus("Connection error.");
System.out.println("Connection exception"+se.getMessage());
}
}
/**
* Closes out your local profile, freeing associated objects into memory
* and unregistering your device from the server.
*/
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
/**
* Make an outgoing call.
*/
public void initiateCall() {
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
}
catch (Exception e) {
Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
Log.i("WalkieTalkieActivity/InitiateCall",
"Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
/**
* Updates the status box at the top of the UI with a messege of your choice.
* #param status The String to display in the status box.
*/
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
/**
* Updates the status box with the SIP address of the current call.
* #param call The current, active call.
*/
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if(useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
/**
* Updates whether or not the user's voice is muted, depending on whether the button is pressed.
* #param v The View where the touch event is being fired.
* #param event The motion to act on.
* #return boolean Returns false to indicate that the parent view should handle the touch event
* as it normally would.
*/
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CALL_ADDRESS:
showDialog(CALL_ADDRESS);
break;
case SET_AUTH_INFO:
updatePreferences();
break;
case HANG_UP:
if(call != null) {
try {
call.endCall();
} catch (SipException se) {
Log.d("WalkieTalkieActivity/onOptionsItemSelected",
"Error ending call.", se);
}
call.close();
}
break;
}
return true;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CALL_ADDRESS:
LayoutInflater factory = LayoutInflater.from(this);
final View textBoxView = factory.inflate(R.layout.call_address_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Call Someone.")
.setView(textBoxView)
.setPositiveButton(
android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textField = (EditText)
(textBoxView.findViewById(R.id.calladdress_edit));
// sipAddress = textField.getText().toString();
sipAddress= "sip:kukukkk#ekiga.net";
initiateCall();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
})
.create();
case UPDATE_SETTINGS_DIALOG:
return new AlertDialog.Builder(this)
.setMessage("Please update your SIP Account Settings.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
updatePreferences();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
})
.create();
}
return null;
}
public void updatePreferences() {
Intent settingsActivity = new Intent(getBaseContext(),
SipSettings.class);
startActivity(settingsActivity);
}
}
Check your android phone is Sip supported or not.
Confirm this code is included in Manifest file:
<uses-sdk android:minSdkVersion="9" />
I am having problems making my TextViews visible from another thread using the method showDisclaimer(). I have used runOnUiThread() to set the visibility of my TextViews. Basically, I want to show these views after importing the csv to the database. Can you take a look and see what I missed?
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView homeText1 = (TextView) findViewById(R.id.home_text1);
TextView homeText2 = (TextView) findViewById(R.id.home_text2);
TextView homeText3 = (TextView) findViewById(R.id.home_text3);
TextView homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
//db = new DatabaseHandler(MainActivity.this);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
if(!uploadDateEqualsDateInFile())
promptOptionalUpdate("There is a new schedule");
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
promptRequiredUpdate("Schedule not updated");
//showDisclaimer();
Log.i("oncreate", "finished!");
}
public void promptOptionalUpdate(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
dropOldSchedule();
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dropOldSchedule(){
//TODO drop old schedule
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Downloading schedule",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL myURL = new URL(csvFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
String[] sched = output.split(",");
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
e.printStackTrace();
}
}
else {
break;
}
}
so.close();
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
getUploadDate();
writeUploadDateInTextFile();
showDisclaimer();
pd.dismiss();
}
});
}
});
thread.start();
//while(thread.isAlive());
Log.d("triggerDownload", "thread died, finished dl. showing disclaimer...");
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
thread.start();
while (thread.isAlive());
Log.d("getUploadDate","thread died, upload date="+str);
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
TextView homeText1x = (TextView) findViewById(R.id.home_text1);
TextView homeText2x = (TextView) findViewById(R.id.home_text2);
TextView homeText3x = (TextView) findViewById(R.id.home_text3);
TextView homeText4x = (TextView) findViewById(R.id.home_text4);
homeText3x
.setText("You may view the schedule of pre-arranged power interruptions by clicking any of these buttons : SIN, City or Date. " +
"The schedule has been updated as of " + str
+ ". Meralco is exerting all efforts to restore electric service as scheduled." +
" The schedule, however, may change without further notice. For verification, follow-ups, or " +
"latest updates, please contact our CALL CENTER through telephone nos. 16211, " +
"fax nos. 1622-8554/1622-8556 or email address callcenter.tech.assist#meralco.com.ph.");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
}
public void promptRequiredUpdate(String Message) {
Log.d("required update","required!");
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
getUploadDate();
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void showAlert(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setMessage(Message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
simplymoody, do what Chirag Raval suggested by declaring private static TextView homeText1, globally and in your onCreate initialise them. However, you should always update the UI from the main thread. But showDisclaimer() is still running on the background thread, so you could run the showDisclaimer() a couple of different ways. One would be to do what you have done in getUploadDate():
runOnUiThread(new Runnable() {
public void run() {
showDisclaimer()
}
});
Or you could use a handler:
private Handler showDisclaimerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
homeText3x.setText("TEXT");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
return false;
}
});
And everywhere in a background thread you wish to run your showDisclaimer(), instead you run:
showDisclaimerHandler.sendEmptyMessage(0);
i m getting null jsonarray , using official android Facebook api example code Hackbook for user Check in and nearest places list.
public class Places extends Activity implements OnItemClickListener {
private Handler mHandler;
private JSONObject location;
protected ListView placesList;
private Facebook mFacebook;
protected LocationManager lm;
protected MyLocationListener locationListener;
private AsyncFacebookRunner mAsyncRunner;
protected static JSONArray jsonArray;
final static double TIMES_SQUARE_LAT = 40.756;
final static double TIMES_SQUARE_LON = -73.987;
protected ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
location = new JSONObject();
setContentView(R.layout.places_list);
mFacebook = new Facebook(Constants.FB_APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle extras = getIntent().getExtras();
String default_or_new = extras.getString("LOCATION");
if (default_or_new.equals("times_square")) {
try {
location.put("latitude",new Double(TIMES_SQUARE_LAT) );
location.put("longitude",new Double(TIMES_SQUARE_LON));
} catch (JSONException e) {
}
fetchPlaces();
} else {
getLocation();
}
}
public void getLocation() {
/*
* launch a new Thread to get new location
*/
new Thread() {
#Override
public void run() {
Looper.prepare();
dialog = ProgressDialog.show(Places.this, "","Fetching Location", false, true,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
showToast("No location fetched.");
}
});
if (lm == null) {
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
if (locationListener == null) {
locationListener = new MyLocationListener();
}
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
if (provider != null && lm.isProviderEnabled(provider)) {
lm.requestLocationUpdates(provider, 1, 0, locationListener,
Looper.getMainLooper());
} else {
/*
* GPS not enabled, prompt user to enable GPS in the
* Location menu
*/
new AlertDialog.Builder(Places.this)
.setTitle("enable_gps_title")
.setMessage("enable_gps")
.setPositiveButton("GPS Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Places.this.finish();
}
}).show();
}
Looper.loop();
}
}.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/*
* User returning from the Location settings menu. try to fetch location
* again.
*/
dialog.dismiss();
getLocation();
}
/*
* Fetch nearby places by providing the search type as 'place' within 1000
* mtrs of the provided lat & lon
*/
private void fetchPlaces() {
if (!isFinishing()) {
dialog = ProgressDialog.show(Places.this, "", "nearby_places", true,
true, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
showToast("No places fetched.");
}
});
}
/*
* Source tag: fetch_places_tag
*/
Bundle params = new Bundle();
params.putString("type", "place");
try {
params.putString("center",
location.getString("latitude") + "," + location.getString("longitude"));
} catch (JSONException e) {
showToast("No places fetched.");
return;
}
params.putString("distance", "1000");
mAsyncRunner.request("search", params, new placesRequestListener());
}
/*
* Callback after places are fetched.
*/
public class placesRequestListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
Log.d("Facebook-FbAPIs", "Got response: " + response);
dialog.dismiss();
try {
jsonArray = new JSONObject(response).getJSONArray("data");
if (jsonArray == null) {
showToast("Error: nearby places could not be fetched");
return;
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
mHandler.post(new Runnable() {
#Override
public void run() {
placesList = (ListView) findViewById(R.id.places_list);
placesList.setOnItemClickListener(Places.this);
placesList.setAdapter(new PlacesListAdapter(Places.this));
}
});
}
public void onFacebookError(FacebookError error) {
dialog.dismiss();
showToast("Fetch Places Error: " + error.getMessage());
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
if (!mFacebook.isSessionValid()) {
Util.showAlert(this, "Warning", "You must first log in.");
} else {
try {
final String message = "Check-in from the " + getString(R.string.app_name);
final String name = jsonArray.getJSONObject(position).getString("name");
final String placeID = jsonArray.getJSONObject(position).getString("id");
new AlertDialog.Builder(this).setTitle("check_in_title")
.setMessage(String.format("check_in_at"))
.setPositiveButton("Chaeck in", new DialogInterface.OnClickListener() {
/*
* Source tag: check_in_tag Check-in user at the
* selected location posting to the me/checkins
* endpoint. More info here:
* https://developers.facebook
* .com/docs/reference/api/user/ - checkins
*/
#Override
public void onClick(DialogInterface dialog, int which) {
Bundle params = new Bundle();
params.putString("place", placeID);
params.putString("message", message);
params.putString("coordinates", location.toString());
mAsyncRunner.request("me/checkins", params, "POST",
new placesCheckInListener(), null);
}
}).setNegativeButton(R.string.cancel, null).show();
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
}
}
}
public class placesCheckInListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
showToast("API Response: " + response);
}
public void onFacebookError(FacebookError error) {
dialog.dismiss();
showToast("Check-in Error: " + error.getMessage());
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(Places.this, msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
/**
* Definition of the list adapter
*/
public class PlacesListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
Places placesList;
public PlacesListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return jsonArray.length();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
View hView = convertView;
if (convertView == null) {
hView = mInflater.inflate(R.layout.place_item, null);
ViewHolder holder = new ViewHolder();
holder.name = (TextView) hView.findViewById(R.id.place_name);
holder.location = (TextView) hView.findViewById(R.id.place_location);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
try {
holder.name.setText(jsonObject.getString("name"));
} catch (JSONException e) {
holder.name.setText("");
}
try {
String location = jsonObject.getJSONObject("location").getString("street") + ", "
+ jsonObject.getJSONObject("location").getString("city") + ", "
+ jsonObject.getJSONObject("location").getString("state");
holder.location.setText(location);
} catch (JSONException e) {
holder.location.setText("");
}
return hView;
}
}
class ViewHolder {
TextView name;
TextView location;
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
dialog.dismiss();
if (loc != null) {
try {
location.put("latitude", new Double(loc.getLatitude()));
location.put("longitude", new Double(loc.getLongitude()));
} catch (JSONException e) {
}
showToast("Location acquired: " + String.valueOf(loc.getLatitude()) + " "
+ String.valueOf(loc.getLongitude()));
lm.removeUpdates(this);
fetchPlaces();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Getting Jsonarray null in below line:
jsonArray = new JSONObject(response).getJSONArray("data");
let me know what is wrong in this above code thnx a lot