This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
So I am attempting to use a spinner to change the text colour of a message in a text view. However, when I attempt to use the function attached to my button click the activity crashes. I have attached the relevant part of the java code and the xml file
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;
public class Colour extends AppCompatActivity {
private Spinner mySpinner;
public static final String EXTRA_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colour);
Intent intent = getIntent();
String messageText = intent.getStringExtra(EXTRA_MESSAGE);
TextView messageView = (TextView)findViewById(R.id.message);
messageView.setText(messageText);
}
public void change(View v){
String text = mySpinner.getSelectedItem().toString();
TextView newColour = (TextView) findViewById(R.id.message);
if(text == "Red"){
newColour.setTextColor(Color.RED);
}
if(text == "Blue"){
newColour.setTextColor(Color.BLUE);
}
if(text == "Green"){
newColour.setTextColor(Color.GREEN);
}
}
XML file:
<TextView
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/message" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/colours"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:id="#+id/spinner" />
<Button
android:text="HOME"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="home"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp" />
<Button
android:text="changeColour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button4"
android:layout_above="#+id/button"
android:layout_alignStart="#+id/button"
android:layout_marginBottom="101dp"
android:onClick="change" />
mySpinner is not initialized before access it's method. please initialize mySpinner first. use following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySpinner = (Spinner)findViewById(R.id.spinner);
}
public void change(View v){
String text = mySpinner.getSelectedItem().toString();
TextView newColour = (TextView) findViewById(R.id.message);
if(text.equals("Red")){
newColour.setTextColor(Color.RED);
}
if(text.equals("Blue")){
newColour.setTextColor(Color.BLUE);
}
if(text.equals("Green")){
newColour.setTextColor(Color.GREEN);
}
}
it seems that you did not setup the spinner in the change method so you need to initialize it first
Related
I am trying to increase the value of variable count by one each time i click on the button to switch the activity back and forth. However, each time i clicked, the count value is still the same. Can someone kindly help ?
I am trying to put some life-cycle android code, but it still does not make any difference.
package com.darayuth.learning;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.darayuth.learning";
public static final String TAG = "MainActivity";
public static final String value = "value";
private int count = 0;
private TextView textView;
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(value, count);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
count = savedInstanceState.getInt(value);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView2);
Button btn = findViewById(R.id.button);
btn.setOnClickListener((View v)->{
sendMessage();
});
}
public void sendMessage(){
count = count + 1;
Log.i(TAG, "value: " + count);
Intent intent = new Intent(this, Main2Activity.class);
EditText editText = findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message );
startActivity(intent);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Button" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
</LinearLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
package com.darayuth.learning;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = findViewById(R.id.textView1);
textView.setText(message);
}
}
I would suggest using SharedPreferences to store and retrieve the value between your activities.
private void storeValue(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Store an integer using the Shared Preferences editor
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("myPreferenceValueKey", value); // Store the value with a key to identify it
editor.apply();
}
private void retrieveValue(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int defaultValue = 0; // This is the value that's returned if the preference doesn't exist
// Retrieve the stored value using the associated key
value = prefs.getInt("myPreferenceValueKey", defaultValue);
}
In your first Activity, just call retrieveValue() in your onCreate() then call storeValue() after incrementing the value but before starting the next Activity.
You can create the same functions in your second Activity to store and retrieve the value as needed.
You can learn more about SharedPreferences at https://developer.android.com/training/data-storage/shared-preferences
I suggest you use a class with a static variable to hold the count variable. And add a function increment() to increase the count.
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 4 years ago.
I am trying to get an input from user and then covert it into double and divide it by 1000 and then set the value in a textview but i while running the app, the app closes and says Unfortunately the app has stopped.
Here's my MainActivity.java file :
package com.blogspot.techtutorialsajen.androiddevelopmentpractice;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btn1;
private EditText get;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.btn1);
result = (TextView)findViewById(R.id.result);
get = (EditText)findViewById(R.id.get);
final double value = Double.parseDouble(get.getText().toString()) / 1000;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
result.setText(String.valueOf(value));
}
});
}
}
And My activity_main.xml file :
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:id="#+id/get"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/enter_a_number"
android:layout_marginTop="48dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn1"
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/result"
android:layout_centerHorizontal="true"
android:layout_marginBottom="28dp" />
<TextView
android:id="#+id/result"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="20pt"
android:text="0"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Well, Your app is crashes because of java.lang.RuntimeException:java.lang.NumberFormatException: Invalid double: ""
that means you are trying to convert empty string to Double.
So, Because the EditText is empty your app is crashes and I have re-write your code so that you can copy-paste.
Here is your MainActivity.Java
package com.blogspot.techtutorialsajen.androiddevelopmentpractice;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btn1;
private EditText get;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.btn1);
result = (TextView)findViewById(R.id.result);
get = (EditText)findViewById(R.id.get);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (get.getText().toString().isEmpty()) {
Toast.makeText(MainActivity .this, "Please input something", Toast.LENGTH_LONG).show();
} else {
final double value = Double.parseDouble(get.getText().toString()) / 1000;
result.setText(String.valueOf(value));
}
}
});
}
}
and here is your activity_main.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:id="#+id/get"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/enter_a_number"
android:layout_marginTop="48dp"
android:inputType="number"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn1"
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/result"
android:layout_centerHorizontal="true"
android:layout_marginBottom="28dp" />
<TextView
android:id="#+id/result"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="20pt"
android:text="0"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I have added android:inputType="number" property to your EditText so that, now on, it will only take Number from the user.
From your xml file and activity code, it clearly says your edittext is empty while launching app.
And you are using this code in oncreate()
final double value = Double.parseDouble(get.getText().toString()) / 1000;
which throws java.lang.NumberFormatException: empty String
You can change your code like,
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!get.getText().toString().isEmpty)
final double value = Double.parseDouble(get.getText().toString()) / 1000;
result.setText(String.valueOf(value));
}
});
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
So I'm trying to implement a simple class in android studio that takes user input in the form of a spinner and changes the colour of the text accordingly. However, even though the condition has been met, as can be seen by the debugging line, the program will not execute the contents of the if statement.
debugging line
'import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Colour extends AppCompatActivity {
TextView tv;
Spinner mySpinner;
ArrayAdapter<CharSequence> adapter;
public static final String EXTRA_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colour);
Intent intent = getIntent();
String messageText = intent.getStringExtra(EXTRA_MESSAGE);
tv = (TextView)findViewById(R.id.message);
tv.setText(messageText);
mySpinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this,R.array.colours,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemIdAtPosition(position)+ " selected",Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void change(View v){
String text = mySpinner.getSelectedItem().toString();
if(text == "Red"){
tv.setTextColor(Color.RED);
}
if(text == "Blue"){
tv.setTextColor(Color.BLUE);
}
if(text == "Green"){
tv.setTextColor(Color.GREEN);
}
}'
'<TextView
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/message" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/colours"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:id="#+id/spinner" />
<Button
android:text="HOME"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="home"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp" />
<Button
android:text="changeColour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button4"
android:layout_above="#+id/button"
android:layout_alignStart="#+id/button"
android:layout_marginBottom="101dp"
android:onClick="change" />'
answer would be
if(text.equals("Red")) etc
because a text is an object of type String it is not a primitive type
primitive type can be compared using == but not a reference type
I am trying to use an intent to start two different classes in which I change either the text size or text colour of an entered message. Starting these classes is triggered by two different button push events in android studio. However, only the TextSize class is being started no matter what button I push and I cannot see the reason why. Below I have the problem activities class code and xml code
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public static final String EXTRAA_MESSAGE ="message2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void changeText(View v){
EditText messageView = (EditText)findViewById(R.id.message);
String messageText = messageView.getText().toString();
Intent result = new Intent(this, TextSize.class);
result.putExtra("message",messageText);
startActivity(result);
}
public void changeColour(View v){
EditText messageView = (EditText)findViewById(R.id.message);
String messageText = messageView.getText().toString();
Intent result = new Intent(this, ColourChange.class);
result.putExtra("message",messageText);
startActivity(result);
}
My XML File
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp" />
<EditText
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:ems="10"
android:layout_below="#+id/textView2"
android:layout_alignParentStart="true" />
<Button
android:text="Change Colour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Colour"
android:onClick="changeColour"
android:layout_centerVertical="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="36dp"
android:onClick="changeText"
android:text="Change Text Size"
android:layout_alignBaseline="#+id/Colour"
android:layout_alignBottom="#+id/Colour"
android:layout_alignParentEnd="true"
android:layout_marginEnd="33dp"
android:id="#+id/TextSize" />
In Android just implements the OnClickListener for you when you define the android:onClick="someMethod" attribute.
you can implemented just different way.
Button btnColour = (Button) findViewById(R.id.Colour);
btnColour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call your method here
changeColour(v);
}
});
// your method code
public void changeColour(View v) {
// your method code
}
As You doing
check your xml file that have you define context with parent layout or not
tools:context="com.example.YourActivity"
// com.example.YourActivity should be your activity with package name
I am having a problem when debugging apps that respond to user input. An ordinary app that just displays text works fine, but when I give a button an event handler I get a generic message "Unfortunately, 'App Name' has stopped.". I have tried many solutions, but to no avail. I am using IntelliJ IDEA 12.0.4 (Community Edition).
Sorry for asking a very common question but it seems the solution is different for everyone.
Edit - new working code
Source Code:
package com.example.Android_Test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static com.example.Android_Test.R.*;
public class MyActivity extends Activity {
EditText editText;
TextView textView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare all widget controls.
editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
textView = (TextView) findViewById(R.id.lblText);
button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText());
}
};
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtEdit" android:layout_gravity="left|center_vertical"
android:layout_alignParentLeft="true" android:layout_marginLeft="0dp" android:layout_alignParentTop="true"
android:layout_marginTop="0dp" android:layout_alignParentRight="true" android:hint="Type here change text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/btnChange"
android:layout_alignLeft="#+id/txtEdit" android:layout_below="#+id/txtEdit"
android:layout_alignRight="#+id/txtEdit"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change this text"
android:id="#+id/lblText"
android:layout_alignLeft="#+id/txtEdit" android:layout_below="#+id/btnChange"
android:layout_alignRight="#+id/txtEdit" android:textSize="18dp"/>
</RelativeLayout>
Logcat is very long so I pasted it here: http://pastebin.com/2qaY8ZJj.
Everyone's Logcat is so much shorter i don't know why
Move this code
// Declare all widget controls.
EditText editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
TextView textView = (TextView) findViewById(R.id.lblText);
inside onCreate() and use R.id... .
Edit
I edited youre code
public class MyActivity extends Activity {
EditText editText;
TextView textView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare all widget controls.
editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
textView = (TextView) findViewById(R.id.lblText);
button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText().toString);
}
};
}