I'm clumsy.
solution on my problem
origin activity
public void marcas(View view) {
ArrayList<Localizacion> object = new ArrayList<Localizacion>(localizaciones);
Intent intent = new Intent(getApplicationContext(), CompraVenta.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST", (Serializable) object);
intent.putExtra("BUNDLE", args);
startActivityForResult(intent, RESPUESTA_ACTIVIDAD);
}
destiny activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compra_venta);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Localizacion> object = (ArrayList<Localizacion>) args.getSerializable("ARRAYLIST");
loc = object;
enlaceInterfaz();
}
in the class Localizacion i'm implement Parceable.
my mistake was to want to use the arrays like I use them in the java class and that's not how it works.
thanks for all
Make your class as Parceable, and then you will be able to pass the list of objects of that class to another Activity.
class Localizacion implements Parceable {
}
Now to send data to another Activity.
intent.putParcelableArrayListExtra("array",object);
In receiving side
loc = getIntent().getParcelableArrayExtra("array");
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
In my application I am getting Null Pointer Exception when click on the up action. The navigation happening properly to parent activity. And it going to the onCreate method of the parent activity. It is expecting a value from intent and it coming as null. But not sure how to set an intent value on up action pressed. Any help appreciated.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
activity 1:
public class SignalListActivity extends AppCompatActivity {
public static final String EXTRA_CAT_ID = "sigcatid";
private DatabaseQuery dbQuery;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signal_list);
setTitle("Cat chat");
try {
Toolbar mToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(mToolbar);
if(getSupportActionBar() != null){
getSupportActionBar().setTitle("Signal List");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
dbQuery = new DatabaseQuery(SignalListActivity.this);
final String cat = (String) getIntent().getExtras().get(EXTRA_CAT_ID);
List<Signal> signals = dbQuery.getSignalsNew(cat);
//getting recycler view
RecyclerView signalRecycler =(RecyclerView)findViewById(R.id.signal_recycler);
//GridLayoutManager mGrid = new GridLayoutManager(this, 2);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
signalRecycler.setLayoutManager(layoutManager);
// signalRecycler.setHasFixedSize(true);
SignalAdapter mAdapter = new SignalAdapter(SignalListActivity.this, signals);
signalRecycler.setAdapter(mAdapter);
mAdapter.setListener(new SignalAdapter.Listener() {
#Override
public void onClick(long id) {
Intent intent = new Intent(getApplicationContext(),SignalActivity.class);
intent.putExtra(SignalActivity.EXTRA_SIG_ID, id);
intent.putExtra(EXTRA_CAT_ID, cat);
startActivity(intent);
}
/*public void onClick(int position) {
Intent intent = new Intent(this, SignalActi.class);
intent.putExtra(PizzaDetailActivity.EXTRA_PIZZA_ID, position);
getActivity().startActivity(intent);
}*/
});
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
.....
Activity 2
public class SignalActivity extends AppCompatActivity {
public static final String EXTRA_SIG_ID = "signalId";
private DatabaseQuery dbQuery;
private Context context;
private String cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signal);
dbQuery = new DatabaseQuery(SignalActivity.this);
Toolbar mToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(mToolbar);
cat = (String) getIntent().getExtras().get(EXTRA_CAT_ID);
if(getSupportActionBar() != null){
getSupportActionBar().setTitle("Signal Details");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
try {
Long signalId = (Long) getIntent().getExtras().get(EXTRA_SIG_ID);
Signal signal = dbQuery.getSignal(signalId);
TextView name = (TextView)findViewById(R.id.name);
name.setText(signal.getName());
//Populate the drink description
TextView description = (TextView)findViewById(R.id.description);
description.setText(signal.getDescription());
TextView teaser = (TextView)findViewById(R.id.teaser);
teaser.setText(signal.getTeaser());
//Populate the drink image
ImageView photo = (ImageView)findViewById(R.id.photo);
int photoId = getResourseId(this,signal.getImage(), "drawable",getPackageName());
photo.setImageResource(photoId);
photo.setContentDescription(signal.getName());
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
...
when clicking up button from activity 2 it is going to onCreate method of activity 1 and expecting the final String cat = (String) getIntent().getExtras().get(EXTRA_CAT_ID);
If you have 2 activities
Activity A
Activity B
Suppose you now in Activity B, when you press the back button, to navigate back to Activity A, your lifecycle in Activity A would enter onResume(), NOT onCreate() as your Activity A still in you back stack, it doesn't require to recreate the activity once again.
Hence you getting null values, as you are expecting onCreate() callback, which unfortunately won't happen.
To solve this problem we have 3 options:
1) Add a SharedViewModel for both activities, use a MutableLiveData in this ViewModel, add data in Activity B, and observe these data in Activity A.
2) Use Broadcast receiver or callback interface between 2 activities.
3) Start new Intent from Activity B to Activity A and receive the data in onCreate()
Change these two lines:
1)
getIntent().getStringExtra(EXTRA_CAT_ID);
instead of
getIntent().getExtras().get(EXTRA_CAT_ID);
2)
getIntent().getLongExtra(EXTRA_SIG_ID,0);
instead of
getIntent().getExtras().get(EXTRA_SIG_ID);
Because of getIntent().getExtras() is null
After seeing this question, it got me thinking. I can get a Intent in a Fragment by calling this inside onCreateView:
String Item = getActivity().getIntent().getExtras().getString("name");
the problem with this is that getActivity might return null, to counter that I can call:
if(getActivity() != null)
String Item = getActivity().getIntent().getExtras().getString("name");
}
this will work fine, but..
I was thinking of creating a static method in my Activity and then accessing the Intent in my fragment by calling that method, like this (In my Activity):
public class DemoActivity extends Activity{
static String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
//Getting the Intent from the previous Activity
name = getIntent().getStringExtra("name");
}
public static String Name(){
//returning the Intent
return name;
}
}
Then in my Fragment I can call this like this:
String name = DemoActivity.Name();
My Question:
Can I do it like this? Will it cause any issues and why?
Currently
It is working fine.
try like this:
Activity class:
Bundle bundle = new Bundle();
bundle.putString("your_key", "your_value");
your_fragment.setArguments(bundle);
Fragment class:
String your_variable = getArguments().getString("your_key");
Set in first activity fragment:
Bundle bundle = new Bundle();
bundle.putString("your_string_key", "your_value");
startActivity(new Intent(getActivity() your_second_activity.class).putExtra("bundle_key", bundle));
Get bundle value second activity:
fragment.setArguments(getIntent().getBundleExtra("bundle_key"));
In Second Activity Fragment:
getArguments().getString("your_string_key")
I want to send a string from a recyclerView of Activity1 to a fragment of Activity2 using intent. for better understanding, here is the demonstration image
so I'm fetching the key from recyclerView like this
#Override
protected void populateViewHolder(EventsViewHolder viewHolder, EventDetails model, int position) {
viewHolder.setEventDate(model.getDate());
viewHolder.setEventIcon(getApplicationContext(),model.getIcon());
viewHolder.setEventTitle(model.getTitle());
viewHolder.setEventDescription(model.getDescription());
viewHolder.setEventTotalGuest(model.getTotal_guests());
String guest_key = getRef(position).getKey();
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent guestListIntent = new Intent(MainActivity.this, GuestListActivity.class);
startActivity(guestListIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
and now I want to send the guestKey by using intent from this activity to a fragment of GuestListActivity.class
I've tried Bundle but I can't send data.
TIA
First, send data from activity1 to activity2
Intent guestListIntent = new Intent(MainActivity.this, GuestListActivity.class);
guestListIntent.putExtra("guest_key",guest_key)
startActivity(guestListIntent);
Catch it in Activity 2
String guest_key = "";
Bundle bundle = getIntent().getExtras();
if(bundle != null){
guest_key = bundle.getString("guest_key","");
}
Now send to Fragment of Activity 2
Bundle bundle = new Bundle();
bundle.putString("guest_key", guest_key);
NewFragment newFragment = new NewFragment();
newFragment.setArguments(bundle);
Catch in Fragment onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String guest_key = getArguments().getString("guest_key","");
return inflater.inflate(R.layout.fragment_item_three, container, false);
}
send the data as u send from activity to activity and receive in fragment as getActivity().getIntent() and then do as you receive data in activity.
Here, any fragment of Activity2 is being created after onCreate() of this activity.
I will suggest you to use any of two approach to receive data in a Fragment of Activity2.
Approach 1:
Send data using Bundle with intent and receive it in Activity2 then set as Arguments while making transition of a fragment.
Bundle bundle = new Bundle();
bundle.putString("YOUR_KEY", "KEY_VALUE");
guestListIntent.putExtras(bundle);
startActivity(guestListIntent);
Receive this data in Activity2,
Bundle extras = getIntent().getExtras();
Set data while Fragment transition,
Fragment frag = new YOUR_FRAGMENT();
frag.setArguments(extras);
Receive data in Fragment,
String value= getArguments().getString("YOUR_KEY");
Approach 2:
Declare static variable. Assign value inside onClick then access and use this value from fragment class
You have to send the data to GuestListActivity and retrive the data in GuestListActivity. After that when you do the fragment tracation or add the fragment pass the data through bundle. Then you will be able to get the data in your desire fragment. For better understanding see the demonstration image.
send data to GuestListActivity
#Override
protected void populateViewHolder(EventsViewHolder viewHolder, EventDetails model, int position) {
// other code of view holder
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent guestListIntent = new Intent(MainActivity.this, GuestListActivity.class);
guestListIntent.putExtra("guest_key",guest_key)
startActivity(guestListIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
}
Retrieve the data in GuestListActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
String guest_key = "";
Bundle bundle = getIntent().getExtras();
if(bundle != null){
guest_key = bundle.getString("guest_key","");
}
}
Send the data to your fragment
Bundle bundle = new Bundle();
bundle.putString("guest_key", guest_key);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
Retrieve data in your fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String guest_key = getArguments().getString("guest_key","");
}
I am new at using fragments. This is how I am passing StringArrayList inside bundle in the onActivityCreated of first fragment in sliding tab
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
next_personal = (Button) getActivity().findViewById(R.id.personal_next);
next_personal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validate();
}
});
}
private void validate() {
isValid = FormValidator.validate(this, new SimpleErrorPopupCallback(getActivity().getApplicationContext(), true));
if (isValid) {
arrayList = new ArrayList<String>();
arrayList.add(memID.getText().toString());
arrayList.add(idNumber.getText().toString());
arrayList.add(firstName.getText().toString());
arrayList.add(secondName.getText().toString());
arrayList.add(lastName.getText().toString());
arrayList.add(secondLastName.getText().toString());
Bundle bundle = new Bundle();
bundle.putStringArrayList("personal",arrayList);
Log.d("bundle",": "+bundle.toString());
FragContactInfo frag = new FragContactInfo();
frag.setArguments(bundle);
((RegisterTabActivity) getActivity()).setCurrentItem(1, true);
}
}
And then I am trying to get the ArrayList in the third fragment of sliding tab as below:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey("personal")) {
ArrayList<String> userId = bundle.getStringArrayList("personal");
}
else{
Toast.makeText(getActivity(),"Bundle is null",Toast.LENGTH_SHORT).show();
}
}
It keeps on returning null. Did the same inside onCreateView of both fragments, same result. What am I getting wrong here?
Using bundle did not help in parsing data between fragments (Somehow)
So I simply created method to set and get data in target fragment.
public void setPdata(JSONObject obj) {
this.personalJSON = obj;
}
public JSONObject getPdata() {
return personalJSON;
}
Then I called the set method to set json in sender fragment.
FragContactInfo frag = new FragContactInfo();
frag.setPdata(json);
And then access the json by simply calling get method.
array1 = getPdata().getJSONArray("args");
If anyone has a more productive solution, please do tell. Happy Coding.
Im still new to Android and got a huge problem...
I have a ListViewActivity class with a String[] array of shops around me. When the user clicks on any of these, I want the ListViewActivity to send the int index to another activity (InfoActivity). However, before starting the InfoActivity, the user is taken to the OptionsActivity and once they click on the button Info they're directed to the InfoActivity. That index will be used to access an item from another string[] array in this activity.
I have tried the following:
ListViewActivity:
Bundle newbundle = new Bundle();
newbundle.putInt("key", position);
Intent intent = new Intent(ListViewActivity.this, InfoActivity.class);
intent.putExtras(newbundle);
startActivity(intent);
startActivity(new Intent(ListViewActivity.this, OptionsActivity.class));
InfoActivity:
public class InfoActivity extends Activity{
String[] price1 = {"£46", "£44", "£45", "£43", "£47", "£45", "£48", "£42", "£46", "£43"};
int key;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Bundle bundle = getIntent().getExtras();
key = bundle.getInt("key", 0);
TextView price1 = (TextView)findViewById(R.id.hairprice11);
price1.setText(hair_stylists_price1[key]);
...
Any ideas??
Try this instead..
Intent intent = new Intent(ListViewActivity.this, InfoActivity.class);
intent.putExtra("key", position);
startActivity(i);
Then pull it out..
int index = getIntent().getIntExtra("key");