Toggle between texts values on Button click - android

I need to be able to toggle between two text values of "Hello world!" and "Hello!!!". I know this is going to be incredibly simple, but as I'm very new to programming so bear with me. Thanks in advance.
package edu.purdue.cnit355_lab1;
public class MainActivity extends Activity {
private Button HelloButton;
private TextView Message;
private OnClickListener HelloButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
Message.setText("Hello!!!");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HelloButton = (Button) findViewById(R.id.HelloButton);
Message = (TextView) findViewById(R.id.MessageText);
HelloButton.setOnClickListener(HelloButtonListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
My layout.main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/HelloButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello_button_label"
/>
<TextView
android:id="#+id/MessageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
/>
</RelativeLayout>
My strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">Hello Button</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="hello_button_label">Say "Hello!".</string>

#Override
public void onClick(View v) {
if (Message.getText().equals("Hello World")) {
Message.setText("Hello!!!");
} else {
Message.setText("Hello World");
}
}
you should also consider getting the string value using
getResources().getString(R.string.hello_world) instead of using them hard coded.
And try to avoid naming variables with uppercase like Message as they can be mistaken for objects.

Your code looks good. You can add some flag to toogle between your strings. Something like this:
private Strig[] hello = new String[]{"Hello World", "Hello!"};
private int toggleFlag = 0;
In your onClick method:
Message.setTex(hello[toogleFlag]);
toggleFlag ^= 1; // exclusive OR

Related

Basic android app showing blank white screen?

I'm new to android studio. Right now I'm making a basic app that recursively counts down from 4 to 0 when you click a button on the screen. When I look at my activity_main.xml in Design view, it shows what I want, but when I run my app on my Virtual Device, it just shows a white screen with nothing on it. How can I fix this? I'll paste my code here, almost all of my code is in the activity_main.xml and MainActivity.java
Here is activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >``
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/button1Contents"
android:onClick="sendMessage"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/button1"
android:text="#string/textView1Contents" />
</RelativeLayout>
and here is my MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = "OneButtonRecursion";
public void sendMessage(View view) {
Button clickedButton = (Button) view;
if (clickedButton == findViewById(R.id.button1)) {
TextView cup = (TextView) findViewById(R.id.textView1);
int handFull = Integer.parseInt(cup.getText().toString());
if (handFull > 0) {
cup.setText(handFull + "");
playNextCup(cup, handFull);
}
} else {
}
}
public static void playNextCup(TextView cupIn, int handFullIn) {
handFullIn--;
cupIn.setText(handFullIn + "");
if (handFullIn != 0) {
playNextCup(cupIn, handFullIn);
Log.i(TAG, "In recursion " + handFullIn);
} else {
}
}
}
and here is my strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">One Button Recursion</string>
<string name="action_settings">Settings</string>
<string name="button1Contents">Button1</string>
<string name="textView1Contents">4</string>
</resources>
You just forgot to Override onCreate() method
onCreate() Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI,
Just Override onCreate() inside your activity it will
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Something is crashing my app after I implemented Spinner setOnItemSelectedListener

Just to clarify first, I'm a newbie with Java and Android, and I'm still in a heavy learning process.
Anyway...
I'm working on a simple Parking SMS app, and I'm stuck with Spinner and a TextView.
Basically, I'm trying to do this: when I select a Parking zone from a Spinner (it has five parking zones), I want to populate a Parking zone description to a TextView below Spinner in the Layout.
Spinner has its own StringArray, while Parking zone descriptions are each in its own Strings.
So it looks like this:
activity_glavni.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Glavni">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
</ScrollView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/txGrad"
android:id="#+id/txOdaberiteGrad"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinnergradovi"
android:layout_below="#+id/txOdaberiteGrad"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />
<Space
android:layout_width="20px"
android:layout_height="20px"
android:id="#+id/space" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txZona"
android:text="#string/txZona"
android:layout_below="#+id/spinnergradovi"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinnerZona"
android:layout_below="#+id/txZona"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txPrikazZone"
android:layout_below="#+id/spinnerZona" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextRegistracija"
android:layout_below="#+id/txPrikazZone"
android:layout_alignParentStart="true"
android:hint="Unesite broj registracije" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_posalji"
android:id="#+id/btn_posalji"
android:layout_below="#+id/editTextRegistracija"
android:layout_alignParentStart="true"
android:layout_marginTop="33dp"
android:layout_alignParentEnd="false"
/>
strings.xml
<resources>
<string name="app_name">ParkingZagreb</string>
<string name="action_settings">Settings</string>
<string name="txGrad">Odaberite grad</string>
<string name="txZona">Odaberite zonu</string>
<string name="btn_posalji">Pošalji SMS!</string>
<string-array name="gradovi">
<item>Zagreb</item>
<item>Velika Gorica</item>
<item>Zaprešić</item>
</string-array>
<string-array name="zone">
<item>Prva zona</item>
<item>Druga zona</item>
<item>Treća zona</item>
<item>Četvrta zona (1)</item>
<item>Četvrta zona (2)</item>
</string-array>
<string-array name="opisi_zona">
<item>6 kn/h, maksimalno 2 h</item>
<item>3 kn/h, maksimalno 3 h</item>
<item>1,5 kn/h, bez ograničenja</item>
<item>5 kn/dan, 7-16 h</item>
<item>10 kn/dan, 7-20 h</item>
</string-array>
Glavni.java
public class Glavni extends ActionBarActivity {
public TextView txPrikazZone;
private Button btn_posalji;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glavni);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
btn_posalji = (Button) findViewById(R.id.btn_posalji);
btn_posalji.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(Glavni.this).create();
alertDialog.setTitle("SMS poslan!");
alertDialog.setMessage("Provjerite SMS aplikaciju. Poruka bi trebala doći za nekoliko trenutaka.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
});
// the first city selection Spinner
Spinner spinner_gradovi = (Spinner) findViewById(R.id.spinnergradovi);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.gradovi, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spinner_gradovi.setAdapter(adapter);
// the second Spinner with parking zones
final Spinner spinner_zona = (Spinner) findViewById(R.id.spinnerZona);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.zone, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spinner_zona.setAdapter(adapter2);
// this is where I'm trying to populate the TextView with the String-Array by selecting an item from the second Spinner
final String[] opisi_zona = getResources().getStringArray(R.array.opisi_zona);
spinner_zona.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
txPrikazZone.setText(opisi_zona[position]);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_glavni, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks for any help...
The reason for the null pointer is that you have not initialized txPrikazZone and you are trying to call setText.
You need to initialize it in your onCreate method like this:
txPrikazZone = (TextView) findViewById(R.id.txPrikazZone);
I hope this helps.
Your adapter it´s the same for both Spinners
EDIT
First try wrapping your ZonaX strings into a string-array
<string-array name="zonas">
...
</string-array>
And now in the code change the set of the ItemSelectedListener
final String[] zonas = getResources().getStringArray(R.array.zonas);
spinner_zona.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
txPrikazZone.setText(zonas[position]);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}

Android - How to setText() of an item outside the present dialog

I have a button that calls a dialog. From that button i have 8 buttons: 1,2,3,4,5,6,7, and cancel. These buttons will be used to change the text of the button. The thing is that it doesn't do anything if i set the text inside the dialog.
buttonDefineHits = (Button) rowView.findViewById(R.id.button_define_hits);
buttonDefineHits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Dialog 1-7 i x para definir los holes
setDialogSetHits();
}
});
.
private void setDialogSetHits(){
final Dialog dialogConfirmPlayers = new Dialog (activity);
dialogConfirmPlayers.setCancelable(false);
dialogConfirmPlayers.setContentView(R.layout.dialog_set_hits);
Button button1Hit = (Button) dialogConfirmPlayers.findViewById(R.id.button_1_hit);
button1Hit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Dialog 1-7 i x para definir los holes
buttonDefineHits.setText("1");
dialogConfirmPlayers.cancel();
}
});
dialogConfirmPlayers.show();
}
You can set the Text of a Button that is defined in a activity from the dialogBox. I guess Aniruddha is wrong in his comment. I mean yes the user cannot have a "Iteration" with the Activity's UI elements as long as a Dialog is shown over it, But programatically you can change the Text property of the Button in your activity. To confirm, this is what I tried:
Created a Dialog on the click event of ImageView.
From the Dialog Button's Click listener, I changed the Text of a editText in the Activity.
Similarly, you should also be able to set the text of the button from the dialog button's click listener.
I think you should remove the 7 buttons from your dialog, and for testing purpose just have one button on it. Then handle the click event on this button and try n set the Activity button's Text. This should work like charm.
Then later you can integrate your 7-buttons.
Here is the working example, you need to modify it accordingly
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:id="#+id/tv1"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/buttonMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv1"
android:layout_below="#+id/tv1"
android:layout_marginTop="44dp"
android:text="Button" />
</RelativeLayout>
dialog_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
TextView t;
Button bMain;
Dialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.tv1);
bMain = (Button) findViewById(R.id.buttonMain);
bMain.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
d = new Dialog(MainActivity.this);
d.setTitle("Hello Android..!");
d.setContentView(R.layout.dialog_view);
Button bOK = (Button) d.findViewById(R.id.button1);
Button bCancel = (Button) d.findViewById(R.id.button2);
d.show();
bOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
t.setText("OK");
bMain.setText("Changed the text");
d.cancel();
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

TextView failure

I'm programming my first android app.
I want to set text on a TextView.
(I already searched here and found out, how to do it...But it still don't work)
Do you know, what the problem is?
This is my Java code.
package com.example.randomcraps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import com.example.*;
public class MainActivity extends Activity {
TextView text = (TextView) findViewById(R.layout.number);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getRandomNumber(){
int i;
double savePoint;
savePoint = Math.random();
savePoint = savePoint*100+1;
i = (int)savePoint;
text.setText(i);
}
}
This is my XML Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="26dp"
android:text="#string/Button1"
android:onClick="getRandomNumber" />
<TextView
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/RandomNumber" />
</RelativeLayout>
Change to
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.number); // id of textview in activity_main.xml
}
findViewById looks for a view with the id mentioned in the current inflated layout. So you need to set layout to the activity and then initialize your views.
Also change
text.setText(i);
// looks for a resource with the id mentioned if not found you get ResourceNotFoundException
To
text.setText(String.valueOf(i));
// int i; i is an int value. Use String.valueOf(intvalue)
Edit:
Your method signature is different. It should be
public void getRandomNumber(View V){ // missing View as param
... //rest of the code
}
Coz you have
android:onClick="getRandomNumber"
Quoting from docs
public static final int onClick
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
Change your code to this.
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.number);
}
Also
text.setText(String.valueOf(i));
NOTE: findViewByID finds view from content. So basically you have to use that method after you set your content.
Set text color after setText and for guarantee set the font size. Sometimes it makes the color default white.

android: get items from string array and show it one by one in text view

as i write in title i need some help here for get items from string array and show it one by one in text view i have code that got them all in list view but i need show them on text view one by one each time random here my code and sorry about my bad english
,thanks for help anyway ...
public class MainActivity extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.planets_array);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#array/planets_array"
/>
</RelativeLayout>
and string array file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
</resources>
Ok, with comments I understood what you need and edited my answer for that. You want to show values of your array in a textView randomly.
Use this activity:
public class MainActivity extends Activity {
String[] mTestArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
mTestArray = getResources().getStringArray(R.array.planets_array);
}
#Override
protected void onResume() {
super.onResume();
updateTextView();
}
private void updateTextView() {
TextView textView = (TextView)findViewById(R.id.randomTextView);
Random random = new Random();
int maxIndex = mTestArray.length;
int generatedIndex = random.nextInt(maxIndex);
textView.setText(mTestArray[generatedIndex]);
}
}
Put this layout under res/layout folder and name it sample.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/randomTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>

Categories

Resources