I have the following Java code for my button event. This code doesn't generate any error at compile-time, but the app crashes during launch.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b0 = (Button) findViewById(R.id.button0);
b0.setOnClickListener(this);
}
String t = "";
TextView inp = (TextView) findViewById(R.id.input);
public void onClick(View v)
{
if (v == findViewById(R.id.button0))
{
t = "0";
inp.setText(inp.getText()+t);
}
}
The Xml Code is :
<Button
android:id="#+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/dbtn"
android:layout_alignBottom="#+id/dbtn"
android:layout_toLeftOf="#+id/button3"
android:text="0" />
What am I doing wrong?
TextView inp = (TextView) findViewById(R.id.input);
Put the above line inside onCreate() method after you call setContentView() and change you TextView variable scope from local to global.
This should fix the issue. If you still having trouble, let me know.
Related
Trying to create notes application. I am trying to add dynamic text view after button click and it should be added to layout, one after another. In my code, only one text view is getting added successfully but from second time, app got crashed. Please help
XML Code:
<EditText
android:id="#+id/text_thingsToDo"
android:layout_width="#dimen/ThingsToDo_EditText_Width"
android:layout_height="#dimen/ThingsToDo_EditText_Height"
android:layout_margin="#dimen/Standardize_Margin"
android:background="#color/ThingsToDo_EditText_Color"/>
<Button
android:id="#+id/save_thingsToDo"
android:layout_toRightOf="#+id/text_thingsToDo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ThingsToDo_Save_Button_Text"
android:layout_marginRight="#dimen/Standardize_Margin"
android:layout_marginTop="#dimen/Standardize_Margin"
android:layout_marginBottom="#dimen/Standardize_Margin"
android:background="#color/ThingsToDo_Save_Button"
android:textColor="#color/White"
android:layout_centerVertical="true"/>
Java Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_things_to_do);
final EditText editText = (EditText) findViewById(R.id.text_thingsToDo);
Button button = (Button) findViewById(R.id.save_thingsToDo);
final TextView notesView = new TextView(this);
final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.rootView_ThingsToDo);
final ArrayList<String> arrayList = new ArrayList<String>();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notesView.setText(editText.getText().toString());
linearLayout.addView(notesView);
}
});
}
Perhaps create a new TextView every time you press the button? Try to declare the TextView as a class member and then in your OnClickListener do this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notesView = new TextView(this);
notesView.setText(editText.getText().toString());
linearLayout.addView(notesView);
}
});
Hopefully this will fix your problem!
I'm new to android develop. i just stated this week.
i dont know if im asking stupid question but i want to learn.
i have created an app just click a button change the background color.
my layout is this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.seluhadu.colorpicker.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="136dp"
tools:layout_editor_absoluteY="1dp"
android:elevation="8dp"
android:layout_alignBaseline="#+id/button3"
android:layout_alignBottom="#+id/button3"
android:layout_alignParentEnd="true"
android:layout_marginEnd="52dp"/>
</RelativeLayout>
and i have a class "java" like this
public class MainActivity extends AppCompatActivity {
Button button;
RelativeLayout relativeLayout;
Integer[] colors = {
R.color.color1,
R.color.color2,
R.color.color3,
R.color.color4,
R.color.color5,
R.color.color6,
R.color.color7,
R.color.color8,
R.color.color9,
R.color.color10,
R.color.color11,
R.color.color12,
R.color.color13,
R.color.color14,
R.color.color15,
R.color.color16,
R.color.color17,
R.color.color18,
R.color.color19,
R.color.color20
};
Random random;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random = new Random();
relativeLayout = (RelativeLayout) findViewById(R.id.background);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
colors[random.nextInt(colors.length)]));
}
});
}
it just change the background color random.
when it change the color if i rotat the screen it change to default back.
my question is how to make a onSaveInstanceState and onRestoreInstanceState method to save the change color even if i reopen the app to stay the color that i change.
OR how can i do like that in other way?
thank you for your help!
When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system
passes your activity. Both the onCreate() and onRestoreInstanceState()
callback methods receive the same Bundle that contains the instance
state information.
Because the onCreate() method is called whether the system is creating
a new instance of your activity or recreating a previous one, you must
check whether the state Bundle is null before you attempt to read it.
If it is null, then the system is creating a new instance of the
activity, instead of restoring a previous one that was destroyed.
public class MainActivity extends AppCompatActivity {
Button button;
RelativeLayout relativeLayout;
Integer[] colors = {
R.color.color1,
R.color.color2,
R.color.color3,
R.color.color4,
R.color.color5,
R.color.color6,
R.color.color7,
R.color.color8,
R.color.color9,
R.color.color10,
R.color.color11,
R.color.color12,
R.color.color13,
R.color.color14,
R.color.color15,
R.color.color16,
R.color.color17,
R.color.color18,
R.color.color19,
R.color.color20
};
Random random;
Boolean backgroundChanged = false;
int colorIndex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore background color from saved state
backgroundChanged = savedInstanceState.getBoolean("backgroundChanged", false);
colorIndex = savedInstanceState.getInt(colorIndex, 0);
}
random = new Random();
relativeLayout = (RelativeLayout) findViewById(R.id.background);
if(backgroundChanged) {
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), colors[colorIndex]));
}
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
backgroundChanged = true;
colorIndex = random.nextInt(colors.length);
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), colors[colorIndex]));
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("backgroundChanged", backgroundChanged);
if(backgroundChanged) {
savedInstanceState.putInt("colorIndex", colorIndex);
}
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Update
Here's my code below, plugged into your posted example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random = new Random();
relativeLayout = (RelativeLayout) findViewById(R.id.background);
button = (Button) findViewById(R.id.button);
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
int colorIndex = settings.getInt("colorIndex", 0);
updateBackground(colorIndex);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int colorIndex = random.nextInt(colors.length);
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
settings.edit().putInt("colorIndex", colorIndex).apply();
updateBackground(colorIndex);
}
});
}
private void updateBackground(int colorIndex) {
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), colors[colorIndex]));
}
If you have to store the color even through app restarts, you should use SharedPreferences instead of using onSaveInstanceState().
In your onClick(), when you generate the random index for your color array, write that value to your SharedPreferences object. In onCreate() when you set everything up, read the value out of the SharedPreferences.
To write:
int colorIndex = random.nextInt(colors.length);
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
settings.edit().putInt("colorIndex", colorIndex).apply();
To read:
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
int colorIndex = settings.getInt("colorIndex", 0);
I hate errors like this. I'm getting a null pointer. I know what it means. I just don't understand how i'm getting it since i know that the item it should be pointing to does exist. I'm creating a textview that will be updated by the opengl renderer. The textview provides a score. I've created the textview in XML and given it a 'id', then i reference it in my program and update it through the renderer. Icreate TextView variables globally then I initialize them in the onCreate() method. Then I created a method to set the text. Which is called inside of my renderer class.
Here is my java code
View r1;
TextView score3, score4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set app to full screen and keep screen on
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(Main.layout);//R.layout.gl_triallayout;
r1 = findViewById(Main.id);////R.id.gl_triallayout;
score3 = (TextView) findViewById(R.id.threeScore);
score4 = (TextView) findViewById(R.id.fourScore);
......
}
public int get3(int i){
score3.setText("Score" + String.valueOf(i));
((RelativeLayout) r1).bringChildToFront(findViewById(R.id.threeScore));
Log.i("i", String.valueOf(i));
return i;
}
XML code
<TextView
android:id="#+id/threeScore"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:textSize="30dp"
android:textColor="#ffff00"/>
Update
Main class
public void Trial(View v) {
layout = R.layout.gl_triallayout;
id = R.id.glTrialLayout;
gameType = 0;
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
}
public void PlayGame(View v) {
layout = R.layout.gl_layout;
id = R.id.glLayout;
gameType = 1;
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
}
I hate the idea of clutter stackoverflow with the same question so if the answer is immensely simple could you give it to me in the comments. then i could delete this.
Your
setContentView(Main.layout)
should be
setContentView(R.layout.filename)
In the above code, you should change your layout file name based on your need like R.layout.activity_main.
Same applies to,
r1 = findViewById(Main.id);////R.id.gl_triallayout;
What is r1?
If it's a button, it should be
r1 = (Button) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout;
If it's a Editext,
r1 = (EditText) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout
If it's a TextView,
r1 = (TextView) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout
Also, In your XML layout, where's the view for score4 and r1?
I think you should start learning the basics of Android first.
I have 2 xml files, "activity_main" and "main_screen", both have 1 button each here are the xml of the buttons:
The login button < this button is on the first screen of my application
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/entrar"
android:id="#+id/button"
android:onClick="onClick"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
And the "save data button" < this one is on the second screen.
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Salvar"
android:id="#+id/button2"
android:onClick="onClick"
android:layout_marginTop="43dp" />
Java code of the first button:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Editable login = editLogin.getText();
String loginTexto = login.toString();
Editable pass = editPass.getText();
String senhaTexto = pass.toString();
try{
trocaTela();
System.out.println("botao login" + R.id.button);
//a.enviaDados(loginTexto, senhaTexto, textView);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
});
Java code of the second button:
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText editNome = (EditText) findViewById(R.id.nomeEdit);
final EditText editDestino = (EditText) findViewById(R.id.destinoEdit);
final EditText editKm = (EditText) findViewById(R.id.kmEdit);
final TextView textView = (TextView) findViewById(R.id.textView);
//pega o texto inserido no campo da placa
Editable editable = editPlaca.getText();
String placaTexto = editable.toString();
//pega o nome inserido no campo do nome
Editable nomeEditable = editNome.getText();
String nomeTexto = nomeEditable.toString();
//pega o destino inserido no campo do destino
Editable destinoEditable = editDestino.getText();
String destinoTexto = destinoEditable.toString();
//pega o valor inserido no campo do km
Editable kmEditable = editKm.getText();
String kmTexto = kmEditable.toString();
try {
ScreenFunctions f = new ScreenFunctions();
System.out.println("botao screen:" + R.id.button2);
f.formatPost(nomeTexto, placaTexto, destinoTexto, kmTexto, textView);
} catch (Exception e) {
System.out.println("Button press exception: " + e.getMessage());
}
}
});
The problem is... i can't understand how i'll treat the "onClick" function, because the "onClick" method is abstract, so i can't change it's name, how could the second button use the MainScreen onClick and the first button use the MainActivity onClick.
remove the
android:onClick="onClick"
You dont need to have this cause you are setting onclicklisteners in your java code
give me info if this helped or not
EDIT
make sure you have catch your button variables correctly:
button = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.button2;
Remove the android:onClick="onClick" in your xml files.
You are misunderstand the usage of android:onClick tag in xml file.
Please check the document of android:onClick tag
Change the name of function:
android:onClick="onClick"
to
android:onClick="someMethod"
I think if you want to make your code prettier and better, you should use ButterKnife for view injection and specifying the onclick method with that, like this:
1.) add ButterKnife to your dependencies
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
...
compile 'com.jakewharton:butterknife:6.0.0'
2.) inject your view into the field
#InjectView(R.id.button)
public Button button;
3.) specify the onClick method
#OnClick(R.id.button)
public void myOnClickMethod(View view)
{
//do things
}
4.) inject the activity or fragment with ButterKnife
Activity:
#Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
ButterKnife.inject(this);
...
}
Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.inject(this, rootView);
...
return rootView;
}
So when I try and run my code in the emulator, the app background pops up then closes giving me the dialog, "Unfortunately, Callisto has stopped working"
I have no idea what is wrong other than it gives me a null pointer exception (line 49) but there is nothing at line 49
XML
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/callisto_heading" />
<Button
android:id="#+id/bClasses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Classes"
android:layout_gravity="center"
android:onClick=""
/>
<Button
android:id="#+id/bSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:layout_gravity="center"
android:onClick=""
/>
</LinearLayout>
Java
package android.callisto.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class CallistoActivity extends Activity {
/** Called when the activity is first created. */
Button settings_button;
Button classes_button;
Button home_button;
CheckBox notif_cb;
CheckBox math_cb;
CheckBox science_cb;
CheckBox ss_cb;
CheckBox english_cb;
CheckBox language_cb;
boolean notif,math,science,english,ss,language;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//settings layout
notif_cb = (CheckBox) findViewById(R.id.cbNotif);
math_cb = (CheckBox) findViewById(R.id.cbMath);
science_cb = (CheckBox) findViewById(R.id.cbScience);
ss_cb = (CheckBox) findViewById(R.id.cbSS);
english_cb = (CheckBox) findViewById(R.id.cbEnglish);
language_cb = (CheckBox) findViewById(R.id.cbLang);
home_button = (Button) findViewById(R.id.bHome);
notif = true;
math = true;
science = true;
english = true;
ss = true;
language = true;
home_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.main);
}
});
//notifications
//main layout
settings_button = (Button) findViewById(R.id.bSettings);
classes_button = (Button) findViewById(R.id.bClasses);
settings_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.settings);
}
});
}
}
FYI the app was loading last night.. Thanks for any help and please remember I am new to Android programming. Thank you.
the problem is here
home_button = (Button) findViewById(R.id.bHome);
in layout file there is no bHome
The problem probabaly is, that you are using the setContentView() for displaying different screens. You should not use this method for changing screens,you should use a different activitys for this.
Usually, you only set the contentView ONCE in the oncreate, per activity.
Your R.layout.main layout probabaly does not contain the 'home' button, but the r.layout.settings layout does.
First you are loading the main layout at this line: setContentView(R.layout.main); But since this layout file does NOT contain the home button, findViewById(R.id.bHome); will return null. After that, calling a method on this returned value, home_button.setOnClickListener(); in your case, will cause a NullPointerException.
What you should do is the following:
Create an activity for your main layout:
public class CallistoMainActivity extends Activity {
/** Called when the activity is first created. */
Button settings_button;
Button classes_button;
Button home_button;
CheckBox notif_cb;
CheckBox math_cb;
CheckBox science_cb;
CheckBox ss_cb;
CheckBox english_cb;
CheckBox language_cb;
boolean notif,math,science,english,ss,language;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//main layout
settings_button = (Button) findViewById(R.id.bSettings);
classes_button = (Button) findViewById(R.id.bClasses);
settings_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),
CallistoSettingsActivity.class));
}
});
}
And an activity for your Settings layout:
public class CallistoSettingsActivity extends Activity {
Button home_button;
CheckBox notif_cb;
CheckBox math_cb;
CheckBox science_cb;
CheckBox ss_cb;
CheckBox english_cb;
CheckBox language_cb;
boolean notif,math,science,english,ss,language;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
//settings layout
notif_cb = (CheckBox) findViewById(R.id.cbNotif);
math_cb = (CheckBox) findViewById(R.id.cbMath);
science_cb = (CheckBox) findViewById(R.id.cbScience);
ss_cb = (CheckBox) findViewById(R.id.cbSS);
english_cb = (CheckBox) findViewById(R.id.cbEnglish);
language_cb = (CheckBox) findViewById(R.id.cbLang);
home_button = (Button) findViewById(R.id.bHome);
notif = true;
math = true;
science = true;
english = true;
ss = true;
language = true;
home_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
//You could either use finish() to finish the current activity, and return to the previous CallistoMainActivity on the stack.
//Or you could simply start the main activity again by using the startActivity() method you see in the onclicklistener on the settings button.
}
});
}
What happens now, is when you click the settings button in the main activity, the settings activity will be shown. When you click the home button in the settings activity, the settings activity will be finished, and the user will be returned to the previous activity on the stack; which is the main activity.
Also do not forget to define the settingsactivity in your AndroidManifest.xml
EDIT: Another thing you should note, that if there is an error 'at line x' but there is nothing at line x in your code, then the code running on your Android device, is not the same as the code you are looking at in your editor. So that might be the reason it was running last night, but not anymore.