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");
}
Related
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.
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"
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");
I want the clicked item to be displayed in another activity.The second activity appears but the string doesn't. I tried other methods as well but the second activity just remains blank.
Here is the Main Activity
EditText TxtOne;
Button btOne;
ListView lisOne;
ArrayList aL;
ArrayAdapter<String> adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TxtOne = (EditText) findViewById(R.id.TxtOne);
btOne = (Button) findViewById(R.id.btOne);
lisOne = (ListView) findViewById(R.id.lisOne);
aL = new ArrayList<String>();
adapt = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aL);
lisOne.setAdapter(adapt);
onBClick();
lisOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent itemInfo = new Intent(MainActivity.this, secondActivity.class);
itemInfo.putExtra("Itemis",position);
startActivity(itemInfo);
}
});
}
public void onBClick(){
btOne.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String InpItem = TxtOne.getText().toString();
aL.add(InpItem);
adapt.notifyDataSetChanged();
}
});
}
The following is the second Activity
public class secondActivity extends AppCompatActivity {
TextView txt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle passedData = getIntent().getExtras();
txt2 = (TextView)findViewById(R.id.txt2);
txt2.setText(passedData.getString("Itemis"));
}
}
I have read other similar posts but none of them work.
Some talk about the textView not being in the active layout because of which the result is NULL. The textView is in the active layout but still it doesn't display the item.
Solution anyone??
In the below Listener, you are adding position to itemInfo Intent. Here position is of type int, So you should do getIntExtra() to retrieve the Integer data instead of getStringExtra()
lisOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent itemInfo = new Intent(MainActivity.this, secondActivity.class);
itemInfo.putExtra("Itemis",position); //position is INT value!!
startActivity(itemInfo);
}
});
So you should do -
getIntExtra(String name, int defaultValue); //this returns the int value of position.
Replace these two lines -
txt2 = (TextView)findViewById(R.id.txt2);
txt2.setText(Integer.toString(getIntent().getExtras().getIntExtra("Itemis",0))); //getting int value in second activity and converting into string for displaying
Note - you should use getStringExtra("Itemis") for retrieving string data from Intents. Not getString("Itemis").
Refer Intent Docs Page for further details on setting and retrieving values from intents.
You are passing and reading extras incorrectly. Do the following:
itemInfo.putExtra("Itemis", position);
and
txt2.setText(String.valueof(getIntent().getIntExtra("Itemis")));
I want to pass an data previous activity on click of Item in Recycler view and show it on a Edit Text.
This is the code i have used to pass data from listview to the previous activity
I want to do the same thing with Recyclerview
//Calling Second Activity
public static final int REQUEST_CODE = 100;
Intent dateintent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(dateintent, REQUEST_CODE);
//onClick of listview pass the data back to previous activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.textView);
String str = txt.getText().toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK,intent);
finish();
}
});
//After getting data show the data in the first activity edit box
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String data= data.getStringExtra("data");
if (data!= null) {
edittext.setText(data);
}
}
}
}
First create this Interface
public interface RunnableValue {
public void run(Object obj);
}
2.This MainActivity add
RunnableValue run=new RunnableValue() {
#Override
public Bundle run(Object obj) {
String str = obj.toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK,intent);
finish();
}
};
mAdapter = new SearchAdapter(dataSet,run);
This RecyclerView Adapter
public SearchAdapter(List<String> dataSet,RunnableValue runnableValue) {
mDataSet = dataSet;
this.runnableValue=runnableValue;
}
public static class SearchHolder extends RecyclerView.ViewHolder {
private final TextView textView;
public SearchHolder(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runnableValue.run(getTextView().toString());
}
});
textView = (TextView) v.findViewById(R.id.txtSearchItem);
}
public TextView getTextView() {
return textView;
}
}
Follow the Jacob's solution here. This adds listener for RecyclerView. Then, do the same as you have done in ListView.
There is no setOnItemClickListener available in RecyclerView, so you need make your own click listener in your RecyclerView adaper, just check out the post, then you should be able to make it.
Hope this help!
RecyclerView doesn't have a setOnItemClickListener like its predecessor ListView did. However, that shouldn't prevent us from doing what we want to do. So, we reinvent the wheel and make our very own OnItemClickListener for your RecyclerView. Here's a step by step guide.
Create an interface called OnItemClickListener by creating a new file called OnItemClickListener.java with an empty method called onItemClick.
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
Create a static variable in your adapter called
static OnItemClickListener mItemClickListener;
Setup onClickListener in your custom ViewHolder with a call to our onItemClick method like so
#Override
public void onClick(View view) {
mItemClickListener.onItemClick(view, getPosition());
}
Create a public method called SetOnItemClickListener in your adapter class
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener)
{
this.mItemClickListener = mItemClickListener;
}
SetOnItemClickListener on your custom RecyclerView Adapter
((NameOfYourAdapter) mAdapter).SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(view != null)
{
TextView txt = (TextView) view.findViewById(R.id.textView);
String str = txt.getText().toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK, intent);
//close this Activity...
finish();
}
}
});
That should do it. If you have any questions, feel free to ask!