Passing ArrayList Object between activities using parcelable - java

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.

Related

How to stop exception from searching Unavailable/no cities?

I have a Weather app that searches for any city typed on the EditText and it works very well.
But the problem is that the app crashes and reports "(my app) has stopped" on my phone whenever I search for an unavailable city or I leave the EditText empty and click the search button(this only happens when I search an unavailable city/no city is searched), It can search any valid city correctly.
Here's what my Logcat displays(only when an unavailable city is searched):
java.lang.NullPointerException: Attempt to invoke virtual method 'com.viz.lightweatherforecast.Retrofit.Example$Main com.viz.lightweatherforecast.Retrofit.Example.getMain()' on a null object reference
at com.viz.lightweatherforecast.FirstFragment$1.onResponse(FirstFragment.java:104)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
and
java.lang.NullPointerException: Attempt to invoke virtual method 'com.viz.lightweatherforecast.first.PrettyTime com.viz.lightweatherforecast.Retrofit.Example.getDt()' on a null object reference
at com.viz.lightweatherforecast.Activity.HomeActivity$1$2.onResponse(HomeActivity.java:100)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
when no city is searched(EditText is empty).
So I'm trying to stop the exception responsible for that and as well write a toast/message to tell the user "no city found" when an unavailable/no city is searched.
Please how do I do that? So far, I've tried adding:
Log.d(TAG, "No City found");
on my
#Override
public void onFailure(#NotNull Call<Example> call, #NotNull Throwable t) {
t.printStackTrace();
}
the method in HomeActivity, but it still crashes.
Here's my specific code:
HomeActivity.java:
public class HomeActivity extends AppCompatActivity {
// User current time
TextView time_field;
ImageView Search;
EditText textfield;
ConstraintLayout constraintLayout;
// For scheduling background image change
public static int count=0;
int[] drawable =new int[]{R.drawable.dubai,R.drawable.central_bank_of_nigeria,R.drawable.eiffel_tower,R.drawable.hong_kong,R.drawable.statue_of_liberty};
Timer _t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
time_field = findViewById(R.id.textView9);
Search = findViewById(R.id.imageView4);
textfield = findViewById(R.id.textfield);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
assert navHostFragment != null;
final NavController navController = navHostFragment.getNavController();
NavigationUI.setupWithNavController(bottomNavigationView, navController);
Search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherData(textfield.getText().toString().trim());
FirstFragment firstFragment = (FirstFragment) navHostFragment.getChildFragmentManager().getFragments().get(0);
firstFragment.getWeatherData(textfield.getText().toString().trim());
constraintLayout = findViewById(R.id.layout);
constraintLayout.setBackgroundResource(R.drawable.dubai);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// run on ui thread
runOnUiThread(() -> {
if (count < drawable.length) {
constraintLayout.setBackgroundResource(drawable[count]);
count = (count + 1) % drawable.length;
}
});
}
}, 5000, 5000);
}
private void getWeatherData(String name) {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<Example> call = apiInterface.getWeatherData(name);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(#NotNull Call<Example> call, #NotNull Response<Example> response) {
assert response.body() != null;
time_field.setText("Last Updated:" + " " + response.body().getDt());
}
#Override
public void onFailure(#NotNull Call<Example> call, #NotNull Throwable t) {
t.printStackTrace();
}
});
}
});
}
}
FirstFragment.java:
public class FirstFragment extends Fragment {
// User current time, current temperature, current condition, sunrise, sunset, temperature, pressure, humidity, wind_speed, visibility, clouds
TextView current_temp, current_output, rise_time, set_time, temp_out, Press_out, Humid_out, Ws_out, Visi_out, Cloud_out;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FirstFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment SecondFragment.
*/
// TODO: Rename and change types and number of parameters
public static FirstFragment newInstance(String param1, String param2) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
// For displaying weather data
current_temp = rootView.findViewById(R.id.textView10);
current_output = rootView.findViewById(R.id.textView11);
rise_time = rootView.findViewById(R.id.textView25);
set_time = rootView.findViewById(R.id.textView26);
temp_out = rootView.findViewById(R.id.textView28);
Press_out = rootView.findViewById(R.id.textView29);
Humid_out = rootView.findViewById(R.id.textView30);
Ws_out = rootView.findViewById(R.id.textView33);
Visi_out = rootView.findViewById(R.id.textView34);
Cloud_out = rootView.findViewById(R.id.textView35);
return rootView;
}
public void getWeatherData(String name) {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<Example> call = apiInterface.getWeatherData(name);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(#NotNull Call<Example> call, #NotNull Response<Example> response) {
assert response.body() !=null;
current_temp.setText(response.body().getMain().getTemp() + " ℃");
current_output.setText(response.body().getWeather().get(0).getDescription());
rise_time.setText(response.body().getSys().getSunrise() + " ");
set_time.setText(response.body().getSys().getSunset() + " ");
temp_out.setText(response.body().getMain().getTemp() + " ℃");
Press_out.setText(response.body().getMain().getPressure() + " hpa");
Humid_out.setText(response.body().getMain().getHumidity() + " %");
Ws_out.setText(response.body().getWind().getSpeed() + " Km/h");
Visi_out.setText(response.body().getVisibility() + " m");
Cloud_out.setText(response.body().getClouds().getAll()+ " %");
}
#Override
public void onFailure(#NotNull Call<Example> call, #NotNull Throwable t) {
t.printStackTrace();
}
});
}
}
EDIT
Example.java:
public class Example {
#SerializedName("coord")
private Coord coord;
#SerializedName("weather")
private List<Weather> weather = null;
#SerializedName("base")
private String base;
#SerializedName("main")
private Main main;
#SerializedName("visibility")
private Integer visibility;
#SerializedName("wind")
private Wind wind;
#SerializedName("clouds")
private Clouds clouds;
#SerializedName("dt")
#Expose
private PrettyTime dt;
#SerializedName("sys")
private Sys sys;
#SerializedName("timezone")
private Integer timezone;
#SerializedName("id")
private Integer id;
#SerializedName("name")
private String name;
#SerializedName("cod")
private Integer cod;
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public PrettyTime getDt() {
return dt;
}
public void setDt(PrettyTime dt) {
this.dt = dt;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public Integer getTimezone() {
return timezone;
}
public void setTimezone(Integer timezone) {
this.timezone = timezone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
public class Clouds {
#SerializedName("all")
private Integer all;
public Integer getAll() {
return all;
}
public void setAll(Integer all) {
this.all = all;
}
}
public class Coord {
#SerializedName("lon")
private Double lon;
#SerializedName("lat")
private Double lat;
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
}
public class Main {
#SerializedName("temp")
private Double temp;
#SerializedName("feels_like")
private Double feelsLike;
#SerializedName("temp_min")
private Double tempMin;
#SerializedName("temp_max")
private Double tempMax;
#SerializedName("pressure")
private Integer pressure;
#SerializedName("humidity")
private Integer humidity;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getFeelsLike() {
return feelsLike;
}
public void setFeelsLike(Double feelsLike) {
this.feelsLike = feelsLike;
}
public Double getTempMin() {
return tempMin;
}
public void setTempMin(Double tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
public Integer getPressure() {
return pressure;
}
public void setPressure(Integer pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
}
public class Sys {
#SerializedName("type")
private Integer type;
#SerializedName("id")
private Integer id;
#SerializedName("country")
private String country;
#SerializedName("sunrise")
#Expose
private PrettyTime sunrise;
#SerializedName("sunset")
#Expose
private PrettyTime sunset;
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public PrettyTime getSunrise() {
return sunrise;
}
public void setSunrise(PrettyTime sunrise) {
this.sunrise = sunrise;
}
public PrettyTime getSunset() {
return sunset;
}
public void setSunset(PrettyTime sunset) {
this.sunset = sunset;
}
}
public class Weather {
#SerializedName("id")
private Integer id;
#SerializedName("main")
private String main;
#SerializedName("description")
private String description;
#SerializedName("icon")
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
public class Wind {
#SerializedName("speed")
private Double speed;
#SerializedName("deg")
private Integer deg;
#SerializedName("gust")
private Double gust;
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public Integer getDeg() {
return deg;
}
public void setDeg(Integer deg) {
this.deg = deg;
}
public Double getGust() {
return gust;
}
public void setGust(Double gust) {
this.gust = gust;
}
}
}
As OP said I just need the best method to handle the exceptions
Let me give two examples for your case to avoid the crash and show toast for both Activity and Fragment.
try/catch
Update your Activity onResponse like below.
public void onResponse(Call<Example> call, Response<Example> response) {
try {
time_field.setText("Last Updated:" + " " + response.body().getDt());
} catch (Exception e) {
time_field.setText("Last Updated: Unknown");
Log.e("TAG", "No City found");
Toast.makeText(HomeActivity.this, "No City found", Toast.LENGTH_SHORT).show();
}
}
Update your Fragment `onResponse like below
public void onResponse(Call<Example> call, Response<Example> response) {
try {
current_temp.setText(response.body().getMain().getTemp() + " ℃");
current_output.setText(response.body().getWeather().get(0).getDescription());
rise_time.setText(response.body().getSys().getSunrise() + " ");
set_time.setText(response.body().getSys().getSunset() + " ");
temp_out.setText(response.body().getMain().getTemp() + " ℃");
Press_out.setText(response.body().getMain().getPressure() + " hpa");
Humid_out.setText(response.body().getMain().getHumidity() + " %");
Ws_out.setText(response.body().getWind().getSpeed() + " Km/h");
Visi_out.setText(response.body().getVisibility() + " m");
Cloud_out.setText(response.body().getClouds().getAll() + " %");
} catch (Exception e) {
Log.e("TAG", "No City found");
Toast.makeText(getActivity(), "No City found", Toast.LENGTH_SHORT).show();
}
}
null check
Update your Activity onResponse like below.
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.isSuccessful() && response.body() != null) {
time_field.setText("Last Updated:" + " " + response.body().getDt());
} else {
time_field.setText("Last Updated: Unknown");
Log.e("TAG", "No City found");
Toast.makeText(HomeActivity.this, "No City found", Toast.LENGTH_SHORT).show();
}
}
Update your Fragment onResponse like below
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.isSuccessful() && response.body() != null) {
current_temp.setText(response.body().getMain().getTemp() + " ℃");
current_output.setText(response.body().getWeather().get(0).getDescription());
rise_time.setText(response.body().getSys().getSunrise() + " ");
set_time.setText(response.body().getSys().getSunset() + " ");
temp_out.setText(response.body().getMain().getTemp() + " ℃");
Press_out.setText(response.body().getMain().getPressure() + " hpa");
Humid_out.setText(response.body().getMain().getHumidity() + " %");
Ws_out.setText(response.body().getWind().getSpeed() + " Km/h");
Visi_out.setText(response.body().getVisibility() + " m");
Cloud_out.setText(response.body().getClouds().getAll() + " %");
} else {
Log.e("TAG", "No City found");
Toast.makeText(getActivity(), "No City found", Toast.LENGTH_SHORT).show();
}
}
Note: There is a bit of scope to improve your code and design a better, like to avoid an extra call to API on search click, one from Activity and another in the fragment. But all those suggestion will be out of the scope of this question, So I will stick to OP request which is I just need the best method to handle the exceptions.
public void onResponse(#NotNull Call<Example> call, #NotNull Response<Example> response) {
assert response.body() !=null;
if(response.body().getMain()==null && response.body().getWeather()!=null && all other field!=null){
yourErrorTextview.setText("No City found");
allOtherField.setText();
}
else if(response.body().getMain()!=null && response.body().getWeather()!=null && all other field!=null){
current_temp.setText(response.body().getMain().getTemp() + " ℃");
allOtherField.setText();
}}
According to the log you get a success response with a body but getMain returns null.
You can prevent this by adding some null checks around getMain. Make sure to check the possibility of null in the api documentation.
You can use try catch block in catch you are getting exception you can toast message city not found so your app will not crash.

Parcelable of Custom Classes

I am currently trying to pass an ArrayList of the class event into another activity as follows.events is an ArrayList of the Event class.
Intent i = new Intent(ViewEvents.this, UserFeed.class);
i.putParcelableArrayListExtra("events",events);
startActivity(i);
I am then retrieving the data as follows:
Intent i = getIntent();
ArrayList<Event> events = i.getParcelableArrayListExtra("events");
My Issue is that I get an Umarshing unknown type code 32 at offset 5788. I am not too sure how to fix this or why this is occurring. I have posted all the code for all three classes down below.Any help would be appreciated to solve this issue.
public class Event implements Parcelable {
public String tvEventName;
public String tvEventInfo;
public String tvDescription;
public String ivEventImage;
public String organizerName;
public String eventId;
public String veneuId;
public String organizerId;
public Venue venue;
public Organizer organizer;
public Event(String tvEventName, String tvEventInfo, String tvDescription, String ivEventImage, String eventId, String veneuId,Venue venue,Organizer organizer) {
this.tvEventName = tvEventName;
this.tvEventInfo = tvEventInfo;
this.tvDescription = tvDescription;
this.ivEventImage = ivEventImage;
this.eventId = eventId;
this.veneuId = veneuId;
}
public Event() {
}
protected Event(Parcel in) {
tvEventName = in.readString();
tvEventInfo = in.readString();
tvDescription = in.readString();
ivEventImage = in.readString();
organizerName = in.readString();
eventId = in.readString();
veneuId = in.readString();
organizerId = in.readString();
}
public static final Creator<Event> CREATOR = new Creator<Event>() {
#Override
public Event createFromParcel(Parcel in) {
return new Event(in);
}
#Override
public Event[] newArray(int size) {
return new Event[size];
}
};
public static Event fromJSON(JSONObject jsonObject)throws JSONException {
Event event = new Event();
//Getting the name of the event
JSONObject nameEvent = jsonObject.getJSONObject("name");
event.tvEventName = nameEvent.getString("text");
//Getting the description for the event Time and location only
JSONObject eventInfo = jsonObject.getJSONObject("start");
event.tvEventInfo = eventInfo.getString("utc");
SimpleDateFormat existingUTCFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat requiredFormat = new SimpleDateFormat("MM-dd hh:mm a");
event.eventId = jsonObject.getString("id");
try{
Date getDate = existingUTCFormat.parse(event.tvEventInfo);
String mydate = requiredFormat.format(getDate);
event.tvEventInfo = mydate;
}
catch(ParseException e){
e.printStackTrace();
}
//Getting the description of the event
JSONObject eventDescription = jsonObject.getJSONObject("description");
event.tvDescription = eventDescription.getString("text");
//Getting a thumbnail of the image for futer use.
try{
jsonObject.getJSONObject("logo");
JSONObject logo = jsonObject.getJSONObject("logo");
JSONObject original= logo.getJSONObject("original");
event.ivEventImage = original.getString("url");
Log.i("Ingo",event.ivEventImage);
}
catch (Exception exception){
event.ivEventImage ="#drawable/tree";
}
event.veneuId = jsonObject.getString("venue_id");
event.organizerId = jsonObject.getString("organizer_id");
return event;
}
public Organizer getOrganizer() {
return organizer;
}
public void setOrganizer(Organizer organizer) {
this.organizer = organizer;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getTvEventName() {
return tvEventName;
}
public void setTvEventName(String tvEventName) {
this.tvEventName = tvEventName;
}
public String getTvEventInfo() {
return tvEventInfo;
}
public void setTvEventInfo(String tvEventInfo) {
this.tvEventInfo = tvEventInfo;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public String getTvDescription() {
return tvDescription;
}
public void setTvDescription(String tvDescription) {
this.tvDescription = tvDescription;
}
public String getIvEventImage() {
return ivEventImage;
}
public void setIvEventImage(String ivEventImage) {
this.ivEventImage = ivEventImage;
}
public String getVeneuId() {
return veneuId;
}
public void setVeneuId(String veneuId) {
this.veneuId = veneuId;
}
public String getOrganizerName() {
return organizerName;
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public void setOrganizerName(String organizerName) {
this.organizerName = organizerName;
}
#Override
public int describeContents() {
return 0;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(tvEventName);
dest.writeString(tvEventInfo);
dest.writeString(tvDescription);
dest.writeString(ivEventImage);
dest.writeString(organizerName);
dest.writeString(eventId);
dest.writeString(veneuId);
dest.writeString(organizerId);
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
}
}
CLASS 2
public class Venue implements Parcelable {
public String address;
public String city;
public String region;
public String postalCode;
public String country;
public String latitude;
public String longitude;
public String simpleAddress;
public Venue() {
}
public Venue(String address, String city, String region, String postalCode, String country, String latitude, String longitude, String simpleAddress) {
this.address = address;
this.city = city;
this.region = region;
this.postalCode = postalCode;
this.country = country;
this.latitude = latitude;
this.longitude = longitude;
this.simpleAddress = simpleAddress;
}
protected Venue(Parcel in) {
address = in.readString();
city = in.readString();
region = in.readString();
postalCode = in.readString();
country = in.readString();
latitude = in.readString();
longitude = in.readString();
simpleAddress = in.readString();
}
public static final Creator<Venue> CREATOR = new Creator<Venue>() {
#Override
public Venue createFromParcel(Parcel in) {
return new Venue(in);
}
#Override
public Venue[] newArray(int size) {
return new Venue[size];
}
};
public static Venue fromJSON(JSONObject jsonObject)throws JSONException {
Venue venue = new Venue();
if(jsonObject.getString("address_1") == null){
if(jsonObject.getString("address_2") == null)
venue.address = "No Location Available";
else
venue.address = jsonObject.getString("address_2");
}
else
venue.address = jsonObject.getString("address_1");
venue.city = jsonObject.getString("city");
venue.region = jsonObject.getString("region");
venue.postalCode = jsonObject.getString("postal_code");
venue.country = jsonObject.getString("country");
venue.latitude = jsonObject.getString("latitude");
venue.longitude = jsonObject.getString("longitude");
venue.simpleAddress =venue.address +","+ venue.city +","+ venue.country;
Log.i("SIMPLE", venue.simpleAddress);
return venue;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getSimpleAddress() {
return simpleAddress;
}
public void setSimpleAddress(String simpleAddress) {
this.simpleAddress = simpleAddress;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(address);
dest.writeString(city);
dest.writeString(region);
dest.writeString(postalCode);
dest.writeString(country);
dest.writeString(latitude);
dest.writeString(longitude);
dest.writeString(simpleAddress);
}
}
CLASS 3
public class Organizer implements Parcelable{
public String description;
public String organizerId;
public String numePastEvents;
public String numFutureEvents;
public String website;
public String facebookUsername;
public String twitter;
public String name;
public Organizer() {
}
protected Organizer(Parcel in) {
description = in.readString();
organizerId = in.readString();
numePastEvents = in.readString();
numFutureEvents = in.readString();
website = in.readString();
facebookUsername = in.readString();
twitter = in.readString();
name = in.readString();
}
public static final Creator<Organizer> CREATOR = new Creator<Organizer>() {
#Override
public Organizer createFromParcel(Parcel in) {
return new Organizer(in);
}
#Override
public Organizer[] newArray(int size) {
return new Organizer[size];
}
};
public static Organizer fromJson(JSONObject jsonObject){
Organizer organizer = new Organizer();
try {
organizer.description = jsonObject.getJSONObject("description").getString("text");
} catch (JSONException e) {
organizer.description ="NA";
e.printStackTrace();
}
try {
organizer.organizerId = jsonObject.getString("id");
} catch (JSONException e) {
organizer.organizerId = "NA";
e.printStackTrace();
}
try {
organizer.numePastEvents = jsonObject.getString("num_past_events");
} catch (JSONException e) {
organizer.numePastEvents = "Na";
e.printStackTrace();
}
try {
organizer.numFutureEvents = jsonObject.getString("num_future_events");
} catch (JSONException e) {
organizer.numFutureEvents = "NA";
e.printStackTrace();
}
try {
organizer.website = jsonObject.getString("website");
} catch (JSONException e) {
Log.i("Error",e.getMessage());
organizer.website = "NA";
e.printStackTrace();
}
try {
organizer.facebookUsername = jsonObject.getString("facebook");
} catch (JSONException e) {
organizer.facebookUsername = "NA";
e.printStackTrace();
}
try {
organizer.name = jsonObject.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
organizer.twitter = jsonObject.getString("twitter");
} catch (JSONException e) {
e.printStackTrace();
}
return organizer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getNumePastEvents() {
return numePastEvents;
}
public void setNumePastEvents(String numePastEvents) {
this.numePastEvents = numePastEvents;
}
public String getNumFutureEvents() {
return numFutureEvents;
}
public void setNumFutureEvents(String numFutureEvents) {
this.numFutureEvents = numFutureEvents;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getFacebookUsername() {
return facebookUsername;
}
public void setFacebookUsername(String facebookUsername) {
this.facebookUsername = facebookUsername;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(description);
dest.writeString(organizerId);
dest.writeString(numePastEvents);
dest.writeString(numFutureEvents);
dest.writeString(website);
dest.writeString(facebookUsername);
dest.writeString(twitter);
dest.writeString(name);
}
When implementing the Parcelable interface, it is an absolute requirement that your reads and writes exactly match each other. In your case, this is your Event(Parcel) constructor and void writeToParcel().
However, your writeToParcel() implementation includes two writes that your constructor does not read.
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
You have to either remove these or add matching reads to your constructor.
venue = in.readParcelable(Venue.class.getClassLoader());
organizer = in.readParcelable(Organizer.class.getClassLoader());

Pass List<> to a Fragment

I'm creating an Android map app by getting venue from Foursquare and using Google Map.
I have set my MainActivity to get the venue results, a MapFragmentClass and a VenueModel.
I keep all the JSON result from Foursquare into a List venueModelList in the MainActivity.
What I want to do is to add markers in the MapFragmentClass based on the coordinates received from Foursquare.
However, I am stuck trying to pass the venueModelList to the MapFragmentClass.
Any help is appreciated. Thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity implements LocationListener{
private final String VENUE_URL = "https://api.foursquare.com/v2/venues/search?ll=";
private final int LIMIT = 40;
private final double RADIUS = 50000;
private String MOSQUE_URL;
private String RES_URL;
public static final String CLIENT_ID = "";
public static final String CLIENT_SECRET = "";
private static final long MIN_TIME_BW_UPDATES = 20000;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private LocationManager locationManager;
private Location lastLocation;
private Location location;
private boolean receivedLocation = false;
private double lt;
private double lg;
private boolean canGetLocation;
private boolean isGPSEnabled;
private boolean isNetworkEnabled;
private boolean updateSettings = false;
private String TAG = "TAG";
private ListView lvVenues;
private Bundle bundle;
private ArrayList<VenueModel> venueModelList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvVenues = (ListView) findViewById(R.id.lvVenues);
String t = timeMilisToString(System.currentTimeMillis());
Bundle extras = getIntent().getExtras();
if (extras != null)
{
lt = extras.getDouble("LATITUDE");
lg = extras.getDouble("LONGITUDE");
receivedLocation = true;
}
else
{
receivedLocation = false;
}
location = getLocation();
if (location != null)
{
if(receivedLocation)
{
location.setLatitude(lt);
location.setLongitude(lg);
}
else
{
lt = location.getLatitude();
lg = location.getLongitude();
Log.d("LAT", "Latitude: " + lt);
Log.d("LONG", "Longitude: " + lg);
}
}
double lt = 3.142182;
double lg = 101.710602;
MOSQUE_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=4bf58dd8d48988d138941735"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
RES_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=52e81612bcbc57f1066b79ff"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
}
public class JSONTask extends AsyncTask<String, String, List<VenueModel>>
{
#Override
public List<VenueModel> doInBackground(String... params)
{
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondObject = parentObject.getJSONObject("response");
JSONArray parentArray = secondObject.getJSONArray("venues");
venueModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++)
{
JSONObject finalObject = parentArray.getJSONObject(i);
JSONObject thirdObject = finalObject.getJSONObject("location");
try {
VenueModel venueModel = new VenueModel();
venueModel.setId(finalObject.getString("id"));
venueModel.setName(finalObject.getString("name"));
venueModel.setAddress(thirdObject.optString("address"));
venueModel.setPostalCode(thirdObject.optString("postalCode"));
venueModel.setCity(thirdObject.optString("city"));
venueModel.setState(thirdObject.optString("state"));
venueModel.setDistance(thirdObject.getInt("distance"));
venueModel.setLat(thirdObject.getDouble("lat"));
venueModel.setLng(thirdObject.getDouble("lng"));
LatLng coordinate = new LatLng(thirdObject.getDouble("lat"), thirdObject.getDouble("lng"));
venueModel.setCoordinate(coordinate);
venueModelList.add(venueModel);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Collections.sort(venueModelList);
return venueModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<VenueModel> result)
{
super.onPostExecute(result);
VenueAdapter adapter = new VenueAdapter(getApplicationContext(), R.layout.row, result);
lvVenues.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_mosque)
{
new JSONTask().execute(MOSQUE_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
if (id == R.id.action_restaurant)
{
new JSONTask().execute(RES_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
private String timeMilisToString(long milis)
{
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public Location getLocation()
{
try
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
Log.v(TAG, "No network provider enabled");
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "Network Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "GPS Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider)
{
Log.v(TAG, "onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider)
{
Log.v(TAG, "onProviderDisabled");
}
public LatLng setCoordinate()
{
LatLng coordinate = new LatLng(getLocation().getLatitude(), getLocation().getLongitude());
LatLng coordinate = new LatLng(lt, lg);
return coordinate;
}
}
VenueModel.java
public class VenueModel implements Comparable<VenueModel>, Parcelable
{
private String id;
private String name;
private String address;
private String postalCode;
private String city;
private String state;
private Integer distance;
private double lat;
private double lng;
private LatLng coordinate;
private List<VenueModel> venueModelList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public void setVenueModelList(List<VenueModel> venueModelList)
{
this.venueModelList = venueModelList;
}
public List<VenueModel> getVenueModelList()
{
return venueModelList;
}
public LatLng getCoordinate() {
return coordinate;
}
public void setCoordinate(LatLng coordinate)
{
this.coordinate = coordinate;
}
#Override
public int compareTo(VenueModel venueModel) {
return this.distance.compareTo(venueModel.distance);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeString(this.address);
dest.writeString(this.postalCode);
dest.writeString(this.city);
dest.writeString(this.state);
dest.writeValue(this.distance);
dest.writeDouble(this.lat);
dest.writeDouble(this.lng);
dest.writeParcelable(this.coordinate, flags);
dest.writeList(this.venueModelList);
}
public VenueModel() {
}
protected VenueModel(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.address = in.readString();
this.postalCode = in.readString();
this.city = in.readString();
this.state = in.readString();
this.distance = (Integer) in.readValue(Integer.class.getClassLoader());
this.lat = in.readDouble();
this.lng = in.readDouble();
this.coordinate = in.readParcelable(LatLng.class.getClassLoader());
this.venueModelList = new ArrayList<VenueModel>();
in.readList(this.venueModelList, VenueModel.class.getClassLoader());
}
public static final Parcelable.Creator<VenueModel> CREATOR = new Parcelable.Creator<VenueModel>() {
#Override
public VenueModel createFromParcel(Parcel source) {
return new VenueModel(source);
}
#Override
public VenueModel[] newArray(int size) {
return new VenueModel[size];
}
};
}
MapFragmentClass.java
public class MapFragmentClass extends Fragment implements OnMapReadyCallback
{
private MainActivity mA;
private GoogleMap gmap;
private static final LatLng coordinate = new LatLng(3.152182, 101.710602);
private LatLng coordinate2;
private ArrayList<VenueModel> venueModelList;
#Override
public void onAttach(Context context)
{
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
gmap = googleMap;
gmap.addMarker(new MarkerOptions().position(coordinate).title("Your location").draggable(true));
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 14));
}
}
Convert that Object to JSON string using GSON and then reconvert that string again to Object of list again.
MapFragment.getInstance(new Gson().toJson(venuList));
public static final getInstance(String venusStringListObj) {}
Bundle argument = new Bundle();
argument.putString("VENUES", venusStringListObj);
MapFragment fragment = new MapFragment();
fragment.setArgument(argument);
return fragment;
}
onCreate(...) {
private List<VenueModel> venueList;
Type listType = new TypeToken<ArrayList<VenueModel>>() {}.getType();
String venueStringRecvFromFragArg = getArguments().getString("VENUES");
venueList = new Gson().fromJson(venueStringRecvFromFragArg, listType);
}
MapFragmentClass mfc = new MapFragmentClass();
Bundle b = new Bundle();
b.putParcelableArrayList("Parcel", list);
mfc.setArguments(b);
FT.add(R.id.mapLayout, mfc);
FT.commit();
To access arrayList in MapFragment use this
ArrayList<VenueModel> myList = getArguments().getParcelableArrayList("Parcel");

Getting java.lang.NullPointerException while ArrayList from Sqlite [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm getting error below while on button click
java.lang.NullPointerException
at com.gor.hocam.MainActivity.getListitem(MainActivity.java:329)
at com.gor.hocam.MainActivity$2.onClick(MainActivity.java:222)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
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:5139)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)
My Button that i clicked is (MainActivity.java:222 is the first line below);
getListitem();
System.out.println(dersadilist.size());
String[] arrRecords = dersadilist.toArray(new String[dersadilist.size()]);
int arr[] = new int[derskodulist.size()];
for (int i = 0; i < derskodulist.size(); i++) {
arr[i] = Integer.parseInt(derskodulist.get(i));
}
new MaterialDialog.Builder(MainActivity.this)
.title("Son Çözdüğünüz Dersler:")
.items(arrRecords)
.itemsIds(arr)
.itemsCallback(new MaterialDialog.ListCallback() {
#Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
Toast.makeText(MainActivity.this, which + ": " + text + ", ID = " + view.getId(), Toast.LENGTH_SHORT).show();
}
}).show();
Here my getListitem ( which is = (MainActivity.java:329);
public void getListitem() {
List<Scoredata> score = db.getAllContacts();
for (Scoredata sc : score) {
dersidler = String.valueOf(sc.getId());
dersadlari = sc.getName();
topscore = sc.getScore();
derskodlari = sc.getKodu();
//sc.getScore();
dersidlist.add(dersidler);
dersadilist.add(dersadlari);
scorelist.add(topscore);
derskodulist.add(dersadlari);
}
}
Thats my Scoredata;
public class Scoredata {
int id;
String name, kodu, score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKodu() {
return kodu;
}
public void setKodu(String kodu) {
this.kodu = kodu;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public Scoredata(String name, String kodu, String score) {
super();
this.name = name;
this.kodu = kodu;
this.score = score;
}
public Scoredata() {
super();
// TODO Auto-generated constructor stub
}
}
And getAllContacts on my DbHighestScore;
public List<Scoredata> getAllContacts() {
List<Scoredata> scoreList = new ArrayList<Scoredata>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Scoredata score = new Scoredata();
score.setId(Integer.valueOf(cursor.getString(0)));
score.setName(cursor.getString(1));
score.setKodu(cursor.getString(2));
score.setScore(cursor.getString(3));
scoreList.add(score);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return scoreList;
}
Check if the db object is not null and the collection object score is not null before parsing through it
public void getListitem() {
if(db != null){
List<Scoredata> score = db.getAllContacts();
if(score!= null){
for (Scoredata sc : score) {
dersidler = String.valueOf(sc.getId());
dersadlari = sc.getName();
topscore = sc.getScore();
derskodlari = sc.getKodu();
//sc.getScore();
dersidlist.add(dersidler);
dersadilist.add(dersadlari);
scorelist.add(topscore);
derskodulist.add(dersadlari);
}
}
}
}

Android Bitmap parcel Unmarshalling error while broadcast it

I have a Parcelable Contact Objects. I need to place them in ArrayList and broadcast it to the Activity. Getting error while reading the ArrayList in broadcast listener. I tried alot to resolve this issue. But could not find any solution to fix it.
Error:
java.lang.RuntimeException: Error receiving broadcast Intent { act=ip. flg=0x10 (has extras) } in io.HomeActivity$1#20d66f72
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:876)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.RuntimeException: Parcel android.os.Parcel#13cda10b: Unmarshalling unknown type code 7274601 at offset 352
at android.os.Parcel.readValue(Parcel.java:2228)
at android.os.Parcel.readListInternal(Parcel.java:2526)
at android.os.Parcel.readArrayList(Parcel.java:1842)
at android.os.Parcel.readValue(Parcel.java:2173)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getParcelableArrayList(Bundle.java:799)
at android.content.Intent.getParcelableArrayListExtra(Intent.java:5126)
at io.HomeActivity$1.onReceive(HomeActivity.java:149)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5343)
            at java.lang.reflect.Method.invoke(Native Method)
Contact
public class Contact implements Parcelable{
private String id;
private String lookupKey;
private String dispName;
private String email;
private String mobileNo;
private Bitmap photoThumbnail;
private String statusMsg;
private int isRapo;
public Contact(){}
public Contact(String id, String lookupKey, String dispName, String email, String mobileNo, Bitmap photoThumbnail,String statusMsg,int isRapo) {
this.id = id;
this.lookupKey = lookupKey;
this.dispName = dispName;
this.email = email;
this.mobileNo = mobileNo;
//this.photoThumbnail = photoThumbnail;
this.statusMsg = statusMsg;
this.isRapo = isRapo;
}
protected Contact(Parcel in) {
id = in.readString();
lookupKey = in.readString();
dispName = in.readString();
email = in.readString();
mobileNo = in.readString();
//photoThumbnail = in.readParcelable(Bitmap.class.getClassLoader());
//photoThumbnail = (Bitmap)in.readValue(Bitmap.class.getClassLoader());
photoThumbnail = (Bitmap)in.readParcelable(Bitmap.class.getClassLoader());
statusMsg = in.readString();
isRapo = in.readInt();
}
public static final Creator<Contact> CREATOR = new Creator<Contact>() {
#Override
public Contact createFromParcel(Parcel in) {
return new Contact(in);
}
#Override
public Contact[] newArray(int size) {
return new Contact[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLookupKey() {
return lookupKey;
}
public void setLookupKey(String lookupKey) {
this.lookupKey = lookupKey;
}
public String getDispName() {
return dispName;
}
public void setDispName(String dispName) {
this.dispName = dispName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public Bitmap getPhotoThumbnail() {
return photoThumbnail;
}
public void setPhotoThumbnail(Bitmap photoThumbnail) {
this.photoThumbnail = photoThumbnail;
}
public String getStatusMsg() {
return statusMsg;
}
public void setStatusMsg(String statusMsg) {
this.statusMsg = statusMsg;
}
public int getIsRapo() {
return isRapo;
}
public void setIsRapo(int isRapo) {
this.isRapo = isRapo;
}
#Override
public String toString() {
return dispName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(lookupKey);
dest.writeString(dispName);
dest.writeString(email);
dest.writeString(mobileNo);
//dest.writeParcelable();
/*if(photoThumbnail != null) {
photoThumbnail.writeToParcel(dest, 5);
}*/
if(photoThumbnail != null){
dest.writeParcelable(photoThumbnail,flags);
}
dest.writeString(statusMsg);
dest.writeInt(isRapo);
}
}
Service
contactResIntent.putParcelableArrayListExtra("clist", contactList);
Broadcast Listener
private BroadcastReceiver contactsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(getApplicationContext(),"GOT Contacts response from service!!!",Toast.LENGTH_SHORT).show();
Log.d("#HomeActivity", "GOT Service response.");
/*Bundle data = intent.getExtras();
ArrayList<Parcelable> clist = data.getParcelableArrayList("clist");*/
ArrayList<Contact> clist = intent.getParcelableArrayListExtra("clist");
if(clist != null){
String s = clist.get(0).getClass().toString();
Log.d("#HomeActivity","CONTACTS LIST :"+s+"##"+String.valueOf(clist.size()));
}
First of all you should avoid putting a bitmap into a Parcel. It usually uses a large amount of memory and I've experienced some TransactionTooLargeException when transferring large parcelables (a limitation of 1Mb). Instead you could write just a String or an identifier that represents that thumbnail and load it again if needed.
That being said, you can try the following (check for null).
Change the constructor:
protected Contact(Parcel in) {
id = in.readString();
lookupKey = in.readString();
dispName = in.readString();
email = in.readString();
mobileNo = in.readString();
if (in.readByte() == 1) {
photoThumbnail = (Bitmap) in.readParcelable(Bitmap.class.getClassLoader());
}
statusMsg = in.readString();
isRapo = in.readInt();
}
Change the writeToParcel
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(lookupKey);
dest.writeString(dispName);
dest.writeString(email);
dest.writeString(mobileNo);
if (photoThumbnail != null){
dest.writeByte((byte) 1);
dest.writeParcelable(photoThumbnail,flags);
} else {
dest.writeByte((byte) 0);
}
dest.writeString(statusMsg);
dest.writeInt(isRapo);
}

Categories