android - replace only content in the same activity - android

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

Related

Made a method each for multiple Spinners - how to pass this data on to new activities?

This might sound a bit convoluted.
I have roughly 15 Spinners in one activity and made a distinct method for each of these spinners. I then initiate the methods in the onCreate method.
Method example:
//Relative Position Spinner
public void relativePositionSpinner() {
Spinner relativePositionSpinner = (Spinner) findViewById(R.id.spinner_relativePosition);
ArrayAdapter relativePositionAdapter = ArrayAdapter.createFromResource(this, R.array.relativePosition, R.layout.spinner_item);
relativePositionSpinner.setAdapter(relativePositionAdapter);
//what happens when selected
relativePositionSpinner.setOnItemSelectedListener(this);
}
OnCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_hand);
//initiate all Spinners
relativePositionSpinner();
absolutePositionSpinner();
etc.
Now what I want is to send the data of each Spinner to another Activity with the click of a Button. I know that I can do this with an intent and using putExtra in the Button method like this:
public void openHandSummary() {
//Find the Button that gives option to enter new hand
Button handInputButton = (Button) findViewById(R.id.hand_input_button);
//set a click listener on Hand Analyzer Button
handInputButton.setOnClickListener(new View.OnClickListener() {
//below code will be executed when the new Hand Button is clicked
#Override
public void onClick(View view) {
Intent handSummaryIntent = new Intent(NewHandActivity.this, HandSummaryActivity.class);
handSummaryIntent.putExtra("RelPosString", WHATTOENTERHERE??)
startActivity(handSummaryIntent);
}
});
}
However I do not know how to retrieve the value/variable out of my Spinners to put them into the Button/intent method? Because if I make a String in the Spinner method, then I can't access this in the Button method.
So I feel like I have too many methods? So is there a way to pass data from one method to another method, or do I have to cancel some methods? What would be the easiest way to set this up?
I also made an onItemSelected to make some toasts, which worked. Can I use OnItemSelected somehow to create variables or initiate a data transfer to another Activity?
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView myText = (TextView) view;
switch (parent.getId()) {
case R.id.spinner_relativePosition:
makeText(NewHandActivity.this, "Relative Position is " + myText.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.spinner_absolutePosition:
makeText(NewHandActivity.this, "Absolute Position is " + myText.getText(), Toast.LENGTH_SHORT).show();
break;
I'm very new to coding, and I just can't figure out the logic how I get the Spinner methods, Button/iniate method and OnItemSelected method to work together and exchange variables. Would appreciate if someone can point me in the right direction. Have already browsed the internet a day or so to find an answer, with no success.
I like your idea of separating out the code to create each spinner into its own method. However, if you are copying and pasting the whole method and making a few changes, you should step back and think about how you can do it even more easily. Often the changes you make after copy and paste give a hint that you should add some parameters to the method. If you do it correctly, you can write just a single method and then copy and paste the method call instead of the entire method and then make appropriate changes to the arguments.
As for your actual question, you are making this much more complicated than necessary. Specifically, you do not need to setOnItemSelectedListener() on any of the Spinners. Instead, the OnClickListener for the button should just get the selected item from each spinner and send it to the new activity in the Intent.

Android - Switch to an activity using Intent and then change TextView's text on the switched activity?

I have a three different activities all of whom switch to a common Activity via Intent, with only minor modifications in the appearance of the child or switched-to Activity. I want to change the text of the TextView, so that each time the child activity displays a different text based on which activity it was switched-to from.
I have tried using this:
Button startSendingLocation = (Button) findViewById(R.id.wmb_start_sending_button);
startSendingLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), ll_wmb_Map.class);
startActivity(intent);
TextView bmo_map_toolbar_title = (TextView) findViewById(R.id.wmb_toolbar_title);
bmo_map_toolbar_title.setText(R.string.ll_bmo_toolbar_title);
}
});
But this doesn't update the text in the TextView. Am I doing it wrong ?
Should I create three different Activities with their own layouts to achieve this ?
Will I be able to add or update a few views, differently, based on the activity I am switching from ?
I thought switching to the same activity via Intent will be a good idea for code-reusability and some efficiency gains as the child activity makes use of a MapFragment in all the three cases.
ll_wmb_Map.class : The common activity that is being switched to, using Intent
wmb_toolbar_title : The id of the TextView I want to change
ll_bmo_toolbar_title : The text I want to set in the TextView
Fine, If you just want to enable/disable the view and change the textview content, you just need to use enable and disable functionality within onclick listeners instead of calling the same activity again and again.
startSendingLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bmo_map_toolbar_title.setText(R.string.ll_bmo_toolbar_title);
//enable/disable the views
}
});

android- Appending textView objects to a LinearLayout by clicking on a button from a different page (multiple times)

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)

Activity not updating properly

I'm new to android, so maybe I'm doing something horribly wrong. I want to have a particular Activity that shows details about an instance of a "Creature" class for a game. Name, damage taken, that sort of thing.
I'm having a problem getting the creature data to be properly shown in the GUI objects. Both at initial creation (where it should copy the creature's name into the name field) and when a damage mark is added (where it doesn't update to show the proper image).
Here's my mini-example of what I have:
public class CreatureDetailActivity2 extends Activity
{
Creature creature;
public void addMark(View v)
{
// connected to the button via android:onClick="addMark" in the XML
creature.getTrack().addDamage(DamageType.Normal, 1);
refreshDisplay();
new AlertDialog.Builder(this).setTitle(creature.getName())
.setMessage(creature.getTrack().toString()).show();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creature_detail);
creature = new Creature("Example");
refreshDisplay();
}
public void refreshDisplay()
{
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
final EditText nameField = (EditText) (creatureDetailView
.findViewById(R.id.textbox_creature_name));
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) (creatureDetailView.findViewById(R.id.damageBox0));
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
}
Now the problem is that the app will load up and start, but then none of the widgets will update properly. You can click the button, and it'll show the AlertDialog, and the text of the AlertDialog will change, but the textfield in the activity won't be changed, and the ImageView doesn't change at any point from what it starts as to the one it's supposed to change to.
So I'm very stumped. I can post more about the project's setup if I'm leaving out something important, but I'm not even sure what the problem going on is so I'm not sure what else to include in my question.
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
Inflates your Activity's layout into basically nothing, just returning the View it inflated. setContentView is what actually inflates your layout into the Activity's View hierarchy.
Once you inflate your layout you don't need to do it again. Just use findViewById without the reference to a dangling unattached View.
Change your refreshDisplay method to this:
public void refreshDisplay()
{
final EditText nameField = (EditText) findViewById(R.id.textbox_creature_name);
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) findViewById(R.id.damageBox0);
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
Nothing changes because You do it completely wrong.
If You wish to update any view element of current activity You do it like this
View v = findViewById(R.id.element);
v.setText("text");
this is just simple example.
You would need to cast a returned element to correct type like to be able to access all available methods.
What You do wrong is trying to inflate a layout again.

Using dynamically created buttons in android to take user to another activity with dynamically generated content

I have a list of buttons in one of my activities that are dynamically generated, and I was wondering how i would get one of those buttons to, when clicked, open another activity and display text based on which button in the list was clicked.
I generate the buttons using a for loop (I've ommited details relating to TextViews in the loop for easier reading, it also used some variables defined elsewhere)
for (int i = 0; i < N; i++) {
// create a new Button
final Button rowButton = new Button(this);
// Set properties of rowButton
rowButton.setText("See Recipe");
rowButton.setId(RecipeArray.get(i));
// add the Button to the LinearLayout
myLinearLayout.addView(rowButton);
// save a reference to the Button for later
myButtons[i] = rowButton;
}
The buttons represent a certain recipe and when clicked they should take the user to a new activity "HowToMake" and generate a textview with the information relating to that recipe only. They are stored in an array at the bottom of the code snippet "myButtons[i] = rowButton" But I'm not sure how I would use this.
Thanks for any help.
You'll have to add an onclicklistener to each button as you add it. Then in the onclick event, you can call the startActivity method of your current Activity. When you create your Intent which will open the new activity, you can add "extras" to it (in other words, you can add some extra data which will be passed into the new activity). New data, such as the ID of the recipe that you want to open :)
Example (Untested, but should be along the right lines):
rowButton.setTag("the unique ID by which you can read back your recipe");
rowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(YourActivity.this, TheViewRecipeClass.class);
intent.putExtra("id", v.getTag());
startActivity(intent);
}
}

Categories

Resources