i have json to serializable claas then i use it to populate listview, and everything works fine but i want to populate textview on another xml page with one of the serializable object and i read to best way to do it is bundle intent, but i did code something wrong.
public class FeedItem implements Serializable {
private String title;
private String date;
private String attachmentUrl;
private String id;
private String content;
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAttachmentUrl() {
return attachmentUrl;
}
public void setAttachmentUrl(String attachmentUrl) {
this.attachmentUrl = attachmentUrl;
}
#Override
public String toString() {
return "[ title=" + title + ", date=" + date + "]";
}
ArrayList<FeedItem> all_thumbs = new ArrayList<FeedItem>();
all_thumbs.add(new FeedItem(title);
Intent intent = new Intent(title);
Bundle extras = new Bundle();
extras.putSerializable("title",title);
intent.putExtras(extras);
}
and in the class where i want to use it
public void updateList() {
TextView infoz = (TextView) getView().findViewById(R.id.infoz);
Bundle args;
getArguments().getSerializable(title);
Instead use:
public void updateList() {
TextView infoz = (TextView) getView().findViewById(R.id.infoz);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String title = (String) extras.getSerializable("title");
IF you want to pass any primitive datatyped values (String,int,long,float etc.) then do not need to use Bundle.putExtra(KEY,Serialized Object) and Bundle.getSerializable(KEY). You can use Bundle.putExtra(KEY,primitive data);
If you want to pass class object to intent/bundle then you need to implement Serializable/Parsable in that class like:
public class Test implements Serializable
{
private static final long serialVersionUID = 1L;
int test1;
}
and then you can pass that object instance to intent like:
myIntent.putExtra( KEY, new Test() );
For more clarification check pass seriable object in intent example
Related
public class Memo extends AppCompatActivity {
DBHandler dbh;
Notes items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memo);
getSupportActionBar().hide();
try{
dbh = new DBHandler(this);
}
catch (Exception ex){
ex.printStackTrace();
}
display();
}
public void display( ){ //method to display all items in the database
List<Notes> books_list = dbh.getNotes(); ////here i get the list fromm the database
///// i used a custom adapter because i needed it
final myAdapter adapter = new myAdapter(this, books_list); ///creating adapter from
myadapter to link it with the list
ListView _note_ = findViewById(R.id.list_txt);
_note_.setAdapter(adapter);
_note_.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items = (Notes) adapter.getItem(position);
String Note_content = items.getNote();
String title = items.getTitle();
String Date = items.getDate();
Intent i = new Intent(getApplicationContext() ,Note_content.class);
i.putExtra("Note ", Note_content);
i.putExtra("title", title);
i.putExtra("Date", Date);
startActivity(i);
}
});
i have a problem when I try to to get data( only Note) from this activity to another activity, other values(Date and Title) are working, I tried to use toString method in Notes class but it gives null for note
public class Note_content extends AppCompatActivity {
Notes item;
TextView txt_note ,txt_date , txt_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_content);
txt_title = findViewById(R.id.txt_ntitle);
txt_note = findViewById(R.id.txt_Nnote);
txt_date = findViewById(R.id.txt_Ndate);
Intent i = getIntent();
String note = i.getStringExtra("Note");
String title = i.getStringExtra("title");
String date = i.getStringExtra("Date");
item = new Notes(title,note,date);
txt_note.setText(item.getNote());
//txt_note.setText(note)
txt_date.setText(date);
txt_title.setText(title);
}
this is the second activit, it is not giving any errors but null instead of the note
and this Notes class
public class Notes {
private int id;
private String title;
private String note ;
private String date;
public Notes() {
}
public Notes(String title, String note, String date) {
this.title = title;
this.note = note;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return this.note+"\n"+title+"\n"+date;
}
}
i.putExtra("Note ", Note_content);
In the above code line, "Note " has an extra space at the end.
I am trying to save an ArrayList of objects (List shelfItems) in the bundle to retrieve it next time the activity is opened.
(the activity gets info from firestore and I want to decrease reads and take away loading time each time the activity is opened).
but i get this error message:
savedInstanceState.putParcelableArrayList("key", shelfItems);
"putParcelableArrayList(java.lang.String, java.util.ArrayList)' in 'android.os.Bundle' cannot be applied to '(java.lang.String, java.util.List)"
This is my object class:
import android.os.Parcel;
import android.os.Parcelable;
public class ShelfItem implements Parcelable{
private String mTitle;
private String mAuthor;
private String mThumbnail;
private long mRating;
private long mEndDate;
private long mBeginDate;
private String mId;
private long mPages;
private boolean mVisible;
//make ShelfItem object
public ShelfItem(String title, String author, String thumbnail, long rating, long beginDate, long endDate, String id, long pages, boolean visible) {
mTitle = title;
mAuthor = author;
mThumbnail = thumbnail;
mRating = rating;
mBeginDate = beginDate;
mEndDate = endDate;
mId = id;
mPages = pages;
mVisible = visible;
}
public String getTitle() {
return mTitle;
}
public String getAuthor() {
return mAuthor;
}
public String getThumbnail() {
return mThumbnail;
}
public long getRating() {
return mRating;
}
public long getBeginDate() {
return mBeginDate;
}
public long getEndDate() {
return mEndDate;
}
public String getId() {
return mId;
}
public long getPages() {
return mPages;
}
public boolean getVisible() {
return mVisible;
}
public ShelfItem(Parcel in) {
mId = in.readString();
mTitle = in.readString();
mAuthor = in.readString();
mThumbnail = in.readString();
mBeginDate = in.readLong();
mEndDate = in.readLong();
mPages = in.readLong();
mVisible = in.readByte() != 0;
mRating = in.readLong();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mId);
out.writeString(mTitle);
out.writeString(mAuthor);
out.writeString(mThumbnail);
out.writeLong(mBeginDate);
out.writeLong(mEndDate);
out.writeLong(mPages);
out.writeByte((byte) (mVisible ? 1 : 0));
out.writeLong(mRating);
}
public static final Parcelable.Creator<ShelfItem> CREATOR = new Parcelable.Creator<ShelfItem>() {
public ShelfItem createFromParcel(Parcel in) {
return new ShelfItem(in);
}
public ShelfItem[] newArray(int size) {
return new ShelfItem[size];
}
};
}
and this is how I try to save the list:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putParcelableArrayList("key", shelfItems);
}
As we learn Java, we're taught to use the interface type (List) instead of the implementation type (ArrayList) when we declare our variables. You probably have code somewhere that looks like this:
List<ShelfItem> shelfItems = new ArrayList<>();
However, in the particular case of Bundle and saving lists, you must use ArrayList specifically, and not any List in general.
If I'm right, and your list is declared like I've shown above, just change it to explicitly use ArrayList:
ArrayList<ShelfItem> shelfItems = new ArrayList<>();
If you're getting the list from somewhere else, and you can't control the implementation type of it, you can construct a new ArrayList when you need to save it:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
ArrayList<ShelfItem> toSave = new ArrayList<>(shelfItems);
savedInstanceState.putParcelableArrayList("key", toSave);
}
Please I need your help .I'am trying to take the date from an activity and then put it in an array list then print it in an ListView .
The problem is the data that I should take it from "Adding Todo" is not showing in the ListView . it do take me to the List Activity but without showing the data .
This is How the app going to be "Adding todo"
And this is the ListView where the data should be in it
My code :-
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
arrayList = new ArrayList<>();
todoAdapter = new TodoAdapter(this , arrayList);
listView.setAdapter(todoAdapter);
}
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, AddTodo.class);
startActivityForResult(intent, Intent_Constants.INTENT_REQUEST_CODE);
}
protected void onActivityResult(int reqCode ,int resultCode , Intent data ){
// here Iam trying to get the data from ADDING TO DO class
if(resultCode == Intent_Constants.INTENT_REQUEST_CODE){
titleText = data.getStringExtra(Intent_Constants.INTENT_TITLE);
priorityText = data.getStringExtra(Intent_Constants.INTENT_PRIORITY);
statusText = data.getStringExtra(Intent_Constants.INTENT_STATUES);
dateText = data.getStringExtra(Intent_Constants.INTENT_DATE);
timeText = data.getStringExtra(Intent_Constants.INTENT_TIME);
todoAdapter.todo.add(new Todo (titleText , statusText ,priorityText ,dateText ,timeText));
}
}
Intent_Constants
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE = 1;
public final static int INTENT_RESULT_CODE = 1 ;
public final static String INTENT_TITLE = "Title";
public final static String INTENT_PRIORITY = "Priority";
public final static String INTENT_TIME = "Time";
public final static String INTENT_DATE = "Date";
public final static String INTENT_STATUES = "Statues";
}
AddTodo class
In this class I find the id then I converted to String
public void saveButton (View view){
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_TITLE , title);
intent.putExtra(Intent_Constants.INTENT_DATE , date);
intent.putExtra(Intent_Constants.INTENT_TIME , time);
intent.putExtra(Intent_Constants.INTENT_PRIORITY , priority);
intent.putExtra(Intent_Constants.INTENT_STATUES , completed);
setResult(INTENT_RESULT_CODE, intent);
finish();
}
TodoAdapter class
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
super(context, R.layout.todo_list,todo);
this.todo = todo;
}
public static class ViewHolder {
TextView titleText;
TextView priorityText;
TextView dateText;
TextView timeText;
CheckBox statusBox;
ImageButton edit_image;
ImageButton open_image;
ImageButton delet_image;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = LayoutInflater.from(getContext()) ;
View customeView =inflater.inflate(R.layout.todo_list,parent ,false);
holder.titleText.setText(getItem(position).getTitle());
holder.priorityText.setText(getItem(position).getPriority());
holder.dateText.setText(getItem(position).getDate());
holder.timeText.setText(getItem(position).getTime());
holder.statusBox.setChecked(false);
holder.edit_image = customeView.findViewById(R.id.edit_imageView);
holder.open_image = customeView.findViewById(R.id.open_imageButton);
holder.delet_image = customeView.findViewById(R.id.delete_imageView);
holder.edit_image.setImageResource(R.drawable.ic_edit_black_24dp);
holder.open_image.setImageResource(R.drawable.ic_refresh_black_24dp);
holder.delet_image.setImageResource(R.drawable.ic_delete_black_24dp);
return customeView;
}
Todo class
public class Todo {
private String title ;
private String status ;
private String priority ;
private String date ;
private String time ;
public Todo() {
}
public Todo(String title, String status, String priority, String date, String time) {
this.title = title;
this.status = status;
this.priority = priority;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public String getStatus() {
return status;
}
public String getPriority() {
return priority;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public void setTitle(String title) {
this.title = title;
}
public void setStatus(String status) {
this.status = status;
}
public void setPriority(String priority) {
this.priority = priority;
}
public void setDate(String date) {
this.date = date;
}
public void setTime(String time) {
this.time = time;
}
}
You can just set a new adapter, I know it isn't best way, but should do the work. Don't create new one, but nulify yours, and initialize it with new data.
#Noura change this
arrayList.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
to
todoAdapter.todo.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
todoAdapter.notifyDataSetChanged();
and at the constructor u need to update your code like below
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
this.todo = todo
super(context, R.layout.todo_list,todo);
}
I am using Retrofit to fetch and display data to the screen. I want to search users by their id's. I made interface like this :
#GET("/posts/{id}")
Call<postmodel> getUsersModel(#Path("id") int id);
The problem is with DetailActivity line 52:
EndPointAccess access = APIClient.getRetrofit().create(EndPointAccess.class);
Call<postmodel> modelCall = access.getUsersModel(Integer.parseInt(_userinput));
Here is the Logcat report:
android.content.res.Resources$NotFoundException:
String resource ID #0x1
at
android.content.res.Resources.getText(Resources.java:351)
at
android.content.res.MiuiResources.getText(MiuiResources.java:97)
at
android.widget.TextView.setText(TextView.java:4562)
at com.example.sahil.typicode1.Activity.DetailActivity$2.onResponse(DetailActivity.java:60)
APIClient.java
public static final String BASE_URL = "https://jsonplaceholder.typicode.com";
private static Retrofit retrofit = null;
public static Retrofit getRetrofit()
{
if (retrofit == null)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory
.create()).build();
}
return retrofit;
}
EndPointAccess.java (Interface)
#GET("/posts/{id}")
Call<postmodel> getUsersModel(#Path("id") int id);
MainActivity.java
EditText userid;
Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userid = (EditText) findViewById(R.id.etuserid);
search = (Button) findViewById(R.id.btnsearch);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,DetailActivity.class);
intent.putExtra("STRING_I_NEED",userid.getText().toString());
startActivity(intent);
}
});
}
DetailActivity.java
TextView userid,usertitle,userbody;
Button viewall;
String _userinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
_userinput = intent.getStringExtra("STRING_I_NEED");
userid = (TextView) findViewById(R.id.textViewid);
usertitle = (TextView) findViewById(R.id.textViewtitle);
userbody = (TextView) findViewById(R.id.textViewbody);
viewall = (Button) findViewById(R.id.btnviewall);
viewall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(DetailActivity.this, "Done!", Toast.LENGTH_SHORT).show();
}
});
getinfo();
}
private void getinfo()
{
EndPointAccess access = APIClient.getRetrofit().create(EndPointAccess.class);
Call<postmodel> modelCall = access.getUsersModel(Integer.parseInt(_userinput));
modelCall.enqueue(new Callback<postmodel>() {
#Override
public void onResponse(Call<postmodel> call, Response<postmodel> response)
{
userid.setText(response.body().getId());
usertitle.setText(response.body().getTitle());
userbody.setText(response.body().getBody());
}
#Override
public void onFailure(Call<postmodel> call, Throwable t) {
Toast.makeText(DetailActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
});
}
postmodel.java (pojo class)
private int id;
private String title;
private String body;
public postmodel(int id, String title, String body) {
this.id = id;
this.title = title;
this.body = body;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
You are trying to set an integer in the setText function which only accepts String values. Therefore it is giving this error.
Hence you need to convert it into a string using String.valueOf() function.
remove userid.setText(response.body().getId());
add userid.setText(String.valueOf(response.body().getId()));
SetText with integer parameter looks resource with that id : reference
So you should pass an string value to setText()
userid.setText(String.valueOf(response.body().getId()));
So, replacing this line in DetailActivity.java might help you fix the exception :)
Fisrt i must mention that i am new to Android and Java. I coded a json http object who populate Serializable class and from them i populate listviews, everything works fine, but now i am trying to populate a textview which is on different xml layout, with one string from Serializable class.
Serializable class
public class FeedItem implements Serializable {
private static final long serialVersionUID = 1L;
private int test1;
private String title;
private String date;
private String attachmentUrl;
private String id;
private String content;
private String url;
private String tiitle = "sfsf";
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAttachmentUrl() {
return attachmentUrl;
}
public void setAttachmentUrl(String attachmentUrl) {
this.attachmentUrl = attachmentUrl;
}
#Override
public String toString() {
return "[ title=" + title + ", date=" + date + "]";
}
public void save(){
FeedItem feed = new FeedItem();
Intent intent = new Intent();
Bundle extras = new Bundle();
intent.putExtra("title", feed);
and the fragment class where i want to populate textview
public void UpdateList(){
TextView infoz = (TextView) getView().findViewById(R.id.infoz);
Intent intent = getActivity().getIntent();
Bundle extras = intent.getExtras();
String title = (String) getActivity().getIntent().getSerializableExtra("title");
Toast.makeText(getActivity(), title, Toast.LENGTH_LONG).show();
}
The toast is empty.
You are putting a Serializable object in your Bundle (in Eclipse, moving your mouse above the method name should show you the signature, which in your case would be putExtra(String name, Serializable extra)). To retrieve the title String, you should first retrieve the FeedItem object, then get the String from it, like so :
intent.putExtra("title", feed);
and
String title = ((FeedItem)getActivity().getIntent().getSerializableExtra("title")).getTitle();
Alternatively, you could just put the title in the extra, if that's all you need, using
intent.putExtra("title", feed.getTitle());
then getting the title like this :
String title = getActivity().getIntent().getStringExtra("title");
This is the code you are using to get the title from the intent:
String title = (String) getActivity().getIntent().getSerializableExtra("title");
This will extract the extra with the key "title" and deserialize it, but you are then casting this to a String. You didn't put a String into the extras Bundle, you put a FeedItem object in there. You need to do this:
FeedItem feedItem = (FeedItem)getActivity().getIntent().getSerializableExtra("title");
String title = feedItem.getTitle();
Also, this code you posted:
public void save(){
FeedItem feed = new FeedItem();
Intent intent = new Intent();
Bundle extras = new Bundle();
intent.putExtra("title", feed);
makes no sense. First, you create a new instance of FeedItem. This new instance will have an empty title. Secondly, you create a Bundle called extras but do nothing with it. And thirdly, are you sure that the Intent you are sending actually has the object you want in the extras? Either check this with a debugger or debug logging.