I have a list which I am trying to broadcast with the use of intents. After following online tutorials, I was adviced to use Parcelable in order to send this data. However, I keep getting this error in logcat:
Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.os.Parcelable
from this line of code
bundle.putParcelable("data", (Parcelable)tweets);
I do not know how to correct this.
Where i am building the intent
protected void onHandleWork(#NonNull Intent intent) {
Log.d(TAG, "onHandleWork: ");
List<tweet> tweets = new ArrayList();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("HyjgZgfiqSODTdICZUXIHI8HK", "TlynMItosq99QxnLMLGxA6FElD3TAKx9UmBxva5oExg9Gz1mzV");
AccessToken accessToken = new AccessToken("2362719277-w5QlRNB2I7PXdMJuDXf5cc8FDT5H8X38ujxrtiT", "3v2Z2cqezaFrV6pFHu2yfPVFHZgMvLjMVKH4cUujI9kwI");
twitter.setOAuthAccessToken(accessToken);
Query query = new Query("Twitch");
try {
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
String createdat = status.getCreatedAt().toString();
String text = status.getText();
String retweets = String.valueOf(status.getRetweetCount());
String favs = String.valueOf(status.getFavoriteCount());
String uri = status.getUser().getProfileImageURL();
tweet onetweet = new tweet(createdat,text,retweets,favs,uri);
// Log.d(TAG, status.getText());
tweets.add(onetweet);
}
if (isStopped()) return;
} catch (TwitterException e) {
e.printStackTrace();
}
sendToUI(tweets);
}
private void sendToUI(List tweets) {
Intent intent = new Intent("tweet_result");
Bundle bundle = new Bundle();
bundle.putParcelable("data", tweets);
intent.putExtras(bundle);
sendBroadcast(intent);
}
My tweet POJO
import android.os.Parcel;
import android.os.Parcelable;
public class tweet implements Parcelable {
private String created_at;
private String text;
private String retweet_count;
private String favorite_count;
private String image_uri;
public String getImage_uri() {
return image_uri;
}
public String getCreated_at() {
return created_at;
}
public String getText() {
return text;
}
public String getRetweet_count() {
return retweet_count;
}
public String getFavorite_count() {
return favorite_count;
}
protected tweet(Parcel in) {
created_at = in.readString();
text = in.readString();
retweet_count = in.readString();
favorite_count = in.readString();
image_uri = in.readString();
}
public static final Creator<tweet> CREATOR = new Creator<tweet>() {
#Override
public tweet createFromParcel(Parcel in) {
return new tweet(in);
}
#Override
public tweet[] newArray(int size) {
return new tweet[size];
}
};
#Override
public int describeContents() {
return 0;
}
public tweet(String created_at, String text, String retweet_count, String favorite_count, String image_uri) {
this.created_at = created_at;
this.text = text;
this.retweet_count = retweet_count;
this.favorite_count = favorite_count;
this.image_uri = image_uri;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(created_at);
dest.writeString(text);
dest.writeString(retweet_count);
dest.writeString(favorite_count);
dest.writeString(image_uri);
}
}
You used wrong method, you should use intent.putParcelableArrayListExtra() but don't forget about that your array list must contains only parcelables items.
Changing my sendToUI() to this has worked:
private void sendToUI(List tweets) {
Intent intent = new Intent("tweet_result"); //tweet_result is a string to identify this intent
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) tweets);
intent.putExtras(bundle);
sendBroadcast(intent);
}
Related
I am trying to pass an object to another class using intent. The object implements Parcelable.
The thing is, when I try to get the attributes it doesn't get the object, it says it's null.
But when I do a System.out.println of the intent.getExtras():
Bundle[{usuariocreado =com.example.frpi.repasando.Usuario#4ed1d39}]
It's actually there!
if (this.getIntent().getExtras() != null) {
Usuario usuariocreado = intent.getParcelableExtra("usuariocreado");
usuariocreado.getNombreUsuario();
} else {
System.out.println("Mierda");
}
This is the code on MainActivty which receives the intent.
NombreUsuario = (EditText) findViewById(R.id.UsuarioRegister);
PasswordPrimero = (EditText) findViewById(R.id.PasswordPrimero);
Usuario obj = new Usuario(String.valueOf(NombreUsuario.getText()), String.valueOf(PasswordPrimero.getText()));
Intent intent = new Intent(getBaseContext(), MainActivity.class);
Usuario usuariocreado = new Usuario(String.valueOf(NombreUsuario.getText()), String.valueOf(PasswordPrimero.getText()));
intent.putExtra("usuariocreado ", usuariocreado);
startActivity(intent);
This is the code on the SecondActivity which sends the intent.
What am i doing wrong??
Thanks!
public class Usuario implements Parcelable {
public Usuario(String nombreUsuario, String passwordPrimero) {
NombreUsuario = nombreUsuario;
PasswordPrimero = passwordPrimero;
}
/**
* NombreUsuario : Paco
* PasswordPrimero : Example
*/
private String NombreUsuario;
private String PasswordPrimero;
protected Usuario(Parcel in) {
NombreUsuario = in.readString();
PasswordPrimero = in.readString();
}
public static final Creator<Usuario> CREATOR = new Creator<Usuario>() {
#Override
public Usuario createFromParcel(Parcel in) {
return new Usuario(in);
}
#Override
public Usuario[] newArray(int size) {
return new Usuario[size];
}
};
public String getNombreUsuario() {
return NombreUsuario;
}
public void setNombreUsuario(String NombreUsuario) {
this.NombreUsuario = NombreUsuario;
}
public String getPasswordPrimero() {
return PasswordPrimero;
}
public void setPasswordPrimero(String PasswordPrimero) {
this.PasswordPrimero = PasswordPrimero;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(NombreUsuario);
dest.writeString(PasswordPrimero);
}
}
You have to cast the intent.getParcelableExtra("usuariocreado") with Usuario
Replace
Usuario usuariocreado = intent.getParcelableExtra("usuariocreado");
with
Usuario usuariocreado = ((Usuario) intent.getParcelableExtra("usuariocreado"));
I have 2 model classes(Data,Title) which contain the same field:
String dataID. I want to get both of this IDs with interface implementation.
I am passing Title model through Bundle to another Activity, passing Data model through Bundle in that same activity(just creating new instance of the activity and resetting information).
I want both of my model classes to implement SharedID interface, with method String getSharedId();
How can I get different ids but from different models? I need to put only one parameter and it should be String in my ViewModelFactory constructor.
public class Data implements SharedId,Parcelable {
private String text;
private String textHeader;
private int viewType;
private String mainId;
private String dataID;
public Data() { }
public String getDataID() {
return dataID;
}
public void setDataID(String dataID) {
this.dataID = dataID;
}
public String getText() {return (String) trimTrailingWhitespace(text); }
public void setText(String text) {
this.text = (String) trimTrailingWhitespace(text);
}
public String getTextHeader() {
return (String) trimTrailingWhitespace(textHeader);
}
public void setTextHeader(String textHeader) {
this.textHeader = textHeader;
}
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
public String getMainId() {
return mainId;
}
public void setMainId(String mainId) {
this.mainId = mainId;
}
protected Data(Parcel in) {
text = in.readString();
textHeader = in.readString();
viewType = in.readInt();
mainId = in.readString();
dataID = in.readString();
}
#Override
public String toString() {
return "Data{" +
"order=" +
", text='" + text + '\'' +
", textHeader='" + textHeader + '\'' +
", viewType=" + viewType +
'}';
}
#SuppressWarnings("StatementWithEmptyBody")
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null) {
return "";
}
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
public static final Creator<Data> CREATOR = new Creator<Data>() {
#Override
public Data createFromParcel(Parcel in) {
return new Data(in);
}
#Override
public Data[] newArray(int size) {
return new Data[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(text);
dest.writeString(textHeader);
dest.writeInt(viewType);
dest.writeString(mainId);
dest.writeString(dataID);
}
#Override
public String getSharedDataId() {
return getDataID();
}
}
public class Title implements SharedId,Parcelable {
private String dataID;
private String title;
public Title() { }
protected Title(Parcel in) {
dataID = in.readString();
title = in.readString();
}
public String getDataID() {
return dataID;
}
public void setDataID(String dataID) {
this.dataID = dataID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public static final Creator<Title> CREATOR = new Creator<Title>() {
#Override
public Title createFromParcel(Parcel in) {
return new Title(in);
}
#Override
public Title[] newArray(int size) {
return new Title[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dataID);
dest.writeString(title);
}
#NonNull
#Override
public String toString() {
return "Title{" +
"dataID='" + dataID + '\'' +
", titleOrder=" +
", title='" + title + '\'' +
'}';
}
#Override
public String getSharedDataId() {
return getDataID();
}
}
And My DetailActivity code, I already succeeded with the mission of passing id, but i need to do this trough interfaces :( So help me out friends, would really appreciate it!
public class DetailActivity extends AppCompatActivity implements
DetailAdapter.OnDialogClickListener,
DetailAdapter.OnDetailClickListener {
private static String id;
private String parentId;
private Data data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView tvToolbarTitle = findViewById(R.id.title_toolbar_detail);
tvToolbarTitle.setSelected(true);
findViewById(R.id.btn_back).setOnClickListener(v -> finish());
ArrayList<SharedId> sharedIds = new ArrayList<>();
sharedIds.add(new Title());
sharedIds.add(new Data());
for (SharedId sharedId : sharedIds){
System.out.println(sharedId.getSharedDataId());
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
}
if (bundle != null) {
Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
String parentId = bundle.getString("mainScreenId");
if (parentId != null) {
this.parentId = parentId;
}
if (model != null) {
this.id = model.getDataID();
tvToolbarTitle.setText(model.getTitle());
}
if (childModel != null) {
this.id = childModel.getDataID();
tvToolbarTitle.setText(childModel.getTextHeader());
}
}
RecyclerView recyclerView = findViewById(R.id.rv_detail);
DetailAdapter adapter = new DetailAdapter(this, this);
recyclerView.setAdapter(adapter);
// TODO: 3/1/19 change it to single ID // DetailViewModelFactory(); // id != null ? id : parentId
DetailViewModelFactory detailViewModelFactory = new DetailViewModelFactory(id != null ? id : parentId);
DetailActivityViewModel viewModel = ViewModelProviders.of(this, detailViewModelFactory).get(DetailActivityViewModel.class);
FirebaseListLiveData<Data> liveData = viewModel.getLiveDataQuery();
liveData.observe(this, adapter::setNewData);
}
#Override
public void onDialogClicked(#NonNull String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(HtmlCompat.fromHtml(text, 0, null, new HandlerHtml()));
builder.setPositiveButton("Ok", null);
builder.show();
}
#Override
public void onDetailClicked(Data data) {
Intent intent = new Intent();
DetailActivity.open(DetailActivity.this);
intent.putExtra("idDetail", data);
intent.putExtra("mainScreenId", id);
startActivity(intent);
}
public static void open(#NonNull Context context) {
context.startActivity(new Intent(context, InfoActivity.class));
}
}
I found a bit different, but working solution!
I create an interface
public interface SharedId {
String getSharedDataId();
String getHeader();
}
Both of my model classes Data + Title implemented Interface and methods from it.
In DetailActivity i created 2 Strings.
private String mainId;
private String detailId;
And then passed ids with my model classes with bundle
`SharedId mainId = new Title();
SharedId detailId = new Data();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mainId = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
detailId = bundle.containsKey("idDetail") ?
bundle.getParcelable("idDetail") : null;
}
if (mainId != null) {
this.detailId = mainId.getSharedDataId();
tvToolbarTitle.setText(mainId.getHeader());
}
if (detailId != null) {
this.mainId = detailId.getSharedDataId();
tvToolbarTitle.setText(detailId.getHeader());
}
And passed in my ViewmodelFactory
DetailViewModelFactory detailViewModelFactory =
new DetailViewModelFactory(this.detailId != null ?
this.detailId : this.mainId);
I want to in finish Activity with result put a List of objets I created a class which look like this :
public class Vals implements Serializable {
public ArrayList<RowBean> data;
public Vals(ArrayList<RowBean> data) {
this.data = data;
}
}
Next in activity (fragment) I did this when I finish my activity with result :
private void finishWithResult() {
Bundle conData = new Bundle();
conData.putString("param_result", counter + "");
Intent intent = new Intent();
intent.putExtras(conData);
ArrayList<RowBean> rows = new ArrayList<>();
for(RowBean row : rowBeen){
if(row.isSelected())
rows.add(row);
}
intent.putExtra(ROW_BEAN_DATA, new Vals(rows));
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
And in console I have :
FATAL EXCEPTION: main
Process: com.maps, PID: 10222 java.lang.RuntimeException:
Parcelable encountered IOException writing serializable object (name = com.maps.Utils.Vals) at
android.os.Parcel.writeSerializable(Parcel.java:1316) at android.os.Parcel.writeValue(Parcel.java:1264) at android.os.Parcel.writeArrayMapInternal(Parcel.java:618) at android.os.Bundle.writeToParcel(Bundle.java:1692) at android.os.Parcel.writeBundle(Parcel.java:636) at android.content.Intent.writeToParcel(Intent.java:7582) at android.app.ActivityManagerProxy.finishActivity(ActivityManagerNative.java:2517)at android.app.Activity.finish(Activity.java:4324) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.finishWithResult(FragmentListOfAllObjetsToReportActivity.java:156) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.confirmChoose(FragmentListOfAllObjetsToReportActivity.java:160) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.access$200(FragmentListOfAllObjetsToReportActivity.java:34) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity$3.onClick(FragmentListOfAllObjetsToReportActivity.java:102) at android.view.View.performClick(View.java:4640)
This is onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 90:
if (resultCode == RESULT_OK) {
Bundle res = data.getExtras();
String result = res.getString("param_result");
int count = Integer.parseInt(result);
if (count != 1)
tvChooseObjects.setText("Wybrano " + count + " obiekty");
else
tvChooseObjects.setText("Wybrano " + count + " obiekt");
rowBeen = ((Vals) getIntent().getSerializableExtra(FragmentListOfAllObjetsToReportActivity.ROW_BEAN_DATA)).data;
Toast.makeText(getApplicationContext(), rowBeen.size() + " " , Toast.LENGTH_LONG).show();
}
break;
}
Try replacing Serializable implementation with Parcelable in Vals & RawBean classes
Replace getSerializableExtra with getParcelableExtra in *onActivityResult**
Vals.java
public class Vals implements Serializable, Parcelable {
public ArrayList<RowBean> data;
public Vals(ArrayList<RowBean> data) {
this.data = data;
}
protected Vals(Parcel in) {
if (in.readByte() == 0x01) {
data = new ArrayList<RowBean>();
in.readList(data, RowBean.class.getClassLoader());
} else {
data = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (data == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(data);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Vals> CREATOR = new Parcelable.Creator<Vals>() {
#Override
public Vals createFromParcel(Parcel in) {
return new Vals(in);
}
#Override
public Vals[] newArray(int size) {
return new Vals[size];
}
};
}
RawBean.java
public class RowBean implements Serializable, Parcelable {
public String title;
public boolean selected;
public RowBean(){
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public RowBean(boolean selected, String title) {
this.selected = selected;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
protected RowBean(Parcel in) {
title = in.readString();
selected = in.readByte() != 0x00;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeByte((byte) (selected ? 0x01 : 0x00));
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<RowBean> CREATOR = new Parcelable.Creator<RowBean>() {
#Override
public RowBean createFromParcel(Parcel in) {
return new RowBean(in);
}
#Override
public RowBean[] newArray(int size) {
return new RowBean[size];
}
};
}
Check out This example
public class Vals implements Serializable {
int id;
String name;
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 Vals(int id, String name) {
this.id = id;
this.name = name;
}
}
Add DataWraperClass
public class DataWrapper implements Serializable {
private ArrayList<Vals > mServicesList;
public DataWrapper(ArrayList<Vals > data) {
this.mServicesList = data;
}
public ArrayList<Vals > getServicesList() {
return this.mServicesList;
}
}
Create Intent Like This
DataWrapper mServiceListData = new DataWrapper(yourarraylist);
mIntent = new Intent(KitVerfiyActivity.this, BeneficiaryDetailsActivity.class);
mIntent.putExtra("arr_list", mServiceListData);
startActivity(mIntent);
get arraylist from Intent like this
DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("arr_list");
mArrayCaseFullList = dw.getServicesList();
Hope this will help you
Use Below method :
private void finishWithResult() {
Bundle conData = new Bundle();
conData.putString("param_result", counter + "");
Intent intent = new Intent();
ArrayList<RowBean> rows = new ArrayList<>();
for(RowBean row : rowBeen){
if(row.isSelected())
rows.add(row);
}
conData.putSerializable(ROW_BEAN_DATA, new Vals(rows));
intent.putExtras(conData);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
Retrieve your data like below code :
Bundle bundle = getIntent().getExtras();
rowBeen = ((Vals) bundle.getSerializable(ROW_BEAN_DATA);
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()
on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!
MyBlog Adapter:
public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogResponse> postsList;
Context context;
public static String blog_Id, blogID;
private LayoutInflater inflater;
public MyBlogAdapter(Context context, List<BlogResponse> postsList){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.postsList = postsList;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_view,parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
final BlogResponse posts= postsList.get(position);
holder.summary.setText(posts.getBlogExcerpt().trim().toString());
holder.title.setText(posts.getBlogTitle().trim().toString());
// Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);
holder.blogHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AnotherSingleView.class);
blog_Id = posts.getBlogId();
intent.putExtra(blogID,blog_Id);
Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
Log.d("MyBlogAdapter,","getItemCount"+postsList.size());
return postsList == null ? (0) : postsList.size();
}
}
SecondActivity:
public class AnotherSingleView extends AppCompatActivity {
String postID;
int position;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
SingleBlogPost singleBlogPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_single_view);
Intent intent = getIntent();
Bundle showBlogId = intent.getExtras();
postID = showBlogId.getString(blogID);
Log.d("AnotherSingleView","Please check blog Id: "+postID);
singleBlogPosts = new ArrayList<>();
blogContent = (TextView)findViewById(R.id.blog_content);
blogSub = (TextView) findViewById(R.id.blog_subtitle);
blogTitle =(TextView) findViewById(R.id.blog_title);
blogPic =(ImageView) findViewById(R.id.blog_pix);
singlePostDisplay();
}
private void singlePostDisplay() {
BlogaPI api = ApiClient.getBlogInterface();
Call<List<SingleBlogPost>> call = api.postResponse(postID);
call.enqueue(new Callback<List<SingleBlogPost>>() {
#Override
public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
singleBlogPosts = response.body();
if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
for (SingleBlogPost posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
else{
Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
} }
#Override
public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Interface:
public interface BlogaPI {
#GET("blog")
Call<BlogList> response();
#GET("post/{blog_id}")
Call<List<SingleBlogPost>> postResponse(#Path("blog_id") String blog_id);
//Call<List<SingleBlogPost>> postResponse();
}
SingleBlogPost:
public class SingleBlogPost {
#SerializedName("blog_id")
#Expose
private String blogId;
#SerializedName("blog_title")
#Expose
private String blogTitle;
#SerializedName("blog_subtitle")
#Expose
private String blogSubtitle;
#SerializedName("blog_excerpt")
#Expose
private String blogExcerpt;
#SerializedName("blog_content")
#Expose
private String blogContent;
#SerializedName("blog_thumbnail")
#Expose
private String blogThumbnail;
#SerializedName("blog_medimg")
#Expose
private String blogMedimg;
#SerializedName("category_title")
#Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
this.blogId = blogId;
this.blogTitle = blogTitle;
this.blogSubtitle = blogSubtitle;
this.blogExcerpt = blogExcerpt;
this.blogContent = blogContent;
this.blogThumbnail = blogThumbnail;
this.blogMedimg = blogMedimg;
this.categoryTitle = categoryTitle;
}
public String getBlogId() {
return blogId;
}
public void setBlogId(String blogId) {
this.blogId = blogId;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogSubtitle() {
return blogSubtitle;
}
public void setBlogSubtitle(String blogSubtitle) {
this.blogSubtitle = blogSubtitle;
}
public String getBlogExcerpt() {
return blogExcerpt;
}
public void setBlogExcerpt(String blogExcerpt) {
this.blogExcerpt = blogExcerpt;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getBlogThumbnail() {
return blogThumbnail;
}
public void setBlogThumbnail(String blogThumbnail) {
this.blogThumbnail = blogThumbnail;
}
public String getBlogMedimg() {
return blogMedimg;
}
public void setBlogMedimg(String blogMedimg) {
this.blogMedimg = blogMedimg;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
}
Check if the server response is different then null before you do a enhanced for like this:
if(singleBlogPosts!= null) {
for (SingleBlogPosts posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
you question was list iterator,but we can`t see you list use on anywhere,i guess you may be use recyclerView on you data has not get,because get data was asynchronous.try to use data if you can sure it is existing.
I'm trying to run an application and it crashes because of this error:
FATAL EXCEPTION: main
Process: com.panaceasoft.citiesdirectory, PID: 4201
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: ""
It had some Gradle errors, but I had solved them, and now it still crashed when I tried to run the app. It looks like that problem is in the class below, at line 252. Tried everything possible to check data and to solve this error, but nothing so far. What should I do? Thanks!
CitiesListFragment:
public class CitiesListFragment extends Fragment {
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Variables
//-------------------------------------------------------------------------------------------------------------------------------------
private RecyclerView mRecyclerView;
private ProgressWheel progressWheel;
private CityAdapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private TextView display_message;
private ArrayList<PCityData> pCityDataList;
private ArrayList<PCityData> pCityDataSet;
private NestedScrollView singleLayout;
private TextView scCityName;
private TextView scCityLocation;
private TextView scCityAbout;
private TextView scCityCatCount;
private TextView scCitySubCatCount;
private TextView scCityItemCount;
private ImageView scCityPhoto;
private Button scCityExplore;
private String jsonStatusSuccessString;
private String connectionError;
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Public Variables
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
public CitiesListFragment() {
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cities_list, container, false);
initUI(view);
initData();
return view;
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initUI(View view){
initSingleUI(view);
initSwipeRefreshLayout(view);
initProgressWheel(view);
initRecyclerView(view);
startLoading();
}
private void initSingleUI(View view) {
singleLayout =(NestedScrollView) view.findViewById(R.id.single_city_layout);
scCityName = (TextView) view.findViewById(R.id.sc_city_name);
scCityLocation = (TextView) view.findViewById(R.id.sc_city_loc);
scCityAbout = (TextView) view.findViewById(R.id.sc_city_desc);
scCityCatCount = (TextView) view.findViewById(R.id.txt_cat_count);
scCitySubCatCount = (TextView) view.findViewById(R.id.txt_sub_cat_count);
scCityItemCount = (TextView) view.findViewById(R.id.txt_item_count);
scCityPhoto = (ImageView) view.findViewById(R.id.sc_city_photo);
scCityExplore = (Button) view.findViewById(R.id.button_explore);
int screenWidth = Utils.getScreenWidth();
int rlWidth = (screenWidth/3) - 20;
RelativeLayout r1 = (RelativeLayout) view.findViewById(R.id.rl_count1);
RelativeLayout r2 = (RelativeLayout) view.findViewById(R.id.rl_count2);
RelativeLayout r3 = (RelativeLayout) view.findViewById(R.id.rl_count3);
r1.setMinimumWidth(rlWidth);
r2.setMinimumWidth(rlWidth);
r3.setMinimumWidth(rlWidth);
scCityPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
scCityExplore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
}
private void initSwipeRefreshLayout(View view) {
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
requestData(Config.APP_API_URL + Config.GET_ALL);
}
});
}
private void initProgressWheel(View view) {
progressWheel = (ProgressWheel) view.findViewById(R.id.progress_wheel);
}
private void initRecyclerView(View view) {
mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(llm);
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setVisibility(view.GONE);
pCityDataSet = new ArrayList<>();
adapter = new CityAdapter(getActivity(), pCityDataSet);
mRecyclerView.setAdapter(adapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
onItemClicked(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initData(){
requestData(Config.APP_API_URL + Config.GET_ALL);
jsonStatusSuccessString = getResources().getString(R.string.json_status_success);
connectionError = getResources().getString(R.string.connection_error);
}
private void requestData(String uri) {
JsonObjectRequest request = new JsonObjectRequest(uri,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
if (status.equals(jsonStatusSuccessString)) {
progressWheel.setVisibility(View.GONE);
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
Utils.psLog("City Count : " + pCityDataList.size());
if(pCityDataList.size() > 1) {
singleLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
updateDisplay();
}else{
mRecyclerView.setVisibility(View.GONE);
singleLayout.setVisibility(View.VISIBLE);
stopLoading();
updateSingleDisplay();
}
updateGlobalCityList();
} else {
stopLoading();
Utils.psLog("Error in loading CityList.");
}
} catch (JSONException e) {
Utils.psErrorLogE("Error in loading CityList.", e);
stopLoading();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ex) {
progressWheel.setVisibility(View.GONE);
stopLoading();
/* NetworkResponse response = ex.networkResponse;
if (response != null && response.data != null) {
} else {*/
try {
display_message.setVisibility(View.VISIBLE);
display_message.setText(connectionError);
}catch (Exception e){
Utils.psErrorLogE("Error in Connection Url.", e);
}
//}
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(request);
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void updateSingleDisplay() {
try {
if (pCityDataList.size() > 0) {
display_message.setVisibility(View.GONE);
singleLayout.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in));
scCityName.setText(pCityDataList.get(0).name);
scCityLocation.setText(pCityDataList.get(0).address);
scCityAbout.setText(pCityDataList.get(0).description);
scCityCatCount.setText(pCityDataList.get(0).category_count + " Categories");
scCitySubCatCount.setText(pCityDataList.get(0).sub_category_count + " Sub Categories");
scCityItemCount.setText(pCityDataList.get(0).item_count + " Items");
Picasso.with(getActivity()).load(Config.APP_IMAGES_URL + pCityDataList.get(0).cover_image_file).into(scCityPhoto);
}
}catch(Exception e){
Utils.psErrorLogE("Error in single display data binding.", e);
}
}
private void updateGlobalCityList() {
GlobalData.cityDatas.clear();
for (PCityData cd : pCityDataList) {
GlobalData.cityDatas.add(cd);
}
}
private void updateDisplay() {
if (swipeRefreshLayout.isRefreshing()) {
pCityDataSet.clear();
adapter.notifyDataSetChanged();
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
} else {
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
}
stopLoading();
adapter.notifyItemInserted(pCityDataSet.size());
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void onItemClicked(int position) {
Utils.psLog("Position : " + position);
Intent intent;
intent = new Intent(getActivity(),SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(position);
intent.putExtra("selected_city_id", pCityDataList.get(position).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
private void startLoading(){
try{
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}catch (Exception e){}
}
private void stopLoading(){
try {
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}catch (Exception e){}
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
Line 252:
pCityDataList = gson.fromJson(response.getString("data"), listType);
PCityData.class:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 6/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCityData implements Parcelable {
public int id;
public String name;
public String description;
public String address;
public String lat;
public String lng;
public String added;
public int status;
public int item_count;
public int category_count;
public int sub_category_count;
public int follow_count;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public String cover_image_description;
public ArrayList<PCategoryData> categories;
protected PCityData(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
address = in.readString();
lat = in.readString();
lng = in.readString();
added = in.readString();
status = in.readInt();
item_count = in.readInt();
category_count = in.readInt();
sub_category_count = in.readInt();
follow_count = in.readInt();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
cover_image_description = in.readString();
if (in.readByte() == 0x01) {
categories = new ArrayList<PCategoryData>();
in.readList(categories, PCategoryData.class.getClassLoader());
} else {
categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(address);
dest.writeString(lat);
dest.writeString(lng);
dest.writeString(added);
dest.writeInt(status);
dest.writeInt(item_count);
dest.writeInt(category_count);
dest.writeInt(sub_category_count);
dest.writeInt(follow_count);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
dest.writeString(cover_image_description);
if (categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCityData> CREATOR = new Parcelable.Creator<PCityData>() {
#Override
public PCityData createFromParcel(Parcel in) {
return new PCityData(in);
}
#Override
public PCityData[] newArray(int size) {
return new PCityData[size];
}
};
}
L.E:
data:
[{"id":"1","name":"MaramureČ™","description":"MaramureČ™ is a mountainous .","address":"MaramureČ™, Romania","lat":"0","lng":"0","admin_id":"3","is_approved":"1","paypal_trans_id":"0","added":"2016-07-1420:45:50","status":"1","item_count":85,"category_count":49,"sub_category_count":0,"follow_count":0,"cover_image_file":"singapore.png","cover_image_width":"600","cover_image_height":"400","cover_image_description":"Singapore","categories":
L.E:
PCategoryData.java:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 8/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCategoryData implements Parcelable {
public int id;
public int shop_id;
public String name;
public int is_published;
public int ordering;
public String added;
public String updated;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public ArrayList<PSubCategoryData> sub_categories;
public Double value;
protected PCategoryData(Parcel in) {
id = in.readInt();
shop_id = in.readInt();
name = in.readString();
is_published = in.readInt();
ordering = in.readInt();
added = in.readString();
updated = in.readString();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
if (in.readByte() == 0x01) {
sub_categories = new ArrayList<PSubCategoryData>();
in.readList(sub_categories, PSubCategoryData.class.getClassLoader());
} else {
sub_categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(shop_id);
dest.writeString(name);
dest.writeInt(is_published);
dest.writeInt(ordering);
dest.writeString(added);
dest.writeString(updated);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
if (sub_categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(sub_categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCategoryData> CREATOR = new Parcelable.Creator<PCategoryData>() {
#Override
public PCategoryData createFromParcel(Parcel in) {
return new PCategoryData(in);
}
#Override
public PCategoryData[] newArray(int size) {
return new PCategoryData[size];
}
};
}
I guess that PCategoryData has double field, and guess that json value of that double field is "";
UPDATE
Your code will be like this:
public class CitiesListFragment extends Fragment {
...
private void requestData(String uri) {
...
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PCategoryData.class, new PCategoryDataTypeAdapter());
final Gson gson = gsonBuilder.create();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
...
}
...
class PCategoryDataTypeAdapter extends TypeAdapter<PCategoryData> {
#Override
public PCategoryData read(JsonReader in) throws IOException {
final PCategoryData data = new PCategoryData();
in.beginObject();
while (in.hasNext()) {
switch (in.nextName()) {
case "value": //Please change "value" to your field name.
try {
data.value = Double.valueOf(in.nextString());
} catch (NumberFormatException e) {
data.value = 0;
}
break;
}
}
in.endObject();
return data;
}
#Override
public void write(JsonWriter out, PCategoryData data) throws IOException {
out.beginObject();
out.name("value").value(data.value); //Please change "value" to your field name.
out.endObject();
}
}
...
}