Get intent value Using getIntent() in MVVM repository - android

I am giving the first steps in MVVM, I have a imbd app using retrofit.
At this moment I have a dynamic URL that change the list of movies by passing a different movie id
#GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(#Path("movie_id") int movieId);
I have a Repository where I am trying to get the Intent values but the .getIntent doesn't work, the Intent is in the recyclerview passing the ID of the movie clicked
public class DetailsMovieRepository {
private List<ResultSimilar> similarMoviesList;
private MutableLiveData<List<ResultSimilar>> mutableLiveData = new MutableLiveData<>();
public MutableLiveData<List<ResultSimilar>> getSimilarMutableliveData() {
MovieDataService movieDataService = RetrofitInstance.getRetrofitInstance();
Intent intent = getIntent(); // DONT WORK!
int movieId = intent.getIntExtra("movie_id",0);
Call<Similar> call = movieDataService.getAllSimilarMovies(movieId);
call.enqueue(new Callback<Similar>() {
#Override
public void onResponse(Call<Similar> call, Response<Similar> response) {
Similar similar = response.body();
if (similar != null && similar.getResults() != null) {
similarMoviesList = similar.getResults();
mutableLiveData.setValue(similarMoviesList);
}
}
#Override
public void onFailure(Call<Similar> call, Throwable t) {
Log.e("onFailed", " ******" + t.getMessage() + "*******");
}
});
return mutableLiveData;
}
}
The question is how can I get the value from the Intent save as a var and pass here
Call<Similar> call = movieDataService.getAllSimilarMovies(---MY INTENT VALUE---);
Starting Intent in Adapter
private SimilarViewHolder(#NonNull View itemView) {
super(itemView);
movieNameTv = itemView.findViewById(R.id.name_movie_tv);
movieRatingTv = itemView.findViewById(R.id.rating_movie_tv);
moviePosterIV = itemView.findViewById(R.id.movie_poster_iv);
movieDateTv = itemView.findViewById(R.id.date_movie_tv);
movieVotesTv = itemView.findViewById(R.id.votes_movie_tv);
movieOriginalTitleTv = itemView.findViewById(R.id.original_title_tv);
movieLanguageTv = itemView.findViewById(R.id.language_movie_tv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
ResultSimilar selectedMovie = similarMoviesList.get(position);
Intent intent = new Intent(context, DetailsActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("movie_id",selectedMovie.getId());
intent.putExtras(bundle);
context.startActivity(intent);
Log.e("ddddd" , "***" + selectedMovie.getId());
}});
}
}
Data service
public interface MovieDataService {
String api_key = "5bbf68dcf3b4ad3875ef7b2ed5ddfe1a";
#GET("3/movie/now_playing?api_key="+api_key+"&language=en-US&page=1")
Call<Movies> getAllMovies();
#GET("3/movie/{movie_id}}?api_key="+api_key+"&language=en-US")
Call<MovieResponse> getMovieDetails(#Path("movie_id") int movieId) ;
#GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(#Path("movie_id") int movieId);
}
Thank you!

If you want to get data from Intent then you should do it in your Activity class, then you can pass it to you repository from the constructor for example detailsMovieRepository(int id);

Related

Android intent data return null

I am starter at Android and now I want to transfer data using intent from one activity to another.
First activity will collect datas and give it to second. but on second the data returns null. So have some errors on there. Here are my code.
public void previewStack(final Context context, final CreateStackNewActivity createStackNewActivity, final Stack stackDetails) {
Map<String, String> options = new HashMap<String, String>();
if(stackDetails.getStackId() != -1){
options.put("stack_id", String.valueOf(stackDetails.getStackId()));
}
int index = 1;
for(StackLineNew stackLine : stackDetails.getLines()){
options.put("title" + index, stackLine.getTitle());
options.put("line_type" + index, Integer.toString(stackLine.getLineType().intValue));
options.put("title" + index, stackLine.getTitle());
if (stackLine.getBody().indexOf("file:/") == -1 && stackLine.getBody().indexOf("content:") == -1) {
options.put("description" + index, stackLine.getBody());
if (stackLine.getLineId() != -1) {
options.put("line_id" + index, Integer.toString(stackLine.getLineId()));
}
}
index++;
}
Call<GenericAPIResponse> call = Hype4DAPI.previewStack(stackDetails.getName(), stackDetails.getCategory(), Integer.toString(stackDetails.getLines().size()), options, "");
call.enqueue(new Callback<GenericAPIResponse>() {
#Override
public void onResponse(Call<GenericAPIResponse> call, Response<GenericAPIResponse> response) {
if(response.isSuccessful()) {
GenericAPIResponse saveStackResponse = response.body();
System.out.println(saveStackResponse);
Toast.makeText(context, saveStackResponse.toString(), Toast.LENGTH_SHORT).show();
createStackNewActivity.saveInProgress = false;
createStackNewActivity.somethingHasChanged = false;
createStackNewActivity.updatePostButtonState();
Intent itnt = new Intent(createStackNewActivity, StackDetailsPage.class);
itnt.putExtra("stackId", stackDetails.getStackId());
itnt.putExtra("isPreview", "true");
itnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
createStackNewActivity.startActivity(itnt);
} else {
System.out.println(response.errorBody());
Toast.makeText(context, response.errorBody().toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<GenericAPIResponse> call, Throwable t) {
t.printStackTrace();
}
});
}
And the code of second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stack_details);
final Intent intent = getIntent();
final String stackId;
if (intent != null) { //Null Checking
stackId = intent.getStringExtra("stackId");
isPreview = intent.getStringExtra("isPreview");
stackTitleStr = intent.getStringExtra("stackTitle");
saveLine = (HashMap<String, Object>)intent.getSerializableExtra("saveLine");
}
else{
stackId = null;
}
On second activity, I have all variables are null. isPreview, stackTitleStr, saveLine are all null.
So anyone please help me quickly.
first you should not create the intent in the onResponse callBack method but create a static method in your StackDetailsPage activity that return the intent it needs. With that, this activity "said" to the other ones whats it needs, and it avoid duplicate string extra keys. use this :
//in StackDetailsPage activity
public static Intent getIntent(Context context, String stackId, String...)
{
Intent intent = new Intent(context, StackDetailsPage.class);
intent.putExtra("stackId", stackId);
...
return intent;
}
and then in onResponse method do that :
startActivity(StackDetailsPage.getIntent(context,stackDetails.getStackId(), ...))

How to Pass Array Object to another activity?

I am looking for some help with a tutorial I have been working on. I am trying to pass an object when I click on a list item from one activity to another using an Intent. I have posted some of the tutorial code I have been using below but can't seem to get it to work.
My Main Activity code is below:
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_HEROES_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i =0; i<array.length(); i++){
JSONObject obj = array.getJSONObject(i);
Hero hero = obj.getString("name"));
heroList.add(hero);
}
adapter = new HeroAdapter(heroList, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And from my Adapter this is the code I have been using this:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Hero hero = heroList.get(position);
holder.textViewName.setText(hero.getName());
holder.textViewName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_ID, hero.getName());
context.startActivity(intent);
}
});
}
The intent is listed but it is not carrying the data into my new activity. I just want to take
hero.getName()
at the position it was clicked on in the itemlist and open up a new activity, and in the new activity set it to a TextView. This is part of code I have used on the new activity, but it wont post anything into the TextView.
TextView textViewName
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hero_detail);
textViewname = (textView) findViewById(R.id.textView);
Intent intent = getIntent();
if(intent == null)
return;
int id = intent.getIntExtra(HeroAdapter.KEY_HERO_ID, -1);
err.setText(id);
For instance I click on spiderman set in the list which is at position 3, and in the new activity the textView will load with Spiderman listed. Any help would be appreciated.
You can pass objects using serializable or parcelable interfaces but if you just want the name of your hero you should pass it as string in your intent. Now you're passing an id. You can totally do that. If it's int you should set it correctly to textview
err.setText(String.valueOf(id));
That's why it's not working now.
Or just pass it as string right from the beginning
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_NAME, hero.getName());
context.startActivity(intent);
And then retrieve it
Intent intent = getIntent();
if(intent == null)
return;
String heroName = intent.getStingExtra(HeroAdapter.KEY_HERO_NAME);
err.setText(heroName);
Try with this:
int id = -1;
if(getIntent().hasExtra(HeroAdapter.KEY_HERO_ID)){
id = getIntent().getExtras().getInt(HeroAdapter.KEY_HERO_ID);
}
err.setText("" + id);
If you need send the hero name then:
In your adapter:
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_ID, hero.getName());
context.startActivity(intent);
In your activity:
String heroName = "";
if(getIntent().hasExtra(HeroAdapter.KEY_HERO_ID)){
heroName = getIntent().getExtras().getString(HeroAdapter.KEY_HERO_ID);
}
err.setText(heroName);

Service and interface

In my project i user Firebase Database. With it i read data frmo db the following way:
public void getSoftwareRecords() {
final List<Software> softwareList = new ArrayList<>();
databaseReference = firebaseDatabase.getReference("software");
getSoftwareRecordsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
softwareList.add(snapshot.getValue(Software.class));
}
Log.d(TAG, "Software from server count: " + softwareList.size());
onSoftwareTransactionListener.onSuccessSyncListOfSoftware(softwareList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Cant read software list from database: " + databaseError.getDetails());
// TODO describe error #102 for documentation
onSoftwareTransactionListener.onFailureSyncListOfSoftware("Ohh.");
}
};
databaseReference.addValueEventListener(getSoftwareRecordsListener);
After, this method i want to call in IntentService. As u notice, there is no return value = void. So, the question is how i can user service and interface together?
Service (as i wanted to use it):
public class ReadSoftwareListService extends IntentService implements Database.OnSoftwareTransactionListener {
private static final String TAG = ReadSoftwareListService.class.getSimpleName();
public static final String ACTION = "...";
public static final String RESULT_CODE = "RESULT_CODE";
public static final String RESULT_VALUE = "RESULT_VALUE";
private Intent in;
public ReadSoftwareListService() {
super("ReadSoftwareListService");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
in = new Intent(ACTION);
Log.d(TAG, "ReadSoftwareListService:: onHandleIntent");
Database database = new Database(com.google.firebase.database.FirebaseDatabase.getInstance());
database.getSoftwareRecords(); // <- this is a method from code above.
}
#Override
public void onSuccessSyncListOfSoftware(List<Software> softwareList) {
Log.d(TAG, "ReadSoftwareListService:: onSuccessSyncListOfSoftware");
Bundle bundle = new Bundle();
bundle.putInt(RESULT_CODE, Activity.RESULT_OK);
in.putExtras(bundle);
// bundle.putSerializable(RESULT_VALUE, softwareList);
LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
#Override
public void onFailureSyncListOfSoftware(String message) {
Log.d(TAG, "ReadSoftwareListService:: onFailureSyncListOfSoftware");
Bundle bundle = new Bundle();
bundle.putInt(RESULT_CODE, Activity.RESULT_CANCELED);
bundle.putString(RESULT_VALUE, message);
in.putExtras(bundle);
LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
And reciever:
public final BroadcastReceiver softwareListReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "softwareListReceiver:: onReceive");
Bundle bundle = intent.getExtras();
int resultCode = bundle.getInt(RESULT_CODE);
if (resultCode == Activity.RESULT_OK) {
Log.d(TAG, "RESULT CODE == OK");
// softwareListAdapter.updateData(bundle.getParcelableArrayList(RESULT_VALUE));
} else {
Log.d(TAG, "RESULT CODE == CANCEL: " + bundle.getString(RESULT_VALUE));
}
}
};
If you really wanted to use IntentService here, you can go add ResultReceiver as a callback. Example:-
Intent intentService = new Intent(context, YourIntentService.class);
intentService.putExtra(StockService.REQUEST_RECEIVER_EXTRA, new ResultReceiver(null) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == StockService.RESULT_ID_QUOTE) {
...
}
}
});
startService(intentService);
Alternatively you can use Custom AsyncTask by passing interface as one of parameters.
Hope this helps.
Note: Vote up if you like this.

Get an object result from an activity in Xamarin with Visual Studio

I want to receive an object back from a child activity in Xamarin with Visual Studio 2015:
[Serializable]
class MyObj
{
public string value { get; }
public MyObj(string v)
{
value = v;
}
}
Child Activity
Intent myIntent = new Intent (this, typeof(FirstActivity));
MyObj obj = new MyObj("message");
myIntent.PutExtra ("obj", obj); // cannot convert "obj" to Bundle
SetResult (Result.Ok, myIntent);
Finish();
FirstActivity
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 0)
if (resultCode == Result.Ok) {
var helloLabel = FindViewById<TextView> (Resource.Id.helloLabel);
MyObj obj = data.GetSerializableExtra("obj") as MyObj;
helloLabel.Text = obj.Text.ToString();
}
}
}
This code causes an error cannot convert obj to Bundle. I've also tried to implement Java.IO.ISerializable is MyObj but I couldn't get a right implementation. It always throws System.NotSupportedException: Unable to activate instance of type MyApp.MyObj from native handle 0x10001d (key_handle 0x1a027cb)
class Object1 : Java.Lang.Object, Java.IO.ISerializable
{
public string value { get; }
public Object1(string v)
{
value = v;
}
}
I would like to get some advice. I'm new in Xamarin and I'm working with Visual Studio 2015
I'd always go for Parcelable. It's very fast! (10x faster) http://www.developerphil.com/parcelable-vs-serializable/
Here is how you implement it in Xamarin:
public class MyObj : Java.Lang.Object, IParcelable
{
public string Value { get; set; }
public MyObj()
{
}
private MyObj(Parcel parcel)
{
// read your values in order
Value = parcel.ReadString();
}
public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
// read your values in order
dest.WriteString(Value);
}
// -- stuff below here is needed from the parcel interfaces/mechanism --
[ExportField("CREATOR")]
public static MyObjCreator InitializeCreator()
{
return new MyObjCreator();
}
public class MyObjCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
return new MyObj(source);
}
public Java.Lang.Object[] NewArray(int size)
{
return new MyObj[size];
}
}
public int DescribeContents()
{
return 0;
}
}
SetResult
Intent myIntent = new Intent(this, typeof(FirstActivity));
MyObj obj = new MyObj {Value = "Hello"};
myIntent.PutExtra("obj", obj);
SetResult(Result.Ok, myIntent);
Finish();
OnActivityResult
var x = (MyObj)data.GetParcelableExtra("obj");
Passing complex objects is a bit tricky. You can use libraries like Json.Net to serialize to string before sending, and then deserialize on the other end.
myIntent.PutExtra ("obj", JsonConvert.SerializeObject(obj));
//in your receiving activity OnActivityResult...
var objectAsString = intent.GetStringExtra("obj")
var result = JsonConvert.DeserializeObject<MyObject>(objectAsString)
Nice and easy solution and well performing too..

How to pass ArrayList of Objects from one to another activity using Intent in android?

I have the following in code in my onClick() method as
List<Question> mQuestionsList = QuestionBank.getQuestions();
Now I have the intent after this line, as follows :
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putParcelableArrayListExtra("QuestionsExtra", (ArrayList<? extends Parcelable>) mQuestionsList);
startActivity(resultIntent);
I don't know how to pass this question lists in the intent from one activity to another activity
My Question class
public class Question {
private int[] operands;
private int[] choices;
private int userAnswerIndex;
public Question(int[] operands, int[] choices) {
this.operands = operands;
this.choices = choices;
this.userAnswerIndex = -1;
}
public int[] getChoices() {
return choices;
}
public void setChoices(int[] choices) {
this.choices = choices;
}
public int[] getOperands() {
return operands;
}
public void setOperands(int[] operands) {
this.operands = operands;
}
public int getUserAnswerIndex() {
return userAnswerIndex;
}
public void setUserAnswerIndex(int userAnswerIndex) {
this.userAnswerIndex = userAnswerIndex;
}
public int getAnswer() {
int answer = 0;
for (int operand : operands) {
answer += operand;
}
return answer;
}
public boolean isCorrect() {
return getAnswer() == choices[this.userAnswerIndex];
}
public boolean hasAnswered() {
return userAnswerIndex != -1;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// Question
builder.append("Question: ");
for(int operand : operands) {
builder.append(String.format("%d ", operand));
}
builder.append(System.getProperty("line.separator"));
// Choices
int answer = getAnswer();
for (int choice : choices) {
if (choice == answer) {
builder.append(String.format("%d (A) ", choice));
} else {
builder.append(String.format("%d ", choice));
}
}
return builder.toString();
}
}
Between Activity: Worked for me
ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);
In the Transfer.class
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");
Hope this help's someone.
Using Parcelable to pass data between Activity
This usually works when you have created DataModel
e.g. Suppose we have a json of type
{
"bird": [{
"id": 1,
"name": "Chicken"
}, {
"id": 2,
"name": "Eagle"
}]
}
Here bird is a List and it contains two elements so
we will create the models using jsonschema2pojo
Now we have the model class Name BirdModel and Bird
BirdModel consist of List of Bird
and Bird contains name and id
Go to the bird class and add interface "implements Parcelable"
add implemets method in android studio by Alt+Enter
Note: A dialog box will appear saying Add implements method
press Enter
The add Parcelable implementation by pressing the Alt + Enter
Note: A dialog box will appear saying Add Parcelable implementation
and Enter again
Now to pass it to the intent.
List<Bird> birds = birdModel.getBird();
Intent intent = new Intent(Current.this, Transfer.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Birds", birds);
intent.putExtras(bundle);
startActivity(intent);
And on Transfer Activity onCreate
List<Bird> challenge = this.getIntent().getExtras().getParcelableArrayList("Birds");
Thanks
If there is any problem please let me know.
Steps:
Implements your object class to serializable
public class Question implements Serializable`
Put this in your Source Activity
ArrayList<Question> mQuestionList = new ArrayList<Question>;
mQuestionsList = QuestionBank.getQuestions();
mQuestionList.add(new Question(ops1, choices1));
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("QuestionListExtra", mQuestionList);
Put this in your Target Activity
ArrayList<Question> questions = new ArrayList<Question>();
questions = (ArrayList<Questions>) getIntent().getSerializableExtra("QuestionListExtra");
It works well,
public class Question implements Serializable {
private int[] operands;
private int[] choices;
private int userAnswerIndex;
public Question(int[] operands, int[] choices) {
this.operands = operands;
this.choices = choices;
this.userAnswerIndex = -1;
}
public int[] getChoices() {
return choices;
}
public void setChoices(int[] choices) {
this.choices = choices;
}
public int[] getOperands() {
return operands;
}
public void setOperands(int[] operands) {
this.operands = operands;
}
public int getUserAnswerIndex() {
return userAnswerIndex;
}
public void setUserAnswerIndex(int userAnswerIndex) {
this.userAnswerIndex = userAnswerIndex;
}
public int getAnswer() {
int answer = 0;
for (int operand : operands) {
answer += operand;
}
return answer;
}
public boolean isCorrect() {
return getAnswer() == choices[this.userAnswerIndex];
}
public boolean hasAnswered() {
return userAnswerIndex != -1;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// Question
builder.append("Question: ");
for(int operand : operands) {
builder.append(String.format("%d ", operand));
}
builder.append(System.getProperty("line.separator"));
// Choices
int answer = getAnswer();
for (int choice : choices) {
if (choice == answer) {
builder.append(String.format("%d (A) ", choice));
} else {
builder.append(String.format("%d ", choice));
}
}
return builder.toString();
}
}
In your Source Activity, use this :
List<Question> mQuestionList = new ArrayList<Question>;
mQuestionsList = QuestionBank.getQuestions();
mQuestionList.add(new Question(ops1, choices1));
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("QuestionListExtra", ArrayList<Question>mQuestionList);
In your Target Activity, use this :
List<Question> questions = new ArrayList<Question>();
questions = (ArrayList<Question>)getIntent().getSerializableExtra("QuestionListExtra");
Your bean or pojo class should implements parcelable interface.
For example:
public class BeanClass implements Parcelable{
String name;
int age;
String sex;
public BeanClass(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
#Override
public BeanClass createFromParcel(Parcel in) {
return new BeanClass(in);
}
#Override
public BeanClass[] newArray(int size) {
return new BeanClass[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
dest.writeString(sex);
}
}
Consider a scenario that you want to send the arraylist of beanclass type from Activity1 to Activity2.
Use the following code
Activity1:
ArrayList<BeanClass> list=new ArrayList<BeanClass>();
private ArrayList<BeanClass> getList() {
for(int i=0;i<5;i++) {
list.add(new BeanClass("xyz", 25, "M"));
}
return list;
}
private void gotoNextActivity() {
Intent intent=new Intent(this,Activity2.class);
/* Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)list);
intent.putExtra("BUNDLE",args);*/
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("StudentDetails", list);
intent.putExtras(bundle);
startActivity(intent);
}
Activity2:
ArrayList<BeanClass> listFromActivity1=new ArrayList<>();
listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");
if (listFromActivity1 != null) {
Log.d("listis",""+listFromActivity1.toString());
}
I think this basic to understand the concept.
Pass your object via Parcelable.
And here is a good tutorial to get you started.
First Question should implements Parcelable like this and add the those lines:
public class Question implements Parcelable{
public Question(Parcel in) {
// put your data using = in.readString();
this.operands = in.readString();;
this.choices = in.readString();;
this.userAnswerIndex = in.readString();;
}
public Question() {
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(operands);
dest.writeString(choices);
dest.writeString(userAnswerIndex);
}
public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {
#Override
public Question[] newArray(int size) {
return new Question[size];
}
#Override
public Question createFromParcel(Parcel source) {
return new Question(source);
}
};
}
Then pass your data like this:
Question question = new Question();
// put your data
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra("QuestionsExtra", question);
startActivity(resultIntent);
And get your data like this:
Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
question = extras.getParcelable("QuestionsExtra");
}
This will do!
The easiest way to pass ArrayList using intent
Add this line in dependencies block build.gradle.
implementation 'com.google.code.gson:gson:2.2.4'
pass arraylist
ArrayList<String> listPrivate = new ArrayList<>();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("private_list", new Gson().toJson(listPrivate));
startActivity(intent);
retrieve list in another activity
ArrayList<String> listPrivate = new ArrayList<>();
Type type = new TypeToken<List<String>>() {
}.getType();
listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
You can use object also instead of String in type
Works for me..
Simple as that !! worked for me
From activity
Intent intent = new Intent(Viewhirings.this, Informaall.class);
intent.putStringArrayListExtra("list",nselectedfromadapter);
startActivity(intent);
TO activity
Bundle bundle = getIntent().getExtras();
nselectedfromadapter= bundle.getStringArrayList("list");
If your class Question contains only primitives, Serializeble or String fields you can implement him Serializable. ArrayList is implement Serializable, that's why you can put it like Bundle.putSerializable(key, value) and send it to another Activity.
IMHO, Parcelable - it's very long way.
I do one of two things in this scenario
Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)
Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.
Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.
You must need to also implement Parcelable interface and must add writeToParcel method to your Questions class with Parcel argument in Constructor in addition to Serializable. otherwise app will crash.
Your arrayList:
ArrayList<String> yourArray = new ArrayList<>();
Write this code from where you want intent:
Intent newIntent = new Intent(this, NextActivity.class);
newIntent.putExtra("name",yourArray);
startActivity(newIntent);
In Next Activity:
ArrayList<String> myArray = new ArrayList<>();
Write this code in onCreate:
myArray =(ArrayList<String>)getIntent().getSerializableExtra("name");
To set the data in kotlin
val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)
To get the data
val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?
Now access the arraylist
Implements Parcelable and send arraylist as putParcelableArrayListExtra and get it from next activity getParcelableArrayListExtra
example:
Implement parcelable on your custom class -(Alt +enter) Implement its methods
public class Model implements Parcelable {
private String Id;
public Model() {
}
protected Model(Parcel in) {
Id= in.readString();
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
#Override
public ModelcreateFromParcel(Parcel in) {
return new Model(in);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Id);
}
}
Pass class object from activity 1
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putParcelableArrayListExtra("model", modelArrayList);
startActivity(intent);
Get extra from Activity2
if (getIntent().hasExtra("model")) {
Intent intent = getIntent();
cartArrayList = intent.getParcelableArrayListExtra("model");
}
Your intent creation seems correct if your Question implements Parcelable.
In the next activity you can retrieve your list of questions like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
}
}
You can pass the arraylist from one activity to another by using bundle with intent.
Use the code below
This is the shortest and most suitable way to pass arraylist
bundle.putStringArrayList("keyword",arraylist);
I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.
ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
Question question = questionList.get(i);
intent.putExtra("question" + i, question);
}
startActivity(intent);
And now in Second Activity
ArrayList<Question> questionList = new ArrayList<>();
Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
Question model = (Question) intent.getSerializableExtra("question" + i);
questionList.add(model);
i++;
}
Note:
implements Serializable in your Question class.
You can use parcelable for object passing which is more efficient than Serializable .
Kindly refer the link which i am share contains complete parcelable sample.
Click download ParcelableSample.zip
You can Pass Arraylist/Pojo using bundle like this ,
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
intent.putExtra("BUNDLE",args);
startActivity(intent);
Get those values in SecondActivity like this
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");
You can try this. I think it will help you.
Don't fotget to Initialize value into ArrayList
ArrayList<String> imageList = new ArrayList<>();
Send data using intent.putStringArrayListExtra()....
Intent intent = new Intent(this, NextActivity.class);
intent.putStringArrayListExtra("IMAGE_LIST", imageList);
startActivity(intent);
Receive data using intent.getStringArrayListExtra()...
ArrayList<String> imageList = new ArrayList<>();
Intent intent = getIntent();
imageList = intent.getStringArrayListExtra("IMAGE_LIST");
As we know getSerializable() is deprecated so we can use other easy way to transfer array between activities or between fragment to activities:
First initialize Array of Cars:
private var carsList = ArrayList<Cars>()
On sending Activity/Fragment side:
val intent = Intent(mContext, SearchActivity::class.java)
intent.putExtra("cars_list", Gson().toJson(carsList))
startActivity(intent)
On Receiving Activity:
val type: Type = object : TypeToken<List<CarsModel?>?>() {}.type
categoryList = Gson().fromJson(intent.getStringExtra("cars_list"), type)
I had the exact same question and while still hassling with the Parcelable, I found out that the static variables are not such a bad idea for the task.
You can simply create a
public static ArrayList<Parliament> myObjects = ..
and use it from elsewhere via MyRefActivity.myObjects
I was not sure about what public static variables imply in the context of an application with activities. If you also have doubts about either this or on performance aspects of this approach, refer to:
What's the best way to share data between activities?
Using static variables in Android
Cheers.

Categories

Resources