I'm working on a project in Android Studio where I have one EditText where the user will insert one word at a time, 10 times. Everytime the user writes a new input and clicks on the button it goes to a different TextView than the previous ones and different from the next ones.
How can I put the different inputs into the specific (different) TextViews?
Every TextView has a different sequencial ID like, word1, word2, etc.
I haven't done java in a long time, so I'm having problems with logic. I tried to do the following but the app crashes.
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
printwords(gameword.getText().toString());
}
});
public void printwords(String word) {
String[] array = new String[10];
TextView[] positions = new TextView[10];
for (int i=0; i < 10; i++){
array[i] = word;
positions[i].setText(array[i]);
}
}
}
You're creating a new array of TextView's and String every time the button is clicked. Change your code to the code below and it should work.
Make your int[] textViews , String[] array & int i = 0 class variables and then initialize them in onCreate() after setContentView()
In above code, int[] textViews is the array of ID's of TextView's from your activity.
After doing that, change your code to following:
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
array[i] = gameword.getText().toString();
YourActivity.this.findViewById(textViews[i]).setText(array[i]);
i++;
}
});
Related
So, let's say I have an Array:
String Array[] = {"Dog goes woof", "Cat goes meow", "Cow goes moo", "Etc..."};
And I have a Button and a TextView connected so that when the button is pressed I can say for example:
public void onClick(View v) {
TextView.setText(Array[1]);
}
Which will then fill the TextView with "Cat goes meow". But I now want the button to decided what should fill the TextView based on what's already there. So let's say I have Array[0] displayed in the TextView, so that it says "Dog goes woof". I then want an if-test that recognizes that Array[0] is displayed, and then changes it to, say, Array[2]. And if Array[2] is displayed, it will then change it to Array[1], and so on.
I am having a bit of issues on how I should set up this if-test, and how I should phrase it so that it recognizes what it is I am looking for in the TextView. And I do want to look for Array[X] or Array[Y] and not the strings themselves like "Dog goes woof". Basically something that says (warning: poor seudo-code ahead):
if TextView contains Array[X]
then TextView.setText(Array[Y])
else if TextView contains Array[Y]
then TextView.setText(Array[Z])
else TextView.setText(Array[X])
I easily understood your requirement and here's what you need:
final Button yourButton= findViewById(R.id.yourButtonID);
final String Array[] = {"Dog goes woof", "Cat goes meow", "Cow goes moo", "Etc..."};
final TextView yourTextView = findViewById(R.id.yourTextViewID);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = 0;
if(textView.getText() == null)
{
textView.setText(Array[1]); // initial value
}
else{
for(int i=0;i<Array.length;i++){
if(Objects.equals(textView.getText(),Array[i])){
position=i; //got the selected position
break;
}
}
if(position<Array.length-1){
textView.setText(Array[position+1]);
}
else{
textView.setText(Array[position-1]);
}
}
}
});
This will check whether there is an initial value and in case of one then it will check for the selected position and if the position is less than the last item then it will increment one and if the last item is selected it will decrement one.
I've tested it and it's working, still something feel free to ask.
I am running this on an emulator: 5554:Nexus_5_API_22_x86.
I am trying to learn SharedPreferences and have written a simple test program.
It contains two buttons: one adds a String + random # to a set which will be stored in SharedPreferences, and the other prints the contents of that set.
Whenever I press the square button on the bottom right hand of the screen and press 'x' to close the app window, then relaunch the app, the contents of the set are reset - in other words, printing the set yields nothing.
However, if I exit the app using only the back button, the contents remain - in other words, printing the set yields whatever was in it before.
Java:
...
public class MainActivity extends AppCompatActivity
{
final int PREF_MODE_PRIVATE = 0;
TextView output;
Set<String> testSet;
Random randomGenerator = new Random();
SharedPreferences data;
SharedPreferences.Editor dataEditor;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output = (TextView) findViewById(R.id.textView); //getting the output textfield
data = getPreferences(PREF_MODE_PRIVATE);
//If first-time setup has not been completed, execute the following block
//I don't want the String Set to be reset to empty every time the app is launched
if(data.getBoolean("initialized", false) == false)
{
//Adding the empty set to storage
testSet = new HashSet<String>();
dataEditor = data.edit();
dataEditor.putStringSet("testSet", testSet); //Add the empty Set to storage
dataEditor.putBoolean("initialized", true); //Set initialized flag to true
dataEditor.apply();
}
}
public void printTestSet(View view)
{
output.setText(""); //Clears the text field
Set<String> toBePrinted = data.getStringSet("testSet", null); //Gets the String Set
//Prints content of the String Set
if(toBePrinted != null)
{
for(String word : toBePrinted)
{
output.append(word + '\n');
}
}
}
public void addToTestSet(View view)
{
//Generate a string followed by a random number and add it to the String Set
int randomInt = randomGenerator.nextInt(1000);
data.getStringSet("testSet", null).add("NEW STRING #" + randomInt);
}
}
The button that prints the String Set calls printTestSet and the one that adds a String to the Set calls addToTestSet.
Upon creation, the app uses a simple boolean to check if it has been initialized the for the first time. If not, it adds an empty String Set to storage and sets the boolean to true. If the boolean is already true (meaning it has already added the empty string set), that step is skipped.
You need to either commit your data either realtime (where you are doing apply) or in application life cycle handler onpause (when your app goes to background). Use option 1 when you have little data or 2 when you have large amount of data to commit.
It looks like you're not saving the shared preferences in addToTestSet.
When you do getStringSet and then add, you need to again save the string Set back into shared prefs like you do in your onCreate() using dataEditor.apply().
Or if you want to be a bit more efficient, you can save your stringSet in the activity's onPause() method to prevent constantly writing to SharedPrefs
When you hit back, your app process isn't being killed, which means when you open it up again the Android system is restoring whatever it can (what was written in textViews, checkboxes that were checked, etc. simple things like that). What you see in the box might not actually be getting populated by SharedPrefs.
Actually i want to make it Random class but then i think to much activity can make the app slow so i just want to make Relative layout Random
so i have 5 layout in one activity class
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
and in each layout there is the button in there to make layout random again
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//The code to how make layout random
}
});
}
and then how to make layout that already opened not open again if the button random was pressed? then if all layout was already opened it will open new activity class
can anyone help me explain with give some example code of that?
Initially set visibility gone to all relative layouts and put all of them into View's ArrayList.
Get random number from 0 to List size.
Get View at random position and set its visibility to Visible and remove from ArrayList.
Do same thing until ArrayList is empty.
Create new activity when ArrayList is empty.
Code:
ArrayList<View> viewList=new ArrayList<>();
initLayouts(){
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
viewList.add(layout1);
viewList.add(layout2);
viewList.add(layout3);
viewList.add(layout4);
viewList.add(layout5);
for(int i=0;i<viewList.size();i++){
viewList.get(i).setVisibility(View.GONE);
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
loadRandomLayout();
}
});
}
public loadRandomLayout(){
if(viewList.size()>0) {
Random r = new Random();
int number = r.nextInt(viewList.size());
viewList.get(number).setVisibility(View.VISIBLE);
viewList.remove(number);
}else{
startActivity(new Intent(this,NewActivity.class));
}
}
You could create random int as follows:
//To get a Random number 1-5 (I saw your RelativeLayouts and you've 5
Random rand = new Random();
int randomNum = rand.nextInt((5 - 1) + 1) + 1;
And then you could create a method to choose what to show :
public void ShowRelativeLayout(int rand){
switch(rand){
case 1:
if (layout1.getVisibility() == View.VISIBLE) {
//Do nothing cause it's visible
break;
} else {
layout1.setVisibility(View.VISIBLE);
break;
}
case 2:
..........
}
Make an array to store the layout indexes.
RelativeLayout[] layout = new RelativeLayout[5];
layout[0] = (RelativeLayout)findViewById(R.id.layout[0]); // 0
layout[1] = (RelativeLayout)findViewById(R.id.layout[1]); // 1
layout[2] = (RelativeLayout)findViewById(R.id.layout[2]); // 2
layout[3] = (RelativeLayout)findViewById(R.id.layout[3]); // 3
layout[4] = (RelativeLayout)findViewById(R.id.layout[4]); // 4
Make a simple random number generator.
public void FindNewLayout ()
{
Random r_generator = new Random();
int randomNum;
//now the only way to know which layouts have been shown before, you
//need to store the indexes that have been used before, somewhere.
//I recommend using an array.
// count, and the array below should be initialized somewhere else
//rather than inside the method so that only one instance of each is
//created, but for simplicity I'll just put their initialization here
int static count = 0;
//I'll explain below what count does.
// the log array that remembers each layout change
boolean[] log = new boolean[5];
do
{
//select new random number
randomNum = r_generator.nextInt((max - min) + 1) + min;
//in this case max = 4, min = 0, so replace these values in the
//equation above
// check the log to see if the number has appeared again
if ( log[randomNum] == false )
{
//Great! it hasn't appeared before, so change layout
log[randomNum] = true;
layout[randomNum].setVisibility = true;
count++; // increases step
break; //stops while because an unused layout has been found
}
}while (count<5)
//if the value of count is equal to 5 then every layout has been used
//before so the do-while code should not be run again
}// end method
And the above method should be called whenever you want to try to change layout.
Finally, you can use something like the Debugger.log("message"); statement
to be printed on the console for debugging purposes if you want, in order to find out when the layout has changed.
I have a textView set up on my main activity, and a button. When I click the button, I'd like the textView to start updating it's value based on the code below. However, this doesn't work and the problem is the loop. Can someone explain why? I am new to Java and Android Development
button2 = (Button) findViewById(R.id.button);
button2.setOnClickListener(new OnClickListener() {
TextView textView = (TextView)findViewById(R.id.refView);
public void onClick(View arg0) {
for(i=1;i<1;i++){
i = i + 1;
textView.setText(String.valueOf(i)+"hello");
}
}
});
Thank You
Try this:
TextView textView = (TextView)findViewById(R.id.refView);
button2.setOnClickListener(new View.OnClickListener() {
int i = 0;
public void onClick(View arg0) {
i = i + 1;
textView.setText(String.valueOf(i)+"hello");
}
});
Your for loop conditions were wrong.
for(i=1;i<1;i++) won't even start, because 1<1 is already met.
Initiate count variable i before onClick and then update it before click and set new text with updated i.
Not sure what exactly you want to happen. But, you can get rid of this line
i = i + 1;
because the i++ already increments i by 1 with each iteration of the for loop.
Second, since i starts off at 1 and you want the loop to run while i<1, it will never enter the loop. It is never less than 1.
Third, if the conditions were different, say
for (int i=0; i<10; i++)
it will run through the loop so fast that you won't even recognize a change.
This is a basic coding style question as I'm trying to be super accurate on best practices. I've browsed around and pieced together some Java code for generating a random string from a list and adding it to an existing string in my Android App.
On investigation I found two approaches, one was to use a single line of code to generate the random string by selecting an item from a list, another was to call a routine to do basically the same thing. I know it can be good to break the code up into smaller chunks, but in this case would one method be generally preferred over the other? Note that the first option is commented out in the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//Add a random day to the string
List<String> list = new ArrayList<>();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
list.add("Thursday");
list.add("Friday");
list.add("Saturday");
list.add("Saturday");
//Random rand = new Random();
//String random = list.get(rand.nextInt(list.size()));
String random = getRandom(list);
message += " " + random;
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
static public <T> T getRandom(List<T> list){
Random rand = new Random();
if(list == null || list.isEmpty()){
return null;
}else{
return list.get(rand.nextInt(list.size()));
}
}
Here in this case a good idea can be moving the code in to a routine. Though the function call may slow down the app(invisibly) this will be a best approach for code reuse. Consider you need the same functionality in another activity, you can simply call this function.