I am attempting to pass an object from one activity to another. I have tried using just intent and how with bundle but I am not sure what is wrong. I have looked at similar solutions here and that is where I got most of my code for this, but it seems that my copy and paste does not work.
This is my main class
public class MainActivity extends AppCompatActivity {
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNewItem();
Button buttonOne = findViewById(R.id.itemButton);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ViewItemDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("item", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
void createNewItem(){
item=new Item("Pixel 4","https://google.com",1000.00);
}
}
This is the activity I am trying to go to:
public class ViewItemDetails extends AppCompatActivity {
Intent intent= getIntent();
Bundle bundle= intent.getExtras();
Item item = (Item) bundle.getSerializable("item");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_item_details);
setStrings();
setButtons();
}
void setStrings() {
try {
TextView nameTextView = findViewById(R.id.itemNameid);
nameTextView.setText(item.getItemName());
TextView itemInitTV = findViewById(R.id.initalPriceNumID);
itemInitTV.setText(Double.toString(item.getInitPrice()));
TextView itemCurrTV = findViewById(R.id.currentPriceNumid);
itemCurrTV.setText(Double.toString(item.getCurrentPrice()));
}catch (NullPointerException e){
//do noting
}
}
void setButtons(){
Button buyButton = findViewById(R.id.buyButtonid);
buyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri uriUrl = Uri.parse(item.getWebaddress());
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
});
Button refreshButton= findViewById(R.id.refrechId);
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Double newPrice= new GenerateNewPrice().GenerateNewPrice(item.getWebaddress());
Toast toast = Toast.makeText(getApplicationContext(),Double.toString(newPrice), Toast.LENGTH_SHORT);
toast.show();
}
});
Button editButton= findViewById(R.id.editid);
editButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast toast = Toast.makeText(getApplicationContext(),"Attempt to edit", Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
This is the object I am attempting to pass between activities.
public class Item implements Serializable {
String itemName, webaddress;
Double initPrice, CurrentPrice;
public Item(String itemName, String webaddress, Double initPrice) {
this.itemName = itemName;
this.webaddress = webaddress;
this.initPrice = initPrice;
}
public String getItemName() {
return itemName;
}
public String getWebaddress() {
return webaddress;
}
public Double getInitPrice() {
return initPrice;
}
public Double getCurrentPrice() {
return CurrentPrice;
}
}
When I run the app on my phone I click the button and then the app closes.
Thank you for your help. If needed I can add more code. I have seen similar questions here, but they have not worked for me. I got similar code from those posts but have not solved my solution.
I appreciate any feedback that is give.
Thank you for your time.
For now and for future help on SOF, remember, Error logs are always helpful in that kind of scenario.
Though, Here are some points..
You should follow the Activity lifecycle rule, Getting the data in onCreate() will be a good idea.
You should use Parcelable instead of Serializable. It is much more efficient.
your initialisation of bundle and item is wrong in the ViewItemDetails.java activity. Try to initialise inside the onCreate method and let us know..
Seems like you have some bug, it should work, you can check out one of the project work example
//creating the budle
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//String selectedItem = (String) adapterView.getItemAtPosition(i);
//getting dat from text view and converting to string
// String textview =((TextView)view.findViewById(R.id.textViewName)).getText().toString();
//Toast.makeText(DriverInfo.this,"Driver id "+driver_id,Toast.LENGTH_SHORT).show();
Bundle bundle=new Bundle();
bundle.putString("DriverID",driver_id);
bundle.putString("Route",loc_src);
bundle.putString("Dest",loc_dest);
bundle.putString("location_address",location_address);
Toast.makeText(DriverInfo.this, "Driver ID="+driver_id, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(DriverInfo.this, DirverCurrentLoc.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
//Getting the bundle data
String lat, lng, realtime,src,dest;
location_address=intent.getStringExtra("location_address");
driver_id=intent.getStringExtra("DriverID");
src=intent.getStringExtra("Route");
dest=intent.getStringExtra("Dest");
You have to initialize this code in onCreate() method like below :
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_item_details);
Intent intent= getIntent();
Bundle bundle= intent.getExtras();
item = (Item) bundle.getSerializable("item");
setStrings();
setButtons();
}
You can use GSON to convert your Object into a JSON format
Intent intent = new Intent(this, ProjectActivity.class);
intent.putExtra("item", new Gson().toJson(item));
startActivity(intent);
then in your second activity, make sure you initialize the bundle correctly in onCreate() lifecycle.
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
.........
Bundle extras = getIntent().getExtras();
if (extras != null) {
item = new Gson().fromJson(extras.getString("item"), Item.class);
}
Note: I read this in an article that google recommends GSON when passing objects on bundle.
Related
I'm kind of new to android. I want to get an int value id(id of dynamically generated buttons) from class MainPage into class Note when a button is clicked. but the value of id always turns to zero in Note class.
here's the summerized code:
MainPage class:
public class MainPage extends AppCompatActivity {
public int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int j=0; j<allnotes.size(); j++) {
//generating buutons
final Button preview_text = new Button(this);
preview_text.setId(j)
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id=v.getId();
startActivity(new Intent(MainPage.this, Note.class));
}
});
}
}
}
Notes class:
public class Note extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
MainPage obj=new MainPage();
int id=obj.id
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout,Integer.toString(id) , 10000);
mySnackbar.show();
}
in snackbar message, id is always zero.
You need to add the id to the Intent you use to start the Note activity. You do this by using Intent.putExtra(...) and in Note you retrieve it via getIntent().getIntExtra(...)
Here I implemented #Riccully Answer in your code.
MainPage.java
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id = v.getId();
Intent intent = new Intent(MainPage.this, Note.class);
intent.putExtra("id_value", id);
startActivity(intent);
}
});
Note.java
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
int id = getIntent().getIntExtra("id_value", 0);
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout, Integer.toString(id), 10000);
mySnackbar.show();
}
we can do this via intent Because Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services, etc.
In Our case, we can send the v.getId() to Note.java, viaputExtra
intent.putExtra("view_id",v.getId());
and receive the value in Note.java by using
getIntent().getIntExtra("view_id", 0);
From the first activity I would like to go to the second, then from the second to the third. In the third activity I would like to enter the name in EditText, then after pressing the button, go to the first activity and at the same time send the information entered in the third activity.
Unfortunately, after pressing the button in the third activity, instead of returning to the first activity, I return to the second activity. Was the first activity killed? What could I do to ensure that the information is correct for the first activity? This is my code:
First:
public class MainActivity extends AppCompatActivity {
TextView textViewInformation;
Button button_GoToSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewInformation = findViewById(R.id.textView);
button_GoToSecond = findViewById(R.id.button);
button_GoToSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Second.class);
startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
String name = i.getStringExtra("name");
textViewInformation.setText(name);
}
}
}
Second:
public class Second extends AppCompatActivity {
Button button_GoToThird;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
button_GoToThird = findViewById(R.id.button2);
button_GoToThird.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Second.this, Third.class);
startActivity(i);
}
});
}
}
Third:
public class Third extends AppCompatActivity {
EditText editText_Data;
Button button_SendData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
editText_Data = findViewById(R.id.editText);
button_SendData = findViewById(R.id.button3);
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
just remove finish(); thats it
The reason that it goes to the second activity is because of this:
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish(); //This kills the current activity.
}
You should do:
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", name);
startActivityForResult(i, RESULT_OK, bundle);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
Bundle bundle = i.getExtras();
String name = bundle.getString("name");
textViewInformation.setText(name);
}
}
When you call finish, it just kills the current activity. If you want to go back to the first activity, just start a new activity for the first activity and pass the data in a Bundle.
If you want to have more of a stack concept, you can use Fragments.
I have 2 EditTexts and I want to copy the String of these EditTexts and use them in a method in another activity.
I was making an app which types some details in two EditTexts and have a button which copies the String of these two EditTexts and paste or use it in a RecyclerView in another Activity.
I tried the Intent and Bundle medthods but could not solve it and actually it was hard to arrange the structure of codes.
This is the activity I want to pass from:
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etTitle.length() != 0 || etDes.length() != 0){
addData();
}else {
Toast.makeText(DataInput.this, "Please Add Data !", Toast.LENGTH_SHORT).show();
}
}
});
}
private void addData() {
String titled = etTitle.getText().toString();
String desed = etDes.getText().toString();
Intent inte = new Intent();
Bundle bund = new Bundle();
bund.putString("title", titled);
bund.putString("des", desed);
inte.putExtras(bund);
startActivity(inte);
}
This is the activity I want to receive with:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), DataInput.class);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.rv);
dAdapter = new DataAdapter(dataList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(dAdapter);
}
public void sendData() {
Bundle bundle = getIntent().getExtras();
String addedTitle = bundle.getString("title");
String addedDes = bundle.getString("dec");
Data data = new Data(addedTitle, addedDes);
dataList.add(data);
dAdapter.notifyDataSetChanged();
}
All I want is to pass the intent and bundle from addData method in the first Activity to the sendData method in the second Activity, so I can use the Strings to pass them in Data constructor.
Use bundle or intent.
// From activity1 to activity2
Intent intent = new Intent(Activity1.this, Activity2.class);
Bundle bundle = new Bundle();
bundle.putString(<key>, <value>);
intent.putExtras(bundle);
startActivity(intent);
// in activity 2 onCreate
Bundle bundle = intent.getExtras();
if (bundle != null) {
// get the value from bundle based on key
}
Here is the short example pass data from activity to activity
I would recommend you to change your implementation in following way so that we can avoid key mismatch issue accidently.
#Override
public void onClick(View v) {
if (etTitle.length() != 0 || etDes.length() != 0){
String title = etTitle.getText().toString();
String description = etDes.getText().toString();
Activity2.launch(this,title,description);
} else {
Toast.makeText(DataInput.this, "Please Add Data !", Toast.LENGTH_SHORT).show();
}
}
In calling activity you may create helper method say launch like below.
public static final String KEY_TITLE = "title";
public static final String KEY_DESCRIPTION = "description";
public static void launch(Context context, String title, String description) {
Intent intent = new Intent(context, Activity2.class);
Bundle data = new Bundle();
data.putString(KEY_TITLE, title);
data.putString(KEY_DESCRIPTION, description);
intent.putExtras(data);
context.startActivity(intent);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = intent.getExtras();
if (bundle != null) {
String title = bundle.getString(KEY_TITLE);
String description = bundle.getString(KEY_DESCRIPTION);
}
}
To retrieve the text from an EditText you can use editText.getText().toString()
To retrieve the text from an EditText use
String value = editText.getText().toString();
And then pass the key value pair either through intent or bundle
Intent in = new Intent(Activity1.this, Activity2.class);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.putExtra("key", value);
startActivity(in);
to receive put this in new activity
String string_name = getIntent().getExtras().getString("key");
Update:
There is key mismatch, you are sending key as "des" and receiving as "dec"
The code below is intended to pass the data, using bundle, collected on signing up in Signup.java to ViewProfile.java which displays the data. On checking for a key in the bundle, it returns true, however, the bundle is null when checked in ViewProfile.java. Help will b appreciated.
Signup.java
public class Signup extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
final EditText n=(EditText)findViewById(R.id.editText3);
final EditText u=(EditText)findViewById(R.id.editText4);
final EditText p=(EditText)findViewById(R.id.editText5);
final EditText c=(EditText)findViewById(R.id.editText6);
Button s=(Button)findViewById(R.id.button4);
final Userdatabase udb=new Userdatabase(this);
s.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String name=n.getText().toString();
String email=u.getText().toString();
String password=p.getText().toString();
String phone=c.getText().toString();
boolean b=udb.insertuser(name,email,password);
if(b==true) {
Intent i = new Intent(Signup.this, MainActivity.class);
Bundle bundle=new Bundle();
bundle.putString("NAME",name);
bundle.putString("ID",email);
bundle.putString("PHONE",phone);
i.putExtras(bundle);
startActivity(i);
}
else
Toast.makeText(getApplicationContext(),"Please try again",Toast.LENGTH_SHORT).show();
}
});
}
}
ViewProfile.java
public class ViewProfile extends AppCompatActivity {
String name,username,contact,profession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
Intent intent=getIntent();
Bundle b=intent.getExtras();
if(b!=null) {
name = b.getString("NAME");
username = b.getString("ID");
contact = b.getString("PHONE");
TextView tv1=(TextView)findViewById(R.id.textView17);
TextView tv2=(TextView)findViewById(R.id.textView18);
TextView tv3=(TextView)findViewById(R.id.textView19);
tv1.setText(name);
tv2.setText(username);
tv3.setText(contact);
}
ImageView img=(ImageView)findViewById(R.id.imageView4);
img.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(ViewProfile.this,Profile.class);
startActivity(i);
}
});
}
}
You are calling the wrong activity in the SignUp activity:
if(b==true) {
Intent i = new Intent(Signup.this, MainActivity.class);//problem here
You have set the intent as MainActivity.class and sending data to MainActivity and not to ViewProfile activity.
Change to this in SignUp activity:
if(b==true) {
Intent i = new Intent(Signup.this, ViewProfile.class);
I want to pass a string to another activity through click on the Listview, but it says I have something wrong.The purpose is to modify the data change when the user wants just to change some words and then update to the data.
Here is the data structure.
https://ppt.cc/f02tWx
It says : https://ppt.cc/f8ZYKx
This is the listview on click part
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
hom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
adapter.getItem(position);
String title = dataSnapshot.child(String.valueOf(position)).getValue().toString();
Intent intent = new Intent(MeTodolist.this, MeTodolistModify.class);
Bundle bundle = new Bundle();
bundle.putString("title", title);
intent.putExtras(bundle);
startActivity(intent);
Log.e("CHANGE",title);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
This is the modifying page.
public class MeTodolistModify extends AppCompatActivity implements View.OnClickListener {
private String student_id,student_name,title;
private EditText addtext;
private Button sure;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_me_todolist_modify);
Intent intent = getIntent();
Bundle bundle = getIntent().getExtras();
String title = bundle.getString("title");
student_id = intent.getStringExtra("student_id");
student_name = intent.getStringExtra("student_name");
createDetail();
}
private void createDetail(){
final FirebaseDatabase db = FirebaseDatabase.getInstance();
final DatabaseReference ref = db.getReference("Student").child(student_id).child("event");
sure = findViewById(R.id.sure);
sure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.sure:
intent = new Intent(MeTodolistModify.this, MeTodolist.class);
intent.putExtra("student_id", student_id );
intent.putExtra("student_name",student_name);
startActivity(intent);
break;
}
}
});
}
#Override
public void onClick(View v) {
}
}
You can achieve that by just few lines of code
Intent intent = new Intent(MeTodolist.this, MeTodolistModify.class);
String title = dataSnapshot.child(String.valueOf(position)).getValue().toString();
intent.putExtra("title", title);
startActivity(intent);
Log.e("CHANGE",title);
MeTodolistModify
String title = getIntent().getStringExtra("title");
Why are you passing Bundle with intent extra? just use one method.
Bundle bundle=new Bundle();
bundle.putString("title", title);
intent.putExtras(bundle);
startActivity(intent);
and from the receiver.
Intent intent = getIntent();
Bundle bundle = getIntent().getExtras();
if(bundle !=null)
String title = bundle.getString("title");
why you are receiving these student_id and student_name. you did not pass them.
student_id = intent.getStringExtra("student_id");
student_name = intent.getStringExtra("student_name");