I'm trying to receive array in proximity alert. The only thing I could send is one Long. This is how I set proximity alert:
private void setProximityAlert(double lat, double lon, final long eventID, int requestCode)
{
float radius = 30f;
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent(PROXIMITY_INTENT_ACTION);
intent.putExtra(ProximityAlert.EVENT_ID_INTENT_EXTRA, eventID);
intent.putExtra("pole", mPositions);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
locManager.addProximityAlert(lat, lon, radius, -1, pendingIntent);
}
It doesn't crash when i comment "intent.putExtra("pole", mPositions);".
This is the array:
private ArrayList<LatLonPair> mPositions;
And this is receiver:
public class ProximityAlert extends BroadcastReceiver {
public static final String EVENT_ID_INTENT_EXTRA = "EventIDIntentExtraKey";
#Override
public void onReceive(Context context, Intent intent) {
long eventID = intent.getLongExtra(EVENT_ID_INTENT_EXTRA, -1);
ArrayList<LatLonPair> list = (ArrayList<LatLonPair>) intent.getSerializableExtra("list");
Toast.makeText(context, "Event: " + eventID, Toast.LENGTH_SHORT).show();
}
}
Without the one putExtra it's working, but i need that array. So this is not working for me:
Array List of objects via intent
LogCat error:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{co.uk.gauntface.android.proximityalerts/co.uk.gauntface.android.proximityalerts.ProximityDisplay}: java.lang.RuntimeException: Parcel: unable to marshal value co.uk.gauntface.android.proximityalerts.models.LatLonPair#44fb61f0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Parcel: unable to marshal value co.uk.gauntface.android.proximityalerts.models.LatLonPair#44fb61f0
at android.os.Parcel.writeValue(Parcel.java:1116)
at android.os.Parcel.writeList(Parcel.java:510)
at android.os.Parcel.writeValue(Parcel.java:1076)
at android.os.Parcel.writeMapInternal(Parcel.java:479)
at android.os.Bundle.writeToParcel(Bundle.java:1552)
at android.os.Parcel.writeBundle(Parcel.java:493)
at android.content.Intent.writeToParcel(Intent.java:5438)
at android.app.ActivityManagerProxy.getIntentSender(ActivityManagerNative.java:2206)
at android.app.PendingIntent.getBroadcast(PendingIntent.java:230)
at co.uk.gauntface.android.proximityalerts.ProximityDisplay.setProximityAlert(ProximityDisplay.java:91)
at co.uk.gauntface.android.proximityalerts.ProximityDisplay.registerIntents(ProximityDisplay.java:79)
at co.uk.gauntface.android.proximityalerts.ProximityDisplay.onCreate(ProximityDisplay.java:43)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
... 11 more
This is LatLonPair Class:
package co.uk.gauntface.android.proximityalerts.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.maps.GeoPoint;
public class LatLonPair implements Parcelable{
private double mLatitude;
private double mLongitude;
private String popis;
private String nadpis;
public LatLonPair() {
mLatitude = -2.60312596534349;
mLongitude = 51.4558140934651;
popis = "Nezadany popis";
nadpis = "Nezadany nadpis";
}
public LatLonPair(double latitude, double longitude, String popis, String nadpis) {
mLatitude = latitude;
mLongitude = longitude;
this.popis = popis;
this.nadpis = nadpis;
}
public static boolean isValid(double lat, double lon) {
if((lon >= -180 && lon <= 180) && (lat >= -90 && lat <= 90)) {
return true;
}
return false;
}
public String getPopis() {
return popis;
}
public String getNadpis() {
return nadpis;
}
public void setLatitude(double latitude) {
mLatitude = latitude;
}
public double getLatitude() {
return mLatitude;
}
public void setLongitude(double longitude) {
mLongitude = longitude;
}
public double getLongitude() {
return mLongitude;
}
public GeoPoint getGeoPoint() {
return new GeoPoint((int) (mLatitude * 1E6), (int) (mLongitude * 1E6));
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
Try calling super(dest,flags) in the overridden writeToParcel method in LatLonPair class
Problem was I didn't have implements Parceable and after that it didn't have CREATE. After that it wasn't crashing and the array lenght was OK, but items had default value. I guess problem was with bad implementation of saving variables in Parceable - it reseted itself. So I gave up and send to broadcastreceiver just few strings I needed there. Thank you all for help.
Related
I have tried to show a message By using the Toast function In different formats I have served many parameters Like : getBaseContext(), getContext(),.getApplication(),Context()
But in the end there are mistakes and he did not succeed in showing a message
//My logCat:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.login, PID: 9911
java.lang.NullPointerException at com.example.android.login.retrieveUserLogin$1.onResponse(retrieveUserLogin.java:76) at retrofit.ExecutorCallAdapterFactory$ExecutorCallback$1.run(ExecutorCallAdapterFactory.java:86 at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
My class:
public class retrieveUserLogin {
public Activity activity;
private ProgressDialog progressDialog;
private HttpApi api;
public int value_array;
private List<Users> user;
private String UserAccount_;
private Call<HttpApi.HttpBinResponse> call;
private Call<List<Users>> getUsersCall;
private List<Integer>collection;
// private Context context;
Context mContext;
public retrieveUserLogin(final String t1 ,final String t2){
// context = context;
api = HttpApi.getInstance();
api.addHeader("Authorization","MyT23");
getUsersCall = api.getService().getAllChatRooms();
getUsersCall.enqueue(new retrofit.Callback<List<Users>>(){
String UserAccuent;
#Override
public void onResponse(retrofit.Response<List<Users>>response, Retrofit retrofit){
collection = new ArrayList<>();
user = response.body();
String [] arrayString = new String[user.size()];
String [] arrayString2 = new String[user.size()];
int[] arrayInt = new int[user.size()];
for(int i=0; i<response.body().size(); i++){
arrayString[i] = user.get(i).user_name;
arrayString2[i] = user.get(i).email;
arrayInt[i] = user.get(i).password;
if(Arrays.asList(arrayString2).contains(t1)){
UserAccuent = arrayString[i];
break;
}
}
boolean Check = Arrays.asList(arrayString2).contains(t1);
boolean Check2 = contains(arrayInt , Integer.parseInt(t2));
if(Check == true && Check2 == true){
Toast.makeText(activity.getApplication(),"تم تسجيل الدخول يا......" +UserAccuent.toString() ,Toast.LENGTH_LONG).show();
// Toast.makeText(getContext(), "sdfasd"+5, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(activity.getBaseContext(),"خطأ فى اسم البريد او كلمة السر" ,Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Throwable t){
progressDialog.dismiss();
// Toast.makeText(getContext(),"XXX" ,Toast.LENGTH_LONG).show();
}});
}
public static boolean contains(int[] arr,int item) {
for (int n : arr){
if (item == n){
return true;
}
}
return false;
}
// End ;
}
//Call from Activity
retrieveUserLogin("username","userpassword",Activity.this)
//Change in Constructor
public retrieveUserLogin(final String t1 ,final String t2, final Context context){
mContext = context;
Toast.makeText(mContext ,"خطأ فى اسم البريد او كلمة السر" ,Toast.LENGTH_LONG).show();}
Try this
In your non-activity class
public class NonActivity {
public void showToast(Context context, String message){
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
change your constractor from public retrieveUserLogin(final String t1 ,final String t2){ to public retrieveUserLogin(Context context, final String t1 ,final String t2){
and assign mContext=context, then pass your activity instance to it.
DO NOT store activities and contexts in fields. Instead pass them as parameters to the method.
public void retrieveUserLogin(
final Context context,
final String t1 ,final String t2) {
// ...
// then change your toasts to
Toast.makeText(context, "...", Toast.LENGTH_LONG).show();
}
The problem was probably that you did not assign a value to activity, but passing context as a parameter solves that issue. That way, you can only call the method if you have a context to give it.
Toast does not show any message because the activity is null:
Toast.makeText(activity.getApplication(),"تم تسجيل الدخول يا......" +UserAccuent.toString() ,Toast.LENGTH_LONG).show();
That is also why you are seeing a NullPointerException in LogCat.
You need to initialize the activity of retrieveUserLogin class:
public Activity activity;
inside the class constructor, and probably you will need to change your constructor a bit by adding one more parameter:
public retrieveUserLogin(Activity activity, final String t1 ,final String t2){
// init activity here
this.activity = activity;
// your code
}
Program runs until it tries to access the SharedPreferences in my updateUserSettings() method. I have spent the last 2 hours searching the internet with no explanations. Please help!
I have the line that messes everything up Commented at the bottom of my onCreate();
Here is FuelEconomyCalculatorActivity.java
package com.example.fuelcalculator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class FuelEconomyCalculatorActivity extends ActionBarActivity implements
OnClickListener {
private EditText fuelEditText;
private EditText distanceEditText;
private TextView mpgTextView;
private TextView litresTextView;
private Button calculateButton;
private Button clearButton;
private RadioButton gallonsRadio;
private RadioButton litresRadio;
private RadioButton milesRadio;
private RadioButton kmRadio;
private String mpg = " ";
private String kp100 = " ";
private boolean metricChecked;
private boolean imperialChecked;
private boolean usGallonChecked;
private boolean ukGallonChecked;
private static final int RESULT_SETTINGS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fuel_economy_calculator);
fuelEditText = (EditText) findViewById(R.id.fuelEditText);
distanceEditText = (EditText) findViewById(R.id.distanceEditText);
mpgTextView = (TextView) findViewById(R.id.mpgTextView);
litresTextView = (TextView) findViewById(R.id.litresTextView);
calculateButton = (Button) findViewById(R.id.calculateButton);
clearButton = (Button) findViewById(R.id.clearButton);
gallonsRadio = (RadioButton) findViewById(R.id.gallonsRadio);
litresRadio = (RadioButton) findViewById(R.id.litresRadio);
milesRadio = (RadioButton) findViewById(R.id.milesRadio);
kmRadio = (RadioButton) findViewById(R.id.kmRadio);
calculateButton.setOnClickListener(this);
clearButton.setOnClickListener(this);
if (savedInstanceState != null) {
mpg = savedInstanceState.getString("mpg");
kp100 = savedInstanceState.getString("kp100");
initializeViews();
}
// updateUserSettings();
}
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("mpg", (String) mpgTextView.getText());
savedInstanceState.putString("kp100", (String) litresTextView.getText());
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
private void initializeViews() {
mpgTextView.setText(mpg);
litresTextView.setText(kp100);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fuel_economy_calculator, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings: {
Intent intent = new Intent(FuelEconomyCalculatorActivity.this,
FuelEconomySettingsActivity.class);
startActivityForResult(intent, RESULT_SETTINGS);
return true;
}
case R.id.action_about: {
Intent intent = new Intent(getApplicationContext(), FuelEconomyAboutPageActivity.class);
startActivity(intent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
updateUserSettings();
break;
}
}
private void updateUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
{
metricChecked = true;
imperialChecked = false;
}
else if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("imperial"))
{
imperialChecked = true;
metricChecked = false;
}
if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("uk"))
{
ukGallonChecked = true;
usGallonChecked = false;
}
else if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("us"))
{
usGallonChecked = true;
ukGallonChecked = false;
}
if(metricChecked)
{
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
else if(imperialChecked)
{
milesRadio.setChecked(true);
gallonsRadio.setChecked(true);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.calculateButton) {
float mpg = 0;
float kmLitres = 0;
// it doesn't matter which you use here, as long
// as you use a fuel and a distance method
if (ukGallonChecked && !usGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallons();
kmLitres = getLitres() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
} else if (usGallonChecked && !ukGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallonsUS();
kmLitres = getLitresUS() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
}
} else if (v.getId() == R.id.clearButton) {
resetValues();
}
}
public float CheckValues(EditText input) {
float value = 0;
try {
value = Float.parseFloat(input.getText().toString());
if (value < 1) {
Toast toast = Toast.makeText(this,
"Please enter a number that is larger than 0",
Toast.LENGTH_SHORT);
toast.show();
}
} catch (Exception ex) {
Toast toast = Toast.makeText(this, "Please enter a number",
Toast.LENGTH_SHORT);
toast.show();
}
return value;
}
public void resetValues() {
mpg = " ";
kp100 = " ";
fuelEditText.setText("");
distanceEditText.setText("");
mpgTextView.setText("");
litresTextView.setText("");
}
public float getKM() {
float distance = CheckValues(distanceEditText);
if (milesRadio.isChecked()) {
distance = (float) (distance * 1.60934);
}
return distance;
}
public float getMiles() {
float distance = CheckValues(distanceEditText);
if (kmRadio.isChecked()) {
distance = (float) (distance * 0.62137);
}
return distance;
}
public float getLitres() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 4.54609);
}
return fuel;
}
public float getLitresUS() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 3.785411784);
}
return fuel;
}
public float getGallons() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.219969);
}
return fuel;
}
public float getGallonsUS() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.264172);
}
return fuel;
}
}
And here is my FuelEconomySettingsActivity.java
package com.example.fuelcalculator;
import android.app.Activity;
import android.os.Bundle;
public class FuelEconomySettingsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new FuelEconomySettingsFragment()).commit();
}
}
Here is my LogCat
07-18 14:35:37.014: E/AndroidRuntime(3084): FATAL EXCEPTION: main
07-18 14:35:37.014: E/AndroidRuntime(3084): Process: com.example.fuelcalculator, PID: 3084
07-18 14:35:37.014: E/AndroidRuntime(3084): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fuelcalculator/com.example.fuelcalculator.FuelEconomyCalculatorActivity}: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.access$900(ActivityThread.java:161)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Handler.dispatchMessage(Handler.java:102)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Looper.loop(Looper.java:157)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.main(ActivityThread.java:5356)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invoke(Method.java:515)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-18 14:35:37.014: E/AndroidRuntime(3084): at dalvik.system.NativeStart.main(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): Caused by: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.updateUserSettings(FuelEconomyCalculatorActivity.java:128)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.onCreate(FuelEconomyCalculatorActivity.java:63)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Activity.performCreate(Activity.java:5426)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
07-18 14:35:37.014: E/AndroidRuntime(3084): ... 11 more
I am new to Android so I am not very good at debugging so could someone please assist me with my predicament?
The activity is already included in my Manifest so I know that is not the issue.
Any help is much obliged.
You are getting a NullPointerException because you are getting null as the default value for SharedPreference.getString()
Since it is getString() get an empty string as the default value...
So try this..
if(sharedPrefs.getString("measuringUnits", "").equalsIgnoreCase("metric"))
instead of
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
I try to get current location and user activity, following the guide from
http://j.mp/io13-location the "checkpoint_final"
but i got those error when i run the program.
my logCat:
02-21 18:12:38.439: E/AndroidRuntime(3798): FATAL EXCEPTION: main
02-21 18:12:38.439: E/AndroidRuntime(3798): Process: com.android.google.codelab.location, PID: 3798
02-21 18:12:38.439: E/AndroidRuntime(3798): java.lang.RuntimeException: Unable to resume activity {com.android.google.codelab.location/com.android.google.codelab.location.LocationActivity}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Handler.dispatchMessage(Handler.java:102)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Looper.loop(Looper.java:136)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invoke(Method.java:515)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-21 18:12:38.439: E/AndroidRuntime(3798): at dalvik.system.NativeStart.main(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.dk.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.a(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm$c.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fl.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.location.LocationClient.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.restartLocationClient(LocationActivity.java:248)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.onResume(LocationActivity.java:197)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Activity.performResume(Activity.java:5310)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
02-21 18:12:38.439: E/AndroidRuntime(3798): ... 12 more
my Code
public class LocationActivity extends FragmentActivity {
public static String TAG = "LocationActivity";
public static boolean isAppForeground = false;
private static final int ERROR_DIALOG_ON_CREATE_REQUEST_CODE = 4055;
private static final int ERROR_DIALOG_ON_RESUME_REQUEST_CODE = 4056;
// Shared variables
private GoogleMap mMap;
private Dialog errorDialog;
// Location Request variables
private LocationClient mLocationClient;
private TextView mLocationStatus;
private LocationCallback mLocationCallback = new LocationCallback();
private Location mLastLocation;
private static final int LOCATION_UPDATES_INTERVAL = 10000; // Setting 10 sec interval for location updates
// Activity Recognition variables
private ActivityRecognitionClient mActivityRecognitionClient;
private ActivityRecognitionCallback mActivityRecognitionCallback = new ActivityRecognitionCallback();
public static final String ACTION_ACTIVITY_RECOGNITION =
"com.android.google.codelab.location.LocationActivity.ACTIVITY_RECOGNITION";
private static final int ACTIVITY_UPDATES_INTERVAL = 4000;
private PendingIntent mActivityRecognitionPendingIntent;
private Switch mSwitch;
private ActivityRecognitionIntentReceiver mActivityRecognitionIntentReceiver;
// Geo Fencing variables
private GeoFenceCallback mGeoFenceCallback = new GeoFenceCallback();
private int id = 0;
private static final float GEOFENCE_RADIUS = 100;
private HashMap<String, Circle> mGeoFences;
private HashMap<String, Circle> mTriggeringFences;
public static final String ACTION_GEOFENCE =
"com.android.google.codelab.location.LocationActivity.GEOFENCE";
private TextView mGeoFenceStatus;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_CREATE_REQUEST_CODE);
}
private void init() {
// Initialize map
if (mMap == null) {
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment =
(SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
mMap = myMapFragment.getMap();
}
// Initialize Location Client
mLocationStatus = (TextView) findViewById(R.id.location_status);
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect();
}
}
// Initialize Action Recognition
if (mActivityRecognitionClient == null) {
mActivityRecognitionClient =
new ActivityRecognitionClient(this,
mActivityRecognitionCallback, mActivityRecognitionCallback);
}
mSwitch = (Switch) findViewById(R.id.swtich);
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startActivityDetection(buttonView);
} else {
stopActivityDetection(buttonView);
}
}
});
if (mActivityRecognitionIntentReceiver == null) {
mActivityRecognitionIntentReceiver = new ActivityRecognitionIntentReceiver();
registerReceiver(mActivityRecognitionIntentReceiver,
new IntentFilter(LocationActivity.ACTION_ACTIVITY_RECOGNITION));
}
// Initialize Geo Fencing
mGeoFenceStatus = (TextView) findViewById(R.id.geo_fence_status);
if (mGeoFences == null) {
mGeoFences = new HashMap<String, Circle>();
}
if (mTriggeringFences == null) {
mTriggeringFences = new HashMap<String, Circle>();
}
// Setup map to allow adding Geo Fences
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.setOnMapLongClickListener(mGeoFenceCallback);
}
#Override
public void onPause() {
super.onPause();
// Indicate the application is in background
isAppForeground = false;
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(mLocationCallback);
mLocationClient.disconnect();
}
}
#Override
public void onResume() {
super.onResume();
// Indicate the application is in foreground
isAppForeground = true;
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_RESUME_REQUEST_CODE);
restartLocationClient();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mActivityRecognitionIntentReceiver);
mActivityRecognitionIntentReceiver = null;
}
private void checkGooglePlayServiceAvailability(int requestCode) {
// Query for the status of Google Play services on the device
int statusCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (statusCode == ConnectionResult.SUCCESS) {
init();
} else {
if (GooglePlayServicesUtil.isUserRecoverableError(statusCode)) {
errorDialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
this, requestCode);
errorDialog.show();
} else {
// Handle unrecoverable error
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ERROR_DIALOG_ON_CREATE_REQUEST_CODE:
init();
break;
case ERROR_DIALOG_ON_RESUME_REQUEST_CODE:
restartLocationClient();
break;
}
}
}
private void restartLocationClient() {
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem menuItem = menu.add(R.string.clear_map);
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
clearMap();
return true;
}
});
return true;
}
public void clearMap() {
mMap.clear();
mLastLocation = null;
mGeoFenceCallback.removeGeoFences();
}
private class LocationCallback implements ConnectionCallbacks, OnConnectionFailedListener,
LocationListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Location Client connected");
// Display last location
Location location = mLocationClient.getLastLocation();
if (location != null) {
handleLocation(location);
}
// Request for location updates
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Location Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG, "Location Client connection failed");
}
#Override
public void onLocationChanged(Location location) {
if (location == null) {
Log.v(LocationActivity.TAG, "onLocationChanged: location == null");
return;
}
// Add a marker iff location has changed.
if (mLastLocation != null &&
mLastLocation.getLatitude() == location.getLatitude() &&
mLastLocation.getLongitude() == location.getLongitude()) {
return;
}
handleLocation(location);
}
private void handleLocation(Location location) {
// Update the mLocationStatus with the lat/lng of the location
Log.v(LocationActivity.TAG, "LocationChanged == #" +
location.getLatitude() + "," + location.getLongitude());
mLocationStatus.setText("Location changed #" + location.getLatitude() + "," +
location.getLongitude());
// Add a marker of that location to the map
LatLng latlongzoom = new LatLng(location.getLatitude(),
location.getLongitude());
String snippet = location.getLatitude() + "," + location.getLongitude();
Marker marker = mMap.addMarker(
new MarkerOptions().position(latlongzoom));
marker.setSnippet(snippet);
marker.setTitle(snippet);
// Center the map to the first marker
if (mLastLocation == null) {
mMap.moveCamera(CameraUpdateFactory.
newCameraPosition(CameraPosition.fromLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()),
(float) 16.0)));
}
mLastLocation = location;
}
};
public void startActivityDetection(View v) {
if (!mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.connect();
}
}
public void stopActivityDetection(View v) {
if (mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.removeActivityUpdates(mActivityRecognitionPendingIntent);
mActivityRecognitionClient.disconnect();
}
}
private class ActivityRecognitionCallback implements ConnectionCallbacks, OnConnectionFailedListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Activity Recognition Client connected");
// Request activity updates
Intent intent = new Intent(LocationActivity.this,
ActivityRecognitionIntentService.class);
intent.setAction(LocationActivity.ACTION_ACTIVITY_RECOGNITION);
mActivityRecognitionPendingIntent = PendingIntent.getService(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mActivityRecognitionClient.requestActivityUpdates(ACTIVITY_UPDATES_INTERVAL,
mActivityRecognitionPendingIntent);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Activity Recognition Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG,
"Activity Recognition Client connection failed " + result.getErrorCode());
}
};
private class GeoFenceCallback implements OnMapLongClickListener,
OnAddGeofencesResultListener, OnRemoveGeofencesResultListener {
#Override
public void onMapLongClick(LatLng point) {
Log.v(LocationActivity.TAG,
"onMapLongClick == " + point.latitude + "," + point.longitude);
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(point).radius(GEOFENCE_RADIUS).strokeColor(
android.graphics.Color.BLUE).strokeWidth(2);
Circle circle = mMap.addCircle(circleOptions);
String key = Integer.toString(id);
id++;
mGeoFences.put(key, circle);
addGeoFences();
}
// Creates Geofence objects from all circles on the map and calls addGeofences API.
private void addGeoFences() {
List<Geofence> list = new ArrayList<Geofence>();
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
Circle circle = entry.getValue();
Log.v(LocationActivity.TAG, "points == " +
circle.getCenter().latitude + "," +
circle.getCenter().longitude);
Geofence geofence = new Geofence.Builder()
.setRequestId(entry.getKey())
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(circle.getCenter().latitude,
circle.getCenter().longitude,
(float) circle.getRadius())
.setExpirationDuration(Geofence.NEVER_EXPIRE).build();
list.add(geofence);
}
if (list.isEmpty()) {
return;
}
// Clear off all the currently triggering geo_fences before new fences
// are added.
for (Circle triggeringGeoFence : mTriggeringFences.values()) {
triggeringGeoFence.remove();
}
mTriggeringFences.clear();
Log.v(LocationActivity.TAG, "addingGeoFences size = " + list.size());
mLocationClient.addGeofences(list, getPendingIntent(), this);
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(ACTION_GEOFENCE);
intent.setComponent(new ComponentName(LocationActivity.this,
GeoFenceIntentReceiver.class));
return PendingIntent.getBroadcast(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
private void removeGeoFences() {
List<String> requestIdsForRemoval = new ArrayList<String>();
if (mGeoFences.isEmpty()) return;
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
String requestId = entry.getKey();
Circle circle = entry.getValue();
if (circle != null) {
circle.remove();
id --;
Log.v(LocationActivity.TAG, "RemoveGeoFence requestId == " + requestId);
Circle triggeringCircle = mTriggeringFences.get(requestId);
if (triggeringCircle != null) {
triggeringCircle.remove();
}
requestIdsForRemoval.add(requestId);
}
}
mGeoFences.clear();
mTriggeringFences.clear();
mLocationClient.removeGeofences(requestIdsForRemoval, this);
}
#Override
public void onAddGeofencesResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Added Geofences == "
+ statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Added Geofences "
+ statusCodeToString(statusCode) + " " + builder.toString());
}
private String statusCodeToString(int statusCode) {
switch(statusCode) {
case LocationStatusCodes.SUCCESS :
return "SUCCESS";
case LocationStatusCodes.GEOFENCE_NOT_AVAILABLE :
return "GEOFENCE_NOT_AVAILABLE";
case LocationStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES :
return "GEOFENCE_TOO_MANY_GEOFENCES";
case LocationStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS :
return "GEOFENCE_TOO_MANY_PENDING_INTENTS";
case LocationStatusCodes.ERROR :
return "ERROR";
}
return "UNKNOWN";
}
#Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode, PendingIntent pendingIntent) {
// Do nothing
}
#Override
public void onRemoveGeofencesByRequestIdsResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Removed Geofence " +
statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Removed Geofences request_ids = " +
builder.toString() + " " + statusCodeToString(statusCode));
}
};
// Triggered when startAcitivity method is called in GeoFenceIntentReceiver.
// Updates UI as geofences are entered/exited.
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
boolean receiverStarted =
intent.getBooleanExtra("RECEIVER_STARTED", false);
if (!receiverStarted) {
return;
}
Bundle bundle = intent.getParcelableExtra("geo_fences");
ArrayList<String> requestIds =
bundle.getStringArrayList("request_ids");
if (requestIds == null) {
Log.v(LocationActivity.TAG, "request_ids == null");
return;
}
int transition = intent.getIntExtra("transition", -2);
for (String requestId : requestIds) {
Log.v(LocationActivity.TAG, "Triggering Geo Fence requestId "
+ requestId);
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER) {
Circle circle = mGeoFences.get(requestId);
if (circle == null) {
continue;
}
Log.v(LocationActivity.TAG, "triggering_geo_fences enter == "
+ requestId);
// Add a superimposed red circle when a geofence is entered and
// put the corresponding object in triggering_fences.
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(circle.getCenter())
.radius(circle.getRadius())
.fillColor(Color.argb(100,100, 0, 0));
Circle newCircle = mMap.addCircle(circleOptions);
mTriggeringFences.put(requestId, newCircle);
} else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Log.v(LocationActivity.TAG, "triggering_geo_fences exit == "
+ requestId);
Circle circle = mTriggeringFences.get(requestId);
if (circle == null) {
continue;
}
// Remove the superimposed red circle from the map and the
// corresponding Circle object from triggering_fences hash_map.
circle.remove();
mTriggeringFences.remove(requestId);
}
}
return;
}
}
2nd class
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
public ActivityRecognitionIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction() != LocationActivity.ACTION_ACTIVITY_RECOGNITION) {
return;
}
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult
.extractResult(intent);
DetectedActivity detectedActivity = result
.getMostProbableActivity();
int activityType = detectedActivity.getType();
Log.v(LocationActivity.TAG, "activity_type == " + activityType);
// Put the activity_type as an intent extra and send a broadcast.
Intent send_intent = new Intent(
LocationActivity.ACTION_ACTIVITY_RECOGNITION);
send_intent.putExtra("activity_type", activityType);
sendBroadcast(send_intent);
}
}
}
edited add the main part of the code
Please Modify your restartLocationClient() Method like this:
private void restartLocationClient() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting()))
{
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
It seems that your mLocationClient is null in this Method.
I hope this helps.
I know it's pretty late for this answer.
But for future reference, I'll post it anyways.
Basically, we have to understand the onConnect() method better. I find the explanation in this thread to be useful.
From there the workaround for this issue is pretty much straightforward.
Solution: restartLocationClient() is only called when mLocationClient.isConnected() returns true.
So, in your onResume method should look like the following:
if (mLocationClient.isConnected()) {
restartLocationClient();
}
Now it will work.
I have used the OrientationEventListener which I have coupled with a Handler to update a TextView when the screen rotates:
MainHandler handler;
TextView tv;
MyOrientationEventListener listener;
class MainHandler extends Handler
{
#Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case MSG_ORIENTATION:
if(tv!=null)
tv.setText(msg.arg1);
break;
default:
if(tv!=null)
tv.setText("Nothing to see here");
}
}
}
This is my OrientationEventListener here:
class MyOrientationEventListener extends OrientationEventListener
{
public MyOrientationEventListener(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyOrientationEventListener(Context context,int attrs)
{
super(context,attrs);
}
#Override
public void onOrientationChanged(int orientation) {
// TODO Auto-generated method stub
Log.d("MainActivity", "Orientation before rounding: "+orientation);
orientation=roundRotation(orientation,0);
Log.d("MainActivity", "Orientation after rounding: "+orientation);
Message msg=handler.obtainMessage(MSG_ORIENTATION);
msg.arg1=orientation;
handler.sendMessage(msg);
}
public int getDisplayOrientation()
{
int rotation=getWindowManager().getDefaultDisplay().getRotation();
switch(rotation)
{
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 90;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return 270;
}
return 0;
}
public int roundRotation(int orientation,int orientationHistory)
{
final int ORIENTATION_HYSTERESIS=5;
boolean changeOrientation=false;
if(orientationHistory==ORIENTATION_UNKNOWN)
changeOrientation=true;
else
{
int dist=Math.abs(orientation-orientationHistory);
dist=Math.min(dist, 360-dist);
changeOrientation=(dist>=45+ORIENTATION_HYSTERESIS);
}
if(changeOrientation)
{
int nOrientation=((orientation+45)/90*90)%360;
Log.d("OrientationEventHandler", "New orientation: "+nOrientation);
return nOrientation;
}
return orientationHistory;
}
}
I am using the Handler in onCreate to register my Handler to the UI thread,thus it can be used to update the Views on screen.However,this code does not seem to work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.tv);
handler=new MainHandler();
listener=new MyOrientationEventListener(this);
}
I am using listener.enable() in onResume and listener.disable() in onPause methods after invoking their respective superclass methods.When I try to rotate the screen and the rounding occurs:
MainActivity(9724): Orientation before rounding: 55
OrientationEventHandler(9724): New orientation: 90
MainActivity(9724): Orientation after rounding: 90
ResourceType(9724): No package identifier when getting value for resource number 0x0000005a
dalvikvm(9724): threadid=1: thread exiting with uncaught exception (group=0x41fdf700)
AndroidRuntime(9724): FATAL EXCEPTION: main
AndroidRuntime(9724): android.content.res.Resources$NotFoundException: String resource ID #0x5a
AndroidRuntime(9724): at android.content.res.Resources.getText(Resources.java:239)
AndroidRuntime(9724): at android.widget.TextView.setText(TextView.java:3837)
AndroidRuntime(9724): at com.example.calllogproject.MainActivity$MainHandler.handleMessage(MainActivity.java:30)
AndroidRuntime(9724): at android.os.Handler.dispatchMessage(Handler.java:99)
AndroidRuntime(9724): at android.os.Looper.loop(Looper.java:137)
AndroidRuntime(9724): at android.app.ActivityThread.main(ActivityThread.java:5103)
AndroidRuntime(9724): at java.lang.reflect.Method.invokeNative(Native Method)
AndroidRuntime(9724): at java.lang.reflect.Method.invoke(Method.java:525)
AndroidRuntime(9724): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
AndroidRuntime(9724): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
AndroidRuntime(9724): at dalvik.system.NativeStart.main(Native Method)
Try this class:
class MainHandler extends Handler
{
#Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case MSG_ORIENTATION:
if(tv!=null)
tv.setText(String.valueOf(msg.arg1));
break;
default:
if(tv!=null)
tv.setText("Nothing to see here");
}
}
}
I've changed
tv.setText(msg.arg1);
into
tv.setText(String.valueOf(msg.arg1));
Ill first start this off saying i have seen all the other posts that deal with this and have tried all of them.
Im trying to do the same thing asked in the other posts, which is to pass the values of a ArrayList from one activity to another using Intent.
I feel I have implemented my class(es) correctly. The main class (Route_Class) i am using is below.
```
public class Route_Class implements Parcelable {
private double latitude = 0;
private double longitude = 0;
private double startingLat = 0;
private double startingLong = 0;
private String name = null;
private String routeName = null;
private String GeoPoints = null;
private String layout_width= null;
private String layout_height = null;
private String orientation = null;
private String xmlns = null;
private String id = null;
private boolean clickable = false;
private boolean enabled = false;
private String layout_width2 = null;
private String layout_height2 = null;
private String apiKey = null;
private ArrayList<GeoPoints_Class> geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
public Route_Class() {
System.out.println("crash 110");
}
public Route_Class(String name, double latitude, double longitude, double startingLat, double startingLong, String routeName, String GeoPoints, String layout_width, String layout_height, String orientation, String xmlns, String id, boolean clickable, boolean enabled, String layout_width2, String layout_height2, String apiKey, ArrayList<GeoPoints_Class> geoPoints_arraylist) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.layout_width2 = layout_width2;
this.latitude = latitude;
this.longitude = longitude;
this.startingLat = startingLat;
this.startingLong = startingLong;
this.routeName = routeName;
this.GeoPoints = GeoPoints;
this.layout_width = layout_width;
this.layout_height = layout_height;
this.orientation = orientation;
this.xmlns = xmlns;
this.id = id;
this.clickable = clickable;
this.enabled = enabled;
this.layout_height2 = layout_height2;
this.apiKey = apiKey;
this.geoPoints_arraylist = geoPoints_arraylist;
System.out.println("crash 16");
}
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
System.out.println("crash 17");
return this.hashCode();
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel dest, int flags) {
System.out.println("crash 18");
dest.writeDouble(latitude);
dest.writeDouble(longitude);
dest.writeDouble(startingLat);
dest.writeDouble(startingLong);
dest.writeString(name);
dest.writeString(routeName);
dest.writeString(GeoPoints);
dest.writeString(layout_width);
dest.writeString(layout_height);
dest.writeString(orientation);
dest.writeString(xmlns);
dest.writeString(id);
dest.writeInt(clickable ? 0 : 1 );
dest.writeInt(enabled ? 0 : 1 );
dest.writeString(layout_width2);
dest.writeString(layout_height2);
dest.writeString(apiKey);
dest.writeTypedList(geoPoints_arraylist);
// dest.writeList((List<GeoPoints_Class>)geoPoints_arraylist);
// dest.writeParcelable((Parcelable) geoPoints_arraylist, 0);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Route_Class> CREATOR = new Parcelable.Creator<Route_Class>() {
public Route_Class createFromParcel(Parcel in) {
System.out.println("crash 20");
return new Route_Class(in);
}
public Route_Class[] newArray(int size) {
System.out.println("crash 21");
return new Route_Class[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Route_Class(Parcel in) {
layout_width2 = in.readString();
latitude = in.readDouble();
longitude = in.readDouble();
startingLat = in.readDouble();
startingLong = in.readDouble();
name = in.readString();
routeName = in.readString();
GeoPoints = in.readString();
layout_width = in.readString();
layout_height = in.readString();
orientation = in.readString();
xmlns = in.readString();
id = in.readString();
clickable = in.readInt() == 0;
enabled = in.readInt() == 0;
layout_height2 = in.readString();
apiKey = in.readString();
System.out.println("crash 5");
//geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
if (geoPoints_arraylist == null) {
geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
}
try {
in.readTypedList(geoPoints_arraylist, GeoPoints_Class.CREATOR);
} catch (Exception e) {
System.out.println("Error " + e);
}
// in.readList(geoPoints_arraylist, com.breckbus.app.GeoPoints_Class.class.getClassLoader());
System.out.println("crash 6");
// geoPoints_arraylist = (ArrayList<GeoPoints_Class>)in.readParcelable(com.breckbus.app.Route_Class.GeoPoints_Class. class.getClassLoader());
}
public double getlatitude() {
return latitude;
}
public void setlatitude(double latitude) {
this.latitude = latitude;
}
public double getlongitude() {
return longitude;
}
public void setlongitude(double longitude) {
this.longitude = longitude;
}
public double getstartingLat() {
return startingLat;
}
public void setstartingLat(double startingLat) {
this.startingLat = startingLat;
}
public double getstartingLong() {
return startingLong;
}
public void setstartingLong(double startingLong) {
this.startingLong = startingLong;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getrouteName() {
return routeName;
}
public void setrouteName(String routeName) {
this.routeName = routeName;
}
public String getGeoPoints() {
return GeoPoints;
}
public void setGeoPoints(String GeoPoints) {
this.GeoPoints = GeoPoints;
}
public String getLayout_width() {
return layout_width;
}
public void setLayout_width(String layout_width) {
this.layout_width = layout_width;
}
public String getLayout_height() {
return layout_height;
}
public void setLayout_height(String layout_height) {
this.layout_height = layout_height;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getOrientation() {
return orientation;
}
public void setOrientation(String orientation) {
this.orientation = orientation;
}
public String getXmlns() {
return xmlns;
}
public void setXmlns(String xmlns) {
this.xmlns = xmlns;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isClickable() {
return clickable;
}
public void setClickable(boolean clickable) {
this.clickable = clickable;
}
public String getLayout_width2() {
return layout_width2;
}
public void setLayout_width2(String layout_width2) {
this.layout_width2 = layout_width2;
}
public String getLayout_height2() {
return layout_height2;
}
public void setLayout_height2(String layout_height2) {
this.layout_height2 = layout_height2;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Route Class Details:").append("\n\n");
sb.append("latitude: ").append(getlatitude());
sb.append("\n");
sb.append("longitude: ").append(getlongitude());
sb.append("\n");
sb.append("startingLat: ").append(getstartingLat());
sb.append("\n");
sb.append("startingLong: ").append(getstartingLong());
sb.append("\n");
sb.append("name: ").append(getname());
sb.append("\n");
sb.append("routeName: ").append(getrouteName());
sb.append("\n");
sb.append("GeoPoints: ").append(getGeoPoints());
sb.append("\n");
sb.append("layout_width: ").append(getLayout_width());
sb.append("\n");
sb.append("layout_height: ").append(getLayout_height());
sb.append("\n");
sb.append("orientation: ").append(getOrientation());
sb.append("\n");
sb.append("xmlns: ").append(getXmlns());
sb.append("\n");
sb.append("id: ").append(getId());
sb.append("\n");
sb.append("clickable: ").append(isClickable());
sb.append("\n");
sb.append("enabled: ").append(isEnabled());
sb.append("\n");
sb.append("layout_width2: ").append(layout_width2);
sb.append("\n");
sb.append("layout_height2: ").append(getLayout_height2());
sb.append("\n");
sb.append("apiKey: ").append(getApiKey());
return sb.toString();
}
// public ArrayList<GeoPoints_Class> getGeoPoints_arraylist() {
// return geoPoints_arraylist;
// }
public ArrayList<GeoPoints_Class> getGeoPoints_arraylist() {
return geoPoints_arraylist;
}
public void setGeoPoints_arraylist(ArrayList<GeoPoints_Class> geoPoints_arraylist) {
this.geoPoints_arraylist = geoPoints_arraylist;
}
public GeoPoints_Class getGeoPoints(int i) {
return geoPoints_arraylist.get(i);
}
public void addGeoPoint(double lat, double lon, String location) {
this.geoPoints_arraylist.add(new GeoPoints_Class(lat, lon, location));
}
}
```
Here is my second class (GeoPoints_Class) that is used in Route_Class.
```
package com.breckbus.app;
import android.os.Parcel;
import android.os.Parcelable;
class GeoPoints_Class implements Parcelable {
private double lat;
private double lon;
private String location;
public GeoPoints_Class(){
System.out.println("crash 99");
}
public GeoPoints_Class(double lat, double lon, String location){
System.out.println("crash 7");
this.lat = lat;
this.lon = lon;
this.location = location;
}
public int describeContents() {
return this.hashCode();
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel dest, int flags) {
System.out.println("crash 11");
dest.writeDouble(lat);
dest.writeDouble(lon);
dest.writeString(location);
System.out.println("crash 12");
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<GeoPoints_Class> CREATOR = new Parcelable.Creator<GeoPoints_Class>() {
public GeoPoints_Class createFromParcel(Parcel in) {
System.out.println("crash 28");
return new GeoPoints_Class(in);
}
public GeoPoints_Class[] newArray(int size) {
System.out.println("crash 29");
return new GeoPoints_Class[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private GeoPoints_Class(Parcel in) {
System.out.println("crash 13");
lat = in.readDouble();
lon = in.readDouble();
location = in.readString();
System.out.println("crash 14");
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("GeoPoint Class Details:").append("\n\n");
sb.append("latitude: ").append(getLat());
sb.append("\n");
sb.append("longitude: ").append(getLon());
sb.append("\n");
sb.append("location: ").append(getLocation());
sb.append("\n");
return sb.toString();
}
}
```
Next is where I put the objects using putExtra.
```
Intent i = new Intent("com.breckbus.app.ROUTE");
// i.putParcelableArrayListExtra("route_Classes_temp", route_Classes);
i.putExtra("route_Classes_temp",route_Classes);
System.out.println("crash 1");
```
Then where i get the objects.
```
Bundle extras = getIntent().getExtras();
Intent d = getIntent();
System.out.println("crash 25");
route_Classes = d.getParcelableArrayListExtra("route_Classes_temp");
System.out.println("crash 2");
// route_Classes = getIntent().getParcelableArrayListExtra("route_Classes_temp");
```
You will notice all of my manual debug statements since Eclipse doesnt work with android applications in debug mode (breakpoints and stuff). (Which if you know the solution to that, it would greatly help).
Next is the only error i get and where the manual debug statements i entered in the code stop. I dont know where it is crashing anymore.
Here is the first couple errors:
```
10-26 00:03:50.165: I/System.out(323): crash 13
10-26 00:03:50.165: I/System.out(323): crash 14
10-26 00:03:50.165: I/System.out(323): crash 28
10-26 00:03:50.165: I/System.out(323): crash 13
10-26 00:03:50.165: I/System.out(323): crash 14
10-26 00:03:50.185: I/System.out(323): crash 6
10-26 00:03:50.195: D/AndroidRuntime(323): Shutting down VM
10-26 00:03:50.195: W/dalvikvm(323): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
10-26 00:03:50.225: E/AndroidRuntime(323): FATAL EXCEPTION: main
10-26 00:03:50.225: E/AndroidRuntime(323): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.breckbus.app/com.breckbus.app.route}: java.lang.RuntimeException: Parcel android.os.Parcel#44edd958: Unmarshalling unknown type code 6553714 at offset 968
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.os.Handler.dispatchMessage(Handler.java:99)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.os.Looper.loop(Looper.java:123)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 00:03:50.225: E/AndroidRuntime(323): at java.lang.reflect.Method.invokeNative(Native Method)
10-26 00:03:50.225: E/AndroidRuntime(323): at java.lang.reflect.Method.invoke(Method.java:521)
```
I hope i provided enough information. Please tell me what i am doing wrong when trying to pass the route_class ArrayList of Object type Route_Class from one activity to another using Intent. These two lines:
i.putExtra("route_Classes_temp",route_Classes);
route_Classes = d.getParcelableArrayListExtra("route_Classes_temp");
Thank you for your help, it is much appreciated.
It is true that you have provided too much information.
However, is this on the same process (i.e. your own app only?) If yes, then avoid doing that entirely. It will be too slow to parcel/unparcel these objects.
Use a singleton where you store your data and just access the singleton from each activity.