I am trying to pass EditText from Activity1 to Activity2.
Activity1 code:
public void openNextActivity()
{
Intent intent = new Intent("com.abc.xyz.ImageActivity");
EditText myEditText = (EditText)findViewById(R.id.myEditText);
int myEditTextId = myEditText.getId();
//For Test purpose ----- starts
// **Point1: next line of code works fine in this Activity1**
EditText myEditTextTest = (EditText)findViewById(myEditTextId);
//For Test purpose ----- ends
intent.putExtra("myEditText", myEditTextId);
startActivity(intent);
}
Activity2 code:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.comments_detail);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
int myEditTextId = extras.getInt("myEditText");
// Point2: next line of code displays the correct Id
Log.d("tag","myEditTextId"+ myEditTextId);
// Point 3: Next line of code not works in this Activity2
EditText myEditText = (EditText)findViewById(myEditTextId);
if(myEditText != null)
{
Log.d("tag","Not null");
}
else
{
Log.d("tag","null");// **Point4: this condition executes**
}
}
}
The problem is that the line : EditText myEditText = (EditText)findViewById(myEditTextId); works fine in Activity1 but its not working in Activity2.
EDIT:
Note: Both activities are using different layouts
Thanks for your valuable time & help.
The only views you have accessible to you are those in the layout you loaded at the start of Activity 2, i.e those in R.layout.comments_detail. I'm guessing that Activity 1 loads a different layout with its setContentView(..) and it's in that layout where 'myEditText is defined and in scope.
You can't pass a view as an extra. You can pass the string in the view (if that's your purpose).
It seems like you're trying to get the EditText id before it's been assigned:
int myEditTextId = myEditText.getId();
EditText myEditText = (EditText)findViewById(myEditTextId); **// Point1: Works fine**
Try this instead:
EditText myEditText = (EditText)findViewById(myEditTextId); **// Point1: Works fine**
int myEditTextId = myEditText.getId();
Edit
Does the EditText in question even exist in the set layout? (R.layout.comments_detail)
This can not be done.
If your attempt is to manipulate activity 1 from activity 2 then you should be returning something to activity 1 from activity 2. By passing the ID of view you made in activity 1 to activity 2 shouldn't resolve to anything due to nothing being created in activity 2. findViewById is invoked on the current activity. As you didn't set anything in the view there is nothing for it to find.
I think it can work if you use the same layout R.layout.comments_detail in Activity1 and Activity2 because findViewById() return the unique id and this id only belong layout comments_detail
Related
I have a MainActivity, which contains ImageView, TextView and 3 clickable Buttons.
After clicking the button, I want to change something in SQlite dtb and according that load different data, but show it again in the same activity.
public void ClickBtn(View v)
{
//insertData(String...
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
So generally - in Main Activity.js I am getting the data from ID, which was clicked before and show that data. The MainActivity should be used infinity times to show different data.
The layout will be always the same - ImageView, TextView and 3 clickable Buttons, just the text will be different.
The question is, how can I only change content inside the same Activity?
I don't think Intent intent = new Intent(MainActivity.this, MainActivity.class); from the current activity can open the same activity...
You really need to study the basics.
When you are working in android, XML layout files are merely blueprints which ultimately are parsed into a reflection-created anonymous view instance, which contains as children each of the members of the XML layout, with the valid XML tag parameters applied to them. Therefore, you aren't dealing with 'Layouts', but with java/kotlin objects, which can be:
Referenced
Mutated
Replaced
So, if you want to change the contents, the first steps is to keep a reference to each object: ImageView, TextView and Buttons, and move the code in charge of filling them to a new method, so you can call it either when loading the activity (onCreate), or when clicking the button. That way the same activity can perform the same action over and over.
Finally, constant recreation of an activity is a TERRIBLE idea. For every object you generate (and an activity IS an object, like everything else), you need X+Y memory, where X is the sum of all the members of the object's class, and Y is the sum of all the operations necessary for instantiation, so by recreating the activity constantly, you waste the device resources, with the added problem of generating a huge backstack of identical activities.
Take a look at a java book, then a kotlin one. It will make your life easier.
This is how I solved it. Just replacing text without refreshing activity. Tested it hundred times also via Memory monitoring and absolutely no impact on device memory.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get from dtb
int room = 1; int a1 = 2; int a2 = 3; int a3 =4;
TextView views = findViewById(R.id.text1);
views.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//get from dtb - img, text where room = a1;
TextView vv = findViewById(R.id.textof);
vv.setText("text from dtb");
}
});
TextView view2 = findViewById(R.id.text2);
view2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//get from dtb - img, text where room = a2;
TextView vv = findViewById(R.id.textof);
vv.setText("another text from dtb");
}
});
}
How can I update the editText field with a button when the button and the editText are on different layouts and classes?
I have a mainActivity class and layout but I wand to add this function to an intent (by clicking the save button update main_activity layout). I tried by calling the saveDegrees method onClick in the intent class but that didn't work.
After that I want to go back to the main_activity layout. My saveDegrees code is this:
public void saveDegrees(View view) {
LayoutInflater inflater = getLayoutInflater();
View activityView = inflater.inflate(R.layout.activity_main, null);
mCompassEditText = (EditText) activityView.findViewById(
R.id.compass_edit_text);
mCompassEditText.setText(toString().valueOf(currentDegree));
}
You cannot access an activity from another activity. Instead, you should send the data back to the first activity. You can do this by starting the second activity with startActivityForResult() rather than startActivity(). The second activity sets the result before finishing. The first activity receives the result in onActivityResult() and changes its own views. See How to manage `startActivityForResult` on Android? for more details.
I have two Activities. Activity 1 is designed to take in user input (EditText), and has a button that (if clicked) will go to activity 2. In activity 2, there is a LinearLayout and a button that will take you back to activity 1. I can currently add one textView (containing the user input from activity 1) to the LinearLayout in activity 2, but I would like to add several textView objects to the LinearLayout. When I try to add user input any time after the first, it simply replaces the textView object that held the information from the user input that was entered the first time.
From Activity 1 (AddExercise):
public class AddExercise extends AppCompatActivity {
private EditText name;
private EditText weight;
private EditText sets;
private EditText reps;
private String deets;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_exercise);
Button button = (Button) findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToAddWorkout();
}
});
}
private void goToAddWorkout() {
Intent intent = new Intent(this, AddWorkout.class);
name = (EditText) findViewById(R.id.name);
weight = (EditText) findViewById(R.id.weight);
sets = (EditText) findViewById(R.id.sets);
reps = (EditText) findViewById(R.id.reps);
deets = name.getText().toString() + "\n\t\tWeight: " + weight.getText().toString() + "\n\t\tSets: " + sets.getText().toString() + "\n\t\tReps: " + reps.getText().toString();
intent.putExtra("details", deets);
startActivity(intent);
}
}
From Activity 2 (AddWorkout):
public class AddWorkout extends AppCompactActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
LinearLayout vBox = (LinearLayout) findViewById(R.id.vBox);
Bundle extras = getIntent().getExtras();
if (extras != null) {
TextView tv = new TextView(this);
tv.setText(extras.getString("details").toString());
vBox.addView(tv);
}
Button button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToAddExercise();
}
});
}
}
You can try a public static List of String each time you can add your text to list and then On your second activity create text-view as per your list count. And add to your linear-layout.
For more click here....
So you want to be able to add multiple entries in your second activity, for every time you add one in the first. I would recommend a different and easier approach.
In your second activity, use a listview/recyclerview, instead of adding new textview. This has the added advantage that once you have added enough entries, scrolling won't be an issue.
Maintain a global list of entries, which you add the entries to. And populate the listview using this list.
you should try something like that as said by roshan-
((ArrayAdapter)listView.getAdapter()).insert(data_object, index);
((ArrayAdapter)listView.getAdapter()).notifyDataSetChanged();
use a shared preference for index... every time you come to second activity increment the index... on exit of app just clear the shared pref index variable.
Also you can add textview in your each list view item
There can be several ways to do it according to me, pick the one that suits your relevant application.
have a single activity and host two fragments. So you can share the data between the fragments using single activity. (Recommended way, I guess Fragments will ease the job for you.). Also you can store a local variable in Activity so that each time you start your application you can start it afresh, if its intended!
If not, you can use SharedPreferences. For each button click, add a string to the preference. When you add one more click, append the new data with a separator like ("|", "||").. So in Activity one write to the preference, in activity 2 read from the preference and display it as list view of dynamically create the linear layout and append it to the root layout.
Declare a static ArrayList in your Activity 1 and access it in activity 2. (Really bad way)
I'm currently working in an Activity which saves text from three EditViews and constructs a SQL query. After that, the query is given to another activity to search and display the results.
Right now I've got two buttons, one to save the query, inside an onClickListener and another button to start the second activity:
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//First the data from the editviews is saved
EditText searchName = (EditText) findViewById(com.pedro.books.R.id.search_name);
search_name = searchName.getText().toString();
searchName.setText("");
EditText searchAut = (EditText) findViewById(com.pedro.books.R.id.search_aut);
search_aut = searchAut.getText().toString();
searchAut.setText("");
EditText searchYea = (EditText) findViewById(com.pedro.books.R.id.search_yea);
search_yea = searchYea.getText().toString();
searchYea.setText("");
//here i construct the query
});
And with an onClick in the xml code, I start the activity with another button:
public void ReadResults(View view){
//The query is given to the ReadActivity to display the results
Intent intent = new Intent(this, ReadActivity.class);
intent.putExtra(ReadActivity.EXTRA_QUERY, query);
startActivity(intent);
}
I've tried with the same button for both without changing anything and it obviously doesn't work, and I've also tried to start the activity inside the onClickListener, but I got this error: "The constructor Intent(new View.OnClickListener(){}, Class) is undefined"
Is there a way to start the activity inside the onClickListener or to stop the second activity to start until the query is saved?
Thanks in advance!!
if you are putting the intent in the onClick of a button you cannot use this you need to use YourActivity.this to properly get context.
this in your button is your OnClickListener like the error says
Where/How do you call your ReadResults method? On a side note - does it need to be public? If you call it inside the clickListener handler then that's wrong.
1) Extract your code out of the clickListener handler and have it into a private method within your activity class.
2) Your clickListener should only call that private method.
3) You could have your 3 editboxes as memebers of your activity and instantiate them onCreate() instead of getting them each time you click the button, it's expensive parsing the UI if not necessary.
I am passing a value for username in one activity through XML. I want to recall the value in the next screen, like, 'Hello/Welcome, '. How is it possible using GetExtra and PutExtra?
Pls. find the below code, which I have tried for the same.
For storing the value of username in one activity:
Intent myActivity2 = new Intent(this,Activity1.class);
myActivity2.putExtra("nickname", R.id.mynickname3);
startActivity(myActivity2);
For recalling the value in other activity:
Bundle extras = getIntent().getExtras();
String val = extras.getString("nickname");
TextView tv=new TextView(this);
tv.setText(val);
If you want to reuse a username, use sharedPreference.
It is not a good idea to pass a userName to another activity then use that.Field like userName may need to use again and again.
In the first activity, you are passing in an integer value (R.id.mynickname3). Instead you need to give it a String. Use this instead:
myActivity2.putExtra("nickname", getString(R.id.mynickname3));
As a side note, you are trying to get a Bundle unnecessarily. Try this:
String val = getIntent().getStringExtra("nickname");
TextView tv = new TextView(this);
if (val != null)
{
tv.setText(val);
}
You're nearly right.
It is not enough to just pass the id of the EditText. You have to use below code -
((EditText)findViewById(R.id.mynickname3)).getText().toString();
int putExtra. Everything else should be fine.
UPDATE: Don't forget to set your TextView as contentView in OnCreate via:
setContentView(..)
Just a silly mistake in your code:
myActivity2.putExtra("nickname", R.id.mynickname3);
Where you have written ID of the EditText (nickname), instead it should be as a:
txtNickName = (EditText) findViewById (R.id.mynickname3);
myActivity2.putExtra("nickname", txtNickName.getText().toString());