How to send an object from imported package to another Activty - java

I've made an activity (A) that recovers a List<Event> from Google Calendar API in an AsyncTask, and then sends it from (A) to (B). The list isn't empty when putting it into the bundle:
bundle.putSerializable(KEY_EVENTS_LIST, (Serializable) items);
but it's null when I recover it in (B)
Bundle b = getIntent().getExtras();
eventList = (List<Event>) b.getSerializable(MainActivity.KEY_EVENTS_LIST);
I don't know which other way I could send it from (A) to (B), or if I could send the List directly to B from the AsyncTask.

You can send serialized array list (ArrayList) using intent from Activity A to Activity B
Intent intent = new Intent(context, B.class);
intent.putExtra("list", serializedArrayListObject);
activity.startActivity(intent);
In Activity B in onCreate method
ArrayList<Event> list=getIntent().getSerializableExtra("list");
to get list from intent

The WorkAround you can do to tackle this creates an Event Class in your project with all the attributes of Event(another package) class and make your Event class a paracalable.
Before setting list to bundle convert it to your list and pass this list.
This is not a good solution but up to my knowledge it will work perfectly.
Hope this will help you.

If you want to save the List in background while sending it to the other activity, you can use sharedPreferences for that as shown below:-
1) You cannot directly save an arrayList in SharedPreferences, so you need to convert it to a set first by:-
Set<String> set = new HashSet<String>();
set.addAll(Your_ArrayList);
2) Save it using sharedPreferences:-
SharedPreferences.Editor editor = getSharedPreferences(MY_PREF_STRING, MODE_PRIVATE).edit();
editor.putStringSet("Key", set);
editor.apply();
where MY_PREF_STRING is declared globally as public static final String MY_PREF_STRING = "MY_PREF";
Retrieve this using
1) In another activity where you want to retrieve this just paste the code given below:-
SharedPreferences preferences = getSharedPreferences(MY_PREF, MODE_PRIVATE);
Set<String> set2 = new HashSet<String>();
set2 = preferences.getStringSet("Key", Collections.singleton("0"));
2) You can again convert this to arrayList using:-
ArrayList<String> array = new ArrayList<String>();
array.addAll(set2);

Related

using putExtra and hasExtra for send and fetch multiple values

I have a Recycleview of multiple movie's poster. I tried to click each poster to start a new activity with details of the movie, now I've tried to use the details of movie like date and name of movie to be shared in detail activity so I used this code in MainActivity:
#Override
public void onClick(String MovieName, String MovieDate) {
Context context = this;
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(context, destinationClass);
intentToStartDetailActivity.putExtra(Intent.EXTRA_TEXT, String.valueOf(MovieName));
intentToStartDetailActivity.putExtra(Intent.EXTRA_CC, String.valueOf(MovieDate));
startActivity(intentToStartDetailActivity);
}
and in DetailActivity:
mMovieName = (TextView) findViewById(R.id.tv_movie_Name);
mMovieDate = (TextView) findViewById(R.id.tv_movie_date);
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity != null) {
if (intentThatStartedThisActivity.hasExtra(Intent.EXTRA_TEXT )) {
movieName = intentThatStartedThisActivity.getStringExtra(Intent.EXTRA_TEXT);
mMovieName.setText(movieName);
}
if (intentThatStartedThisActivity.hasExtra(Intent.EXTRA_CC )) {
movieDate = intentThatStartedThisActivity.getStringExtra(Intent.EXTRA_CC);
mMovieDate.setText(movieDate);
}
}
It works fine and I get the information in detail activity but I used Intent.EXTRA_TEXT and Intent.EXTRA_CC and I need to use more. So, my question is can I rename the EXTRA_ with some other word that I choose? Cuz I saw it when I search different names for Extra but don't know how to create a new one like Extra_DESCRIPTION.
And the second question - is it true to use a new if condition with hasExtra() like I did to get information? can't I use only on if condition with hasExtra() to get all information? if so then how to do that?
ofcourse you can use any key you like.
for example
intent.putExtra("username", yourUsername);
intent.putExtra("password", yourPassword);
and it's a good practice to check intent.hasExtra(String key) to avoid null pointer exception.
or you can just directly check if intent has any extra budle by intent.hasExtras()

Passing multiple strings to a new activity and displaying them in a list view. Java, Android SDK

I have my 2 activities set up and linked.
What I'm trying to do:
Take a generated text view in my first activity, convert it to a string, pass it to my other activity, where is it displayed in a list view with other previous passed text views.
So in my first activity I currently have:
public void SaveMessage(View view) {
String saved = message.getText().toString();
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("message",message);
Toast.makeText(getApplicationContext(), R.string.addedfavs, Toast.LENGTH_SHORT).show();
}
However I don't really know where to go from this, I've looked at trying store the strings in arrays or then in array lists, but to no avail.
Help would be much appreciated on how to receive each string and store it in some sort of arraylist (as arrays are of fixed size) or any format that could consequently be displayed in a ListView.
However I don't really know where to go from this,
First of all you must start the intent activity:
context.startActivity(intent);
Then, when necessary, in FirstActivity or SecondActivity, get the intent that started your activity with:
Intent intent = getIntent();
Now, you have also the extras with that intent. As you have the extra data as Strings, use intent.getStringExtra(String name) method.
In your case:
String message = intent.getStringExtra("message");
I've looked at trying store the strings in arrays or then in array lists, but to no avail.
You have other extra methods like getStringArrayListExtra to pass ArrayList<> or getStringArrayExtra to pass Arrays
I could not properly understand your question, but according to my understanding, there are two solutions.
Solution 1:
If you want to save previously passed texts, you can do that using a db. Whenever you pass a string from your first activity to second one, store that text in db and get all the strings from db and populate those in list.
Or you can save it in arraylist and save the array list to SharedPreferences like:
public void addMessage(String message) {
if (currentMessages == null) {
currentMessages = new ArrayList<String>();
}
currentMessages.add(message);
//save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(MESSAGES, ObjectSerializer.serialize(currentMessages));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}
public ArrayList<String> getMessages() {
if (currentMessages == null) {
currentMessages= new ArrayList<String>();
}
// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
currentMessages = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString(MESSAGES, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
You can use this arraylist as a data source for your adapter.
Solution 2:
If there are multiple messages that are passed via intent, then use this:
ArrayList<String> messages = new ArrayList<String>();
messages.add(message1);
messages.add(message2);
.
.
.
messages.add(messageN);
Then use this arraylist as a data source for your adapter.
Edited:
SHARED_PREFS_FILE can be a static final String like:
public static final String SHARED_PREFS_FILE = "sharedPrefsFile";
(Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).)
You can get ObjectSerializer class from here and add it to your project.

Android - Design trouble - Should I use setTag to hold information for OnClick event?

I'm doing a small project as part of the Android course.
The app is supposed to retrieve the most popular movies using some site's API and then display them in a grid view (using posters as thumbnails).
When a specific movie is clicked a new activity will be started providing details.
I've gotten this far:
Obtained a list of most popular movies poster image URL's using the website's API.
Implemented an adapter extending ArrayAdapter which accepts ArrayList as the data source and loads the image from URL into ImageView item.
Populated the GridView using the adapter.
Setup listeners on Gridview using this code:
s:
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
//do stuff according to position/view
}
The info I need to pass onto the movie details activity when a movie is clicked can be obtained in step 1 (I just extracted the poster URLS from the json).
To be able to even provide information when a view is clicked I need to (at the very minimum) also extract the movie's ID and store it.
So as it seems my options are:
Store the IDs in the adapter. Then when a click occurs use getItem(position) to obtain the ID and send it with the intent. The next activity will then have to query the server for the movie details.
This means creating a class:
static class MovieItem {
int Id;
string posterUrl;
}
And converting the adapter to use ArrayList<MovieItem>.
Same as option 1 but instead use setTag to store the Id of the movie.
Same as option 1 but instead obtain all the required information (title, rating, plot, etc..) and store it to MovieItem. Query not required in the next activity.
Same as option 3 but instead use setTag (MovieItem). Query not required in the next activity.
I'm new to app development and I'm trying to get things done the right way, Would appreciate some help.
EDIT:
Also wanted to add, if I had stored additional movie information in the adapter would that not have been appropriate because the information isn't relevant to that class?
Thanks for your troubles! :)
When you first request the list of Movie info, you could store the details for each movie in something like a HashMap<String, HashMap<String, String>>, where the String is the movie id, and the Map is a set of Key/Value pairs for details information. Then, when a click comes through on your onClick, you would use the position to determine which movie poster was clicked. You would then retrieve the details HashMap for the selected movie, put it into a Bundle, pass it to the Intent of your new Activity, then retrieve it on the other side. So the code would look something like this:
When you first retrieve your list of movies, you would do something like this:
//You would put each set of movie data into a HashMap like this...
HashMap<String, HashMap<String, String>> movies = new HashMap<>();
HashMap<String, String> details = new HashMap<>();
details.put("dateReleased", "7.12.2015");
details.put("rating", "PG-13");
details.put("title", "Cool Awesome Movie");
movies.put("12345", details);
//Then when an onClick comes in, you would get the set of
//details for the movie that was selected (based on position)
HashMap<String, String> selectedDetails = movies.get("12345");
//Put the retrieved HashMap of details into a Bundle
Bundle bundle = new Bundle();
bundle.putSerializable("movieDetails", selectedDetails);
//Send the bundle over to the new Activity with the intent
Intent intent = new Intent(this, YourDetailsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
Then when the new Activity starts, you would retrieve the details from the Bundle in your onCreate():
//Then in onCreate() of the new Activity...
Bundle bundle = getIntent().getExtras();
HashMap<String, String> movieDetails = (HashMap<String, String>) bundle.getSerializable("movieDetails");
String dateReleased = movieDetails.get("dateReleased");
String rating = movieDetails.get("rating");
String title = movieDetails.get("title");

retrieving string from parse.com and displaying it in TextView Android

I have uploaded data onto parse.com and i am trying to retrieve the data from parse.com and display it in a textview.
i have a parseconstants class:
public static final String TYPE_STRING = "string";
public static final String KEY_FILE_TYPE = "fileType";
i send the message and it uploads to parse fine
String fileName = "text.txt";
String fileType = "text";
these 2 values are sent to parse.com as filename and filetype.
but when i get it back in inboxActivity here:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ParseObject message = mUserBio.get(position);
String messageType = message.getString(ParseConstants.KEY_FILE_TYPE);
ParseFile file = message.getParseFile(ParseConstants.KEY_FILE);
Uri fileUri = Uri.parse(file.getUrl());
if (messageType.equals(ParseConstants.TYPE_STRING)){
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
intent.setData(fileUri);
startActivity(intent);
}
it does not call on the text activity class and does not show the class.
in the TextViewController i try to display the text into the TextView like below:
mDisplay = (TextView)findViewById(R.id.bioDisplay);
Uri textUri = getIntent().getData();
File string = new File(textUri.toString());
mDisplay.setText((CharSequence) string);
1) Why does the ViewtextActivity not show?
2) will the textview display the retrieved user bio?
Firstly, try to avoid calling constants like this:
ParseConstants.KEY_FILE_TYPE
Completely!
Rather import your class statically:
import static <your_package_name>.ParseConstants.*;
//now you can access your constants by calling it on its own:
String messageType = message.getString(KEY_FILE_TYPE);
EDIT
Your naming standards are not up to standard (An instance of File, should be called something to do with a File, and not "string")!! You are trying to display an object of type File within a TextView which won't work. Rather try this, instead of letting Android Studio cast it to a CharSequence:
mDisplay.setText(string.toString());
Thirdly, when calling ViewTextActivity, there are 3 ways to do this (as I am not sure if you are using a Fragment or not):
//if you are using a Fragment:
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
//if you are using a FragmentActivity, you need to cast it:
Intent intent = new Intent((Your_Base_Activity) getActivity(), ViewTextActivity.class);
//if you are using a normal activity:
Intent intent = new Intent(Your_Activity_Name.this, ViewTextActivity.class);
As far as your TextView displaying data is concerned, your code does seem logically correct.
EDIT 2
From the ParseObject API, we see that getString will return the String value from that Key that is put in as the parameter (See Here).
According to you, you are checking if the return value is equal to the word "string". This doesn't make sense, as you are putting in the key value of "fileType".
My suggestion is check if the return is not null by using a log:
String messageType = message.getString(KEY_FILE_TYPE);
Log.e("MessageReturned: ", "Returned-" + messageType);
Or you can rethink, what the value that is supposed to equate to is supposed to be, as "string" doesn't make sense as far as I can see.
EDIT 3
Since you are saying that the value uploaded for the variable fileType is "text" should you not rather be doing this:
if (messageType.equals("text")){
EDIT 4
Your method of parsing information between the intents is obsolete. You need to try this:
if (messageType.equals(ParseConstants.TYPE_STRING)){
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
intent.putExtra("fileUri", fileUri.toString());
startActivity(intent);
}
Then in your other class, you access it like so:
Bundle extras = getIntent().getExtras();
Uri receivedFileUri = Uri.parse(extras.getString("fileUri"));

Pass data from listview to field in other class

I have a listview in a class that should pass data to another class however it seems I am doing it wrong. Class A contains the listview and through an intent it sends the data back. Class B must receive the data and pass to a field. For that I use a bundle which contain the string and must pass it. However it seems I am doing something wrong. Any hints?
Class A.
public static final String Item = "shop";
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item3 = (String)arrayAdapter.getItem(position).toString();
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
intent.putExtra(Item,item3);
startActivity(intent);
//Toast.makeText(getActivity().getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
}
});
Class B.
Bundle argsss = new Bundle();
argsss = getActivity().getIntent().getExtras();
if(argsss != null){
String shop = argsss.getString(ClassA.Item);
testButton.setText(shop);
}
Stacktrace :
Process: nl.boydroid.loyalty4g.app, PID: 27526
android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.boydroid.loyalty4g.app/nl.boydroid.loyalty4g.app.redeempoints.RedeemItemFragment}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1636)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1430)
at android.app.Activity.startActivityForResult(Activity.java:3532)
at android.app.Activity.startActivityForResult(Activity.java:3493)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.Fragment.startActivity(Fragment.java:880)
at nl.boydroid.loyalty4g.app.redeempoints.SearchableShopList$1.onItemClick(SearchableShopList.java:90)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1524)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3531)
at android.widget.AbsListView$3.run(AbsListView.java:4898)
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:5586)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
This should work:
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
Problem with your code it that you're binding String into Intent object directly and not into Bundle. This is reason why your code is not working. Your Bundle is empty.
you have sent data through the intent not bundle so get the data in other activity as intent
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
note: Im not that knowledgeable in android so i dont know about Bundle class nor Intent class just want to share some thoughts.
Try this.
String shop = argsss.getString("shop");
the value of the Item which is your key (shop) because of this.
public static final String Item = "shop";
look at this ,
//you are putting or passing the value of item3 to Item which is your key named "shop"
intent.putExtra(Item,item3);
so you can only get the value using the key you set.
Update
try this
// first create a bundle for you to be able to use it later.
Bundle sampleBundle = new Bundle();
// then set the values you want. with the Item key.
sampleBundle.putString(Item, item3);
// then create the intent
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
// then put your bundle to intent.
intent.putExtras(sampleBundle);
startActivity(intent);
to get this try this.
Bundle bundle = this.getIntent().getExtras();
if(bundle !=null){
//Obtain Bundle
String strdata = bundle.getString("shop");
//do the process
}
note again: i havent compile it i dont have ide for android its just a hint.
or
if you want to use only intent to pass some value
use your code above then on the other class you can get it by :
Intent intent = getIntent();
//this is how you retrieve the data
String shop = intent.getStringExtra("shop");
Additional ref.
Intent
Fragment to Fragment Try this dude. :)
Fragment to Fragment . Look at the last answer it may help you finding some ways on how fragments work.
Another possible solution
Passing data fragment to fragment
Additional info.
I think you cant pass data from fragment to another fragment directly.
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Based on Fragment Documentation.
Question.
//note: not sure about the flow of the program. just want to ask.
ClassA extends Activity ClassB extends Activity
|| ||
ClassA call the FragmentClassA? FragmentClassB startActivity(ClassB)?
|| ||
FragmentClassA you want to pass data --> ? FragmentClassB
after that, you want to start the ClassB Activity class inside FragmentClassB?
Bundle add the object as serializable and send it to another fragment.

Categories