Null pointer Exception while calling Asynctask situated inside fragment - android

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.

Related

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.

How to integrate Google Plus and Facebook Authentication together in the same activity of Android project?

I need to to integrate both Facebook and Google Plus in the same activity but I'm not getting success in it. I have tried both in individual projects and they work fine but when I add both projects together my app gets crashed. Even I have tried them with custom buttons too but they don't work either.
Currently my Facebook part is working fine but I get error when I click on Google's button at the time of login. I get error in these methods:
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
and
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
I'm implementing in this class:
public class LoginActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
// Your Facebook APP ID
private static String APP_ID = "XXXXXXXXXXXXXXX"; // Replace with your App
// ID
LinearLayout ll;
// Strings of Facebook
String fb_mUserId = "", fb_mUserToken = "", fb_mUserName = "",
fb_mUserEmail = "", fb_verified_value = "", fb_Task_message;
boolean fb_verified, google_verified;
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
#SuppressWarnings("unused")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
EditText edittext_username, edittext_password;
Button Btn_login, Btn_register;
TextView Text_univesity, errorMsg, tv_forget_password;
LinearLayout ll_google, ll_fb;
static String Username, password, name, Twilio_Id = "",
name_candidate = "", phone_no = "", email_candidate = "",
country = "", mobile_verification = "", fb_id = "";
ImageView im;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
int id, Mode = 0, fb_clicked = 0, google_clicked = 0;
static int user_ids;
String IMEI_number;
GPSTracker gps;
static double latitude = 0.00, longitude = 0.00;
Context context;
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "LoginActivity";
// Profile pic image size in pixels
// private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
// Strings of Google Plus
String google_email="", google_id="", google_name="", google_verified_value="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
IMEI_number = telephonyManager.getDeviceId();
im = (ImageView) findViewById(R.id.header);
mAsyncRunner = new AsyncFacebookRunner(facebook);
if (Mode == 3) {
if (login_details.contains("name")) {
name = login_details.getString("name", "");
Intercom.client().registerIdentifiedUser(
new Registration().withUserId(name));
} else {
Intercom.client().registerIdentifiedUser(
new Registration().withUserId("123456"));
}
// We're logged in, we can register the user with Intercom
// Carry on as normal
Intent mode = new Intent(LoginActivity.this, MenuItems.class);
startActivity(mode);
finish();
} else {
edittext_password = (EditText) findViewById(R.id.et_login_password);
Btn_login = (Button) findViewById(R.id.btn_login);
Btn_register = (Button) findViewById(R.id.btn_login_register);
ll_fb = (LinearLayout) findViewById(R.id.login_fb);
ll_google = (LinearLayout) findViewById(R.id.login_google);
tv_forget_password = (TextView) findViewById(R.id.tv_login_forget_password);
Btn_login.setOnClickListener(this);
Btn_register.setOnClickListener(this);
ll_fb.setOnClickListener(this);
ll_google.setOnClickListener(this);
tv_forget_password.setOnClickListener(this);
// Initializing google plus api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE).build();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
// Direct Login Process
break;
case R.id.btn_login_register:
// Direct register process
finish();
break;
case R.id.login_fb:
fb_clicked++;
loginToFacebook();
getProfileInformation();
if (!fb_mUserEmail.equals("")) {
if (fb_verified == true) {
fb_verified_value = "1";
} else {
fb_verified_value = "0";
}
new FacebookAsynTask().execute();
}
break;
case R.id.login_google:
google_clicked++;
signInWithGplus();
// getGoogleProfileInformation();
if (!google_email.equals("")) {
if (google_verified == true) {
google_verified_value = "1";
} else {
google_verified_value = "0";
}
new GoogleAsynTask().execute();
}
break;
case R.id.tv_login_forget_password:
break;
}
}
#Override
protected void onResume() {
super.onResume();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/** LOGIN TO FACEBOOK */
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
Toast.makeText(LoginActivity.this, "FIRST CASE", Toast.LENGTH_SHORT)
.show();
getProfileInformation();
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Toast.makeText(LoginActivity.this, "SECOND CASE",
Toast.LENGTH_SHORT).show();
getProfileInformation();
// Making Login button invisible
}
public void onError(DialogError error) {
// Function to handle error
}
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (fb_clicked != 0) {
facebook.authorizeCallback(requestCode, resultCode, data);
fb_clicked = 0;
}
else if (google_clicked != 0) {
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
google_clicked = 0;
}
}
/**
* Get Profile information by making request to Facebook Graph API
* */
public void getProfileInformation() {
try {
JSONObject profile = Util.parseJson(facebook.request("me"));
Log.e("Profile", "" + profile);
fb_mUserId = profile.getString("id");
fb_verified = profile.getBoolean("verified");
fb_mUserToken = facebook.getAccessToken();
fb_mUserName = profile.getString("name");
fb_mUserEmail = profile.getString("email");
runOnUiThread(new Runnable() {
public void run() {
Log.e("FaceBook_Profile", "" + fb_mUserId + "\n"
+ fb_mUserToken + "\n" + fb_mUserName + "\n"
+ fb_mUserEmail);
}
});
} catch (FacebookError e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/** AsyncTask of Direct Login */
class FacebookAsynTask extends AsyncTask<Void, Void, Void> {
}
/** GOOGLE's CODE STARTS */
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getGoogleProfileInformation();
// Update the UI after signin
// updateUI(true);
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
// updateUI(false);
}
/**
* Fetching user's information name, email, profile pic
* */
private void getGoogleProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
google_name = currentPerson.getDisplayName();
google_id = currentPerson.getId();
google_verified = currentPerson.isVerified();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
google_email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + google_name + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + google_email
+ ", Image: " + personPhotoUrl);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
class GoogleAsynTask extends AsyncTask<Void, Void, Void> {
}
It would be great if anybody helps me in it.
Thanks.
I've solved my problem myself yesterday by adding few lines in onClick part
if (mGoogleApiClient.isConnected()) {
getProfileInformation();
} else {
signInWithGplus();
getProfileInformation();
}
}
It appears that if you call signInWithGplus() the first time, it'll try to access mConnectionResult which is null at that point.
The reason for that is because you're only setting it in onConnectionFailed() which would have not been called.

Content quickly disappears

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

Google GCM client not sending messages after unregistering/registering the BroadcastReceiver programatically

I would like to register/unregister the BroadcastReceiver which I am using to receive messages from GCM. I have declared and initialised the BroadcastReceiver.class in my onResume(), but after I unregister inside onPause() next time my app launches it wont send messages any more, only if I send the regId again and register with the GCM server as well.
Can the BroadcastReceiver be responsible for not sending the messages? Or is it essential to have the BroadcastReceiver registered in the Manifest file??
I would be really grateful for any suggestion.
UPDATE:
Interestingly if I register the BroadcastReceiver programatically, the GCM server gives a new regId all the time when registering the device itself on the GCM server, when the BroadcastReceiver is registered in the Manifest, the GCM server gives the same regId. WHY??
Methods for registering/unregistering:
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
receiver = new GcmBroadcastReceiver();
filter.addAction("com.google.android.c2dm.intent.RECEIVE");
filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
filter.addCategory("com.taxidirectdriver");
registerReceiver(receiver, filter, "com.google.android.c2dm.permission.SEND", null);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Full MainActivity:
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private static final String PROPERTY_APP_VERSION = "appVersion";
GoogleCloudMessaging gcm;
String regid;
Context context;
AtomicInteger msgId = new AtomicInteger();
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;
public SharedPreferences pref;
public static String DNAME = "dname";
public static final String REGID="regid";
String driverName;
private static final float DEFAULTZOOM = 15;
private static final String TAG = null;
private static long locRefresh = 300000;
private static long fastestRefresh = 120000;
LocationClient mLocationClient;
Marker marker;
Geocoder geocoder;
List<Address> addresses;
ArrayList<Double> drivers = new ArrayList<Double>();
Map<String,Double> nameAndDistance = new HashMap<String, Double>();
String address;
OrdersDBHelper dbHelper;
private GcmBroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isOnline()){
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
driverName = pref.getString(DNAME, "none");
if(driverName == null || driverName == "none") {
Intent i = new Intent(this, Registration.class);
startActivity(i);
} else {
// GCM startup
gcm = GoogleCloudMessaging.getInstance(this);
context = getApplicationContext();
regid = getRegistrationId(context);
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
regid = pref.getString(REGID, "");
if (regid == null || regid.equals("")){
registerInBackground();
}
} // end of else statement
// Initiate Map if services exists
if (servicesOK() && isOnline() && isLocationOn()) {
setContentView(R.layout.map_activity);
if (initMap()) {
//Toast.makeText(this, "Ready To map!", Toast.LENGTH_SHORT).show();
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
else {
Toast.makeText(this, "Map Not Available!", Toast.LENGTH_SHORT).show();
}
}
else {
Intent conInt = new Intent(this, ConnDependencies.class);
conInt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(conInt);
}
} else {
Intent conInt = new Intent(this, ConnDependencies.class);
conInt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(conInt);
} //end is online
}
#Override
protected void onResume() {
super.onResume();
locRefresh = 300000;
fastestRefresh = 120000;
Log.i(TAG, "Resfresh interval set to "+ locRefresh + " millis");
/*
//experimental receiver registration
IntentFilter filter = new IntentFilter();
receiver = new GcmBroadcastReceiver();
filter.addAction("com.google.android.c2dm.intent.RECEIVE");
filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
filter.addCategory("com.taxidirectdriver");
registerReceiver(receiver, filter, "com.google.android.c2dm.permission.SEND", null);
*/
if(isOnline() && isLocationOn()){
Log.i(TAG, "Location and internet ok!");
} else {
Intent conInt = new Intent(this, ConnDependencies.class);
conInt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(conInt);
}
}
#Override
protected void onPause() {
super.onPause();
locRefresh = 21600000;
fastestRefresh = 21600000;
Log.i(TAG, "Resfresh interval set to "+ locRefresh + "(6 hours) millis");
//unregisterReceiver(receiver);
}
public void exitApp (){
Intent inn = new Intent(this, DialogAlert.class);
startActivity(inn);
//unregisterReceiver(receiver);
Log.i(TAG, "Receiver unregistered!");
finish();
}
public boolean isLocationOn(){
LocationManager locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(locman.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return true;
}
return false;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
public void showOrders(View view) {
Intent intent = new Intent(this, ClientDetails.class);
startActivity(intent);
}
// Check for Play Services
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Cant Connect to Google Play services", Toast.LENGTH_SHORT).show();
}
return false;
}
// Initializing map
private boolean initMap(){
if (mMap == null){
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
// My Location
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
//Toast.makeText(this, "Connected to current location service", Toast.LENGTH_SHORT).show();
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(locRefresh);
request.setFastestInterval(fastestRefresh);
mLocationClient.requestLocationUpdates(request, this);
//Marking users location
Location currentLocation = mLocationClient.getLastLocation();
LatLng ll = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, DEFAULTZOOM);
mMap.animateCamera(update);
if (marker != null){
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(driverName)
.position(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_marker));
marker = mMap.addMarker(options);
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, DEFAULTZOOM);
mMap.animateCamera(update);
if (marker != null){
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(driverName)
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_marker));
//.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
marker = mMap.addMarker(options);
final int DEFAULT_TIMEOUT = 20 * 1000;
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(DEFAULT_TIMEOUT);
if (location.getLatitude() != 0) {
RequestParams params = new RequestParams();
params.put("NAME", driverName);
params.put("REGID", regid);
params.put("LAT", String.valueOf(location.getLatitude()));
params.put("LNG", String.valueOf(location.getLongitude()));
client.post("http://edmondvarga.com/android_dev/taxidirect/update_coor.php", params, new AsyncHttpResponseHandler() {
#Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
//Toast.makeText(getApplicationContext(), "ERROR UPDATING POSITION!", Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
Log.d("HTTP", "onSuccess, coordinates sent!");
}
});
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground()
{
new AsyncTask<Void, Void, String>()
{
#Override
protected String doInBackground(Void... params)
{
String msg = "";
try
{
if (gcm == null)
{
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(Globals.GCM_SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over
// HTTP, so it can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we use upstream GCM messages to send the
// registration ID to the 3rd party server
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
}
catch (IOException ex)
{
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
#Override
protected void onPostExecute(String msg)
{
//Toast.makeText(getApplicationContext(), "regId is: " + regid, Toast.LENGTH_SHORT).show();
}
}.execute(null, null, null);
}
/**
* Store regid and the app version in SETTINGS_PREF
*
*/
private void storeRegistrationId(Context context, String regid) {
int appVersion = getAppVersion(context);
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(REGID,regid);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Sends the registration ID to the 3rd party server via an upstream
* GCM message. Ideally this would be done via HTTP to guarantee success or failure
* immediately, but it would require an HTTP endpoint.
*/
private void sendRegistrationIdToBackend()
{
String name = driverName;
Log.d(Globals.TAG, "Driver name is: " + driverName + " " + "REGISTER USERID: " + regid);
new AsyncTask<String, Void, String>()
{
#Override
protected String doInBackground(String... params)
{
String msg = "";
try
{
Bundle data = new Bundle();
data.putString("name", params[0]);
data.putString("action", "com.taxidirect.gcmdemo.REGISTER");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(Globals.GCM_SENDER_ID + "#gcm.googleapis.com", id, Globals.GCM_TIME_TO_LIVE, data);
msg = "Sent registration";
}
catch (IOException ex)
{
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg)
{
//Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}.execute(name);
}
/**
* Gets the current registration ID for application on GCM service, if there
* is one.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context)
{
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
String registrationId = pref.getString(REGID, "");
if (registrationId == null || registrationId.equals(""))
{
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = pref.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion)
{
Log.i(Globals.TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context)
{
try
{
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
}
catch (NameNotFoundException e)
{
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.exitApp:
exitApp();
return true;
}
return super.onOptionsItemSelected(item);
}
}
RegIds for the same phone after 4 registering attempts on the GCM Server:
Records are: D1 : APA91bEYZYdKgdngfbxYIjyvhtWm-1ncGOBz1OUER8lM_BfnAwU8IwFAOkawMCgyETGTnHgTOUETKcfYUXUeRvDbEOEoSLexKNh6T9vo4FnBLD7ZajJ0FjahrTNTLrMIafzz0VPw3E5ApK4uCoUM6ibwETQrkDo2RQ
Records are: D2 : APA91bETu7NDrbBGhx4iSUB3YbYq3SG4ZitS_MFFL94CSk13hY_WhOf7HEwyshSnlb2iEmHja3T_qPq1PKfTPre1UGKHkGCpg3xW02HTwBhgp18kQoqUp-MEChN-BJqlDtnDh8A-dHXhGdCRYdd0ou_HYY-MQvOkxA
Records are: 3 : APA91bF2BM3UIg9eLk8Jkj3PwFTsvRD5-1p3CQ3QkFKkhfUm8rfbuchdfwITdErx4p8_L2XWu5f1dU6ZSn9L1uyjqNY6ZMvHsn4kXS2J6Csf1sdjGct444xZZl8P56bIqUaX5Deotm-4eUCD-RBEIHhBK24RTBvtuQ
Records are: 6 : APA91bFYWdORwtUP8b02RZjnL7UBrdBTk3_RRn818F1RV2kMF9T7eQvrGfjmg7qy61drJTlnFqORDmcxKnLiIGC13Gve9qYmO1xd2ZhJX72Llskpm_AWE8bSth7D_9iS6m-BSXcTe25vG4AMxOOmryfSbwR2VmwA-Q
If you dynamically register the receiver, it isn't helpful if you receive a message when the app is not running. See this post:
Dynamic register of C2DM receiver using registerReceiver
If you want to ignore messages when the app is not active, you can set flags. But it seems like dynamic registration is not a good plan either way.

An error occured during retrieval of video in you tube

I am making an app in whic h i hava to you stream you tube video and show in my app but i am getting error message an error occured during retrieval of video.My code snippet is as follows:
public class Rads extends Activity {
public static final String SCHEME_YOUTUBE_VIDEO = "ytv";
public static final String SCHEME_YOUTUBE_PLAYLIST = "ytpl";
static final String YOUTUBE_VIDEO_INFORMATION_URL = "http://www.youtube.com/get_video_info?&video_id=";
static final String YOUTUBE_PLAYLIST_ATOM_FEED_URL = "http://gdata.youtube.com/feeds/api/playlists/";
protected ProgressBar mProgressBar;
protected TextView mProgressMessage;
protected VideoView mVideoView;
public final static String MSG_INIT = "com.keyes.video.msg.init";
protected String mMsgInit = "Initializing";
public final static String MSG_DETECT = "com.keyes.video.msg.detect";
protected String mMsgDetect = "Detecting Bandwidth";
public final static String MSG_PLAYLIST = "com.keyes.video.msg.playlist";
protected String mMsgPlaylist = "Determining Latest Video in YouTube Playlist";
public final static String MSG_TOKEN = "com.keyes.video.msg.token";
protected String mMsgToken = "Retrieving YouTube Video Token";
public final static String MSG_LO_BAND = "com.keyes.video.msg.loband";
protected String mMsgLowBand = "Buffering Low-bandwidth Video";
public final static String MSG_HI_BAND = "com.keyes.video.msg.hiband";
protected String mMsgHiBand = "Buffering High-bandwidth Video";
public final static String MSG_ERROR_TITLE = "com.keyes.video.msg.error.title";
protected String mMsgErrorTitle = "Communications Error";
public final static String MSG_ERROR_MSG = "com.keyes.video.msg.error.msg";
protected String mMsgError = "An error occurred during the retrieval of the video. This could be due to network issues or YouTube protocols. Please try again later.";
/** Background task on which all of the interaction with YouTube is done */
protected QueryYouTubeTask mQueryYouTubeTask;
protected String mVideoId = null;
#Override
protected void onCreate(Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// create the layout of the view
setupView();
// determine the messages to be displayed as the view loads the video
extractMessages();
// set the flag to keep the screen ON so that the video can play without the screen being turned off
getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mProgressBar.bringToFront();
mProgressBar.setVisibility(View.VISIBLE);
mProgressMessage.setText(mMsgInit);
// extract the playlist or video id from the intent that started this video
Uri lVideoIdUri = this.getIntent().getData();
if(lVideoIdUri == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
String lVideoSchemeStr = lVideoIdUri.getScheme();
String lVideoIdStr = lVideoIdUri.getEncodedSchemeSpecificPart();
if(lVideoIdStr == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
if(lVideoIdStr.startsWith("//")){
if(lVideoIdStr.length() > 2){
lVideoIdStr = lVideoIdStr.substring(2);
} else {
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
}
///////////////////
// extract either a video id or a playlist id, depending on the uri scheme
YouTubeId lYouTubeId = null;
if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_PLAYLIST)){
lYouTubeId = new PlaylistId(lVideoIdStr);
}
else if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_VIDEO)){
lYouTubeId = new VideoId(lVideoIdStr);
}
if(lYouTubeId == null){
Log.i(this.getClass().getSimpleName(), "Unable to extract video ID from the intent. Closing video activity.");
finish();
}
mQueryYouTubeTask = (QueryYouTubeTask) new QueryYouTubeTask().execute(lYouTubeId);
}
/**
* Determine the messages to display during video load and initialization.
*/
private void extractMessages() {
Intent lInvokingIntent = getIntent();
String lMsgInit = lInvokingIntent.getStringExtra(MSG_INIT);
if(lMsgInit != null){
mMsgInit = lMsgInit;
}
String lMsgDetect = lInvokingIntent.getStringExtra(MSG_DETECT);
if(lMsgDetect != null){
mMsgDetect = lMsgDetect;
}
String lMsgPlaylist = lInvokingIntent.getStringExtra(MSG_PLAYLIST);
if(lMsgPlaylist != null){
mMsgPlaylist = lMsgPlaylist;
}
String lMsgToken = lInvokingIntent.getStringExtra(MSG_TOKEN);
if(lMsgToken != null){
mMsgToken = lMsgToken;
}
String lMsgLoBand = lInvokingIntent.getStringExtra(MSG_LO_BAND);
if(lMsgLoBand != null){
mMsgLowBand = lMsgLoBand;
}
String lMsgHiBand = lInvokingIntent.getStringExtra(MSG_HI_BAND);
if(lMsgHiBand != null){
mMsgHiBand = lMsgHiBand;
}
String lMsgErrTitle = lInvokingIntent.getStringExtra(MSG_ERROR_TITLE);
if(lMsgErrTitle != null){
mMsgErrorTitle = lMsgErrTitle;
}
String lMsgErrMsg = lInvokingIntent.getStringExtra(MSG_ERROR_MSG);
if(lMsgErrMsg != null){
mMsgError = lMsgErrMsg;
}
}
/**
* Create the view in which the video will be rendered.
*/
private void setupView() {
LinearLayout lLinLayout = new LinearLayout(this);
lLinLayout.setId(1);
lLinLayout.setOrientation(LinearLayout.VERTICAL);
lLinLayout.setGravity(Gravity.CENTER);
lLinLayout.setBackgroundColor(Color.BLACK);
LayoutParams lLinLayoutParms = new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lLinLayout.setLayoutParams(lLinLayoutParms);
this.setContentView(lLinLayout);
RelativeLayout lRelLayout = new RelativeLayout(this);
lRelLayout.setId(2);
lRelLayout.setGravity(Gravity.CENTER);
lRelLayout.setBackgroundColor(Color.BLACK);
android.widget.RelativeLayout.LayoutParams lRelLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lRelLayout.setLayoutParams(lRelLayoutParms);
lLinLayout.addView(lRelLayout);
mVideoView = new VideoView(this);
mVideoView.setId(3);
android.widget.RelativeLayout.LayoutParams lVidViewLayoutParams = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lVidViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
mVideoView.setLayoutParams(lVidViewLayoutParams);
lRelLayout.addView(mVideoView);
mProgressBar = new ProgressBar(this);
mProgressBar.setIndeterminate(true);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setEnabled(true);
mProgressBar.setId(4);
android.widget.RelativeLayout.LayoutParams lProgressBarLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressBarLayoutParms.addRule(RelativeLayout.CENTER_IN_PARENT);
mProgressBar.setLayoutParams(lProgressBarLayoutParms);
lRelLayout.addView(mProgressBar);
mProgressMessage = new TextView(this);
mProgressMessage.setId(5);
android.widget.RelativeLayout.LayoutParams lProgressMsgLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressMsgLayoutParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
lProgressMsgLayoutParms.addRule(RelativeLayout.BELOW, 4);
mProgressMessage.setLayoutParams(lProgressMsgLayoutParms);
mProgressMessage.setTextColor(Color.LTGRAY);
mProgressMessage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
mProgressMessage.setText("...");
lRelLayout.addView(mProgressMessage);
}
#Override
protected void onDestroy() {
super.onDestroy();
YouTubeUtility.markVideoAsViewed(this, mVideoId);
if(mQueryYouTubeTask != null){
mQueryYouTubeTask.cancel(true);
}
if(mVideoView != null){
mVideoView.stopPlayback();
}
// clear the flag that keeps the screen ON
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.mQueryYouTubeTask = null;
this.mVideoView = null;
}
public void updateProgress(String pProgressMsg){
try {
mProgressMessage.setText(pProgressMsg);
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error updating video status!", e);
}
}
private class ProgressUpdateInfo {
public String mMsg;
public ProgressUpdateInfo(String pMsg){
mMsg = pMsg;
}
}
/**
* Task to figure out details by calling out to YouTube GData API. We only use public methods that
* don't require authentication.
*
*/
private class QueryYouTubeTask extends AsyncTask<YouTubeId, ProgressUpdateInfo, Uri> {
private boolean mShowedError = false;
#Override
protected Uri doInBackground(YouTubeId... pParams) {
String lUriStr = null;
String lYouTubeFmtQuality = "17"; // 3gpp medium quality, which should be fast enough to view over EDGE connection
String lYouTubeVideoId = null;
if(isCancelled())
return null;
try {
publishProgress(new ProgressUpdateInfo(mMsgDetect));
WifiManager lWifiManager = (WifiManager) Rads.this.getSystemService(Context.WIFI_SERVICE);
TelephonyManager lTelephonyManager = (TelephonyManager) Rads.this.getSystemService(Context.TELEPHONY_SERVICE);
////////////////////////////
// if we have a fast connection (wifi or 3g), then we'll get a high quality YouTube video
if( (lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0) ||
( (lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
/* icky... using literals to make backwards compatible with 1.5 and 1.6 */
lTelephonyManager.getNetworkType() == 9 /*HSUPA*/ ||
lTelephonyManager.getNetworkType() == 10 /*HSPA*/ ||
lTelephonyManager.getNetworkType() == 8 /*HSDPA*/ ||
lTelephonyManager.getNetworkType() == 5 /*EVDO_0*/ ||
lTelephonyManager.getNetworkType() == 6 /*EVDO A*/)
&& lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)
){
lYouTubeFmtQuality = "18";
}
///////////////////////////////////
// if the intent is to show a playlist, get the latest video id from the playlist, otherwise the video
// id was explicitly declared.
if(pParams[0] instanceof PlaylistId){
publishProgress(new ProgressUpdateInfo(mMsgPlaylist));
lYouTubeVideoId = YouTubeUtility.queryLatestPlaylistVideo((PlaylistId) pParams[0]);
}
else if(pParams[0] instanceof VideoId){
lYouTubeVideoId = pParams[0].getId();
}
mVideoId = lYouTubeVideoId;
publishProgress(new ProgressUpdateInfo(mMsgToken));
if(isCancelled())
return null;
////////////////////////////////////
// calculate the actual URL of the video, encoded with proper YouTube token
lUriStr = YouTubeUtility.calculateYouTubeUrl(lYouTubeFmtQuality, true, lYouTubeVideoId);
if(isCancelled())
return null;
if(lYouTubeFmtQuality.equals("17")){
publishProgress(new ProgressUpdateInfo(mMsgLowBand));
} else {
publishProgress(new ProgressUpdateInfo(mMsgHiBand));
}
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error occurred while retrieving information from YouTube.", e);
}
if(lUriStr != null){
return Uri.parse(lUriStr);
} else {
return null;
}
}
#Override
protected void onPostExecute(Uri pResult) {
super.onPostExecute(pResult);
try {
if(isCancelled())
return;
if(pResult == null){
throw new RuntimeException("Invalid NULL Url.");
}
mVideoView.setVideoURI(pResult);
if(isCancelled())
return;
// TODO: add listeners for finish of video
mVideoView.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.finish();
}
});
if(isCancelled())
return;
final MediaController lMediaController = new MediaController(Rads.this);
mVideoView.setMediaController(lMediaController);
lMediaController.show(0);
//mVideoView.setKeepScreenOn(true);
mVideoView.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.mProgressBar.setVisibility(View.GONE);
Rads.this.mProgressMessage.setVisibility(View.GONE);
}
});
if(isCancelled())
return;
mVideoView.requestFocus();
mVideoView.start();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Error playing video!", e);
if(!mShowedError){
showErrorAlert();
}
}
}
private void showErrorAlert() {
try {
Builder lBuilder = new AlertDialog.Builder(Rads.this);
lBuilder.setTitle(mMsgErrorTitle);
lBuilder.setCancelable(false);
lBuilder.setMessage(mMsgError);
lBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface pDialog, int pWhich) {
Rads.this.finish();
}
});
AlertDialog lDialog = lBuilder.create();
lDialog.show();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Problem showing error dialog.", e);
}
}
#Override
protected void onProgressUpdate(ProgressUpdateInfo... pValues) {
super.onProgressUpdate(pValues);
Rads.this.updateProgress(pValues[0].mMsg);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}

Categories

Resources