I want to pass the string to another activity - java

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

Related

How to pass an object to a new activity in android studio?

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.

Transferring data from the third activity to the first

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.

How to pass an edittext string from an activity to a method in another activity?

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"

Why is the bundle always null in spite of key being present?

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

Using getExtra() - NullPointerException

I have a Fragment with the onItemClick-method in which I call another Activity and pass id parameter:
public class MoviesListFragment extends Fragment {
// some code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView mid = (TextView) view.findViewById(R.id.textID);
Intent intent = new Intent(getActivity().getBaseContext(), InfoActivity.class);
intent.putExtra("id", mid.getText());
startActivity(intent);
}
});
}
So, in another activity (InfoActivity.java) I'm trying to get id-value:
public class InfoActivity extends Activity {
Intent intent = getIntent();
private final String id = intent.getStringExtra("id");
// some code
and get an exception on this line: intent.getStringExtra("id");
Where I made a mistake?
This code:
Intent intent = getIntent();
private final String id = intent.getStringExtra("id");
Should be called from inside the onCreate() or similar method, otherwise it is called when the Activity object is created, before the intent is passed to it.
private final String id;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
Intent intent = getIntent();
id = intent.getStringExtra("id");
}

Categories