Android intent extra populate - java

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.

Related

I have problem in transferring data from activity to another activity

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.

Broadcasting a list using sendBroadcast()

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);
}

TodoList application android

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);
}

How to get the real data text, with already substring text?

I'm doing create an Catalogue Movie app. I have a ListView which contains an ImageView, title, description, and release date.
In the ListView, I take a substring of the description, because it's too long if showed in a ListView, and now I want to get the real description, in the DetailActivity (setOnItemClickListener).
This is my code:
try {
String title = object.getString("title");
String description = object.getString("overview");
double movieRatet = object.getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
String releaseDate = object.getString("release_date");
String posterUrl = object.getString("poster_path");
posterUrl = POSTER_BASE_URL + "w185" + posterUrl;
description = description.length() > 64 ? description.substring(0,64)+"...":description;
Log.d("movie poster", posterUrl);
Log.d("movie title ", title);
Log.d("movie description ", description);
Log.d("movie release ", releaseDate);
this.title = title;
this.description = description;
this.rate = releaseDate;
this.imgurl = posterUrl;
}catch (Exception e){
e.printStackTrace();
}
This is my OnItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Clicked"+position,Toast.LENGTH_LONG).show();
RelativeLayout listItem = (RelativeLayout) view.findViewById(R.id.rl_item);
TextView clickedItemView = (TextView) listItem.findViewById(R.id.tv_judul);
TextView clickedItemView2 = (TextView) listItem.findViewById(R.id.tv_deskripsi);
TextView clickedItemView3 = (TextView) listItem.findViewById(R.id.tv_rate);
String title = clickedItemView.getText().toString();
String desk = clickedItemView2.getText().toString();
String rate = clickedItemView3.getText().toString();
Intent i = new Intent(getApplicationContext(), DetailActivity.class);
desk.substring(0);
i.putExtra("title", title);
i.putExtra("desk", desk);
i.putExtra("rate", rate);
startActivity(i);
}
});
Picture of the DetailActivity:
I want to get the full description, how?
you can add a params "fullMessage" to storage the all of the message,and "description" to storage some message.Then use i.putExtra("desk", fullMessage) to carry full message to another activity.
Another solution is to add those attribute to your TextView in ListView
<TextView
<!-- other value -->
android:maxLines="3"
android:ellipsize="end"/>
And you can put full message to this TextView,it will folding itself when the message is too long.
Just do not overwrite your description variable. Instead of above have one more variable that holds your truncated value, say overview.
String overview = description.length() > 64 ? description.substring(0,64)+"...":description;
Then your description variable will continue to hold the original value. Just use that where you need.
Try this :
mymodalclass:make class
public class MyModal {
String title ;
String description ;
double movieRatet ;
String movieRate;
String releaseDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getMovieRatet() {
return movieRatet;
}
public void setMovieRatet(double movieRatet) {
this.movieRatet = movieRatet;
}
public String getMovieRate() {
return movieRate;
}
public void setMovieRate(String movieRate) {
this.movieRate = movieRate;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getPosterUrl() {
return posterUrl;
}
public void setPosterUrl(String posterUrl) {
this.posterUrl = posterUrl;
}
String posterUrl ;
}
//****************************************
while parsing data :
Arraylist list = new ArrayList();
for(int i=0;i<yourjsonarray.length();i++){
JSONObject object = yourjsonarray.getJSONObject(i);
MyModal m = new MyModal();
m.setTitle(object.getString("title"));//like this set all data
//now add this object to list
list.add(m);
}
//now when you click list just get clicked position and by this position get that particular object and pass that to next activity
ex: position = your_clicked_position
MyModal clicked_modal_object = (MyModal) list.get(your_clicked_position);
//now pass this clicked_modal_object to next activity
You can use two variables.(I'm sure this is what #Gautam mentioned) The first is the full description and the second is the shorter description.
String description = object.getString("overview"); // full
String shortDesc = description.length() > 64 ? description.substring(0,64)+"...":description; // add this to listView
Log.d("movie description ", shortDesc);
I want to get the real description, in the DetailActivity
(setOnItemClickListener)
When button clicked, get the description string instead
i.putExtra("desk", description);
Note: Make sure you set description as globally.

Android intent bundle pass string

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

Categories