Android Studio: Boolean function crashes my app - java

Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.
Code:
MainActivity.java
package com.leuchtstein.flashlight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView) ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void triggerlight(View view) {
if (stat == false) {
text.setText("ON");
stat = true;
} else {
text.setText("OFF");
stat = false;
}
}
}
activity_main.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="com.leuchtstein.flashlight.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/desc_textview"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
app:layout_constraintHorizontal_bias="0.95"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="triggerlight"
android:text="Turn on/off"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.387" />
Well, thanks in advance.

Don't call
TextView text = (TextView) findViewById(R.id.textView) ;
in initialisation, rather call it in onCreate() method.
This is because Android first initializes the script, and calls onCreate only when setContentView() has been called and it has set up the button, &c. Thus findViewById(int id) can't find anything yet.
Put
text = (TextView) findViewById(R.id.textView);
in onCreate() and put
TextView text;
in initialisation instead.

Try this :
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}

You haven't provided the logcat or any other any ifo, but one thing I can see here that could go wrong is this :
TextView text = (TextView) findViewById(R.id.textView);
Change your code to look like this :
public class MainActivity extends AppCompatActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
So the difference is, you assign a value to your TextView using findViewById, after you have have called setContentView().
All view assignments should be only done after setContentView()is called in activities because that is where you set your root view and when you call findViewById(), the system looks up a view with an id in the root view.

Related

How do I pass string from SecondActivity to MainActivity on Android Studio?

I have a public String stringPass in SecondActivity.java that I want to pass to MainActivity.java so that when I click a button, the string from the SecondActivity.java updates a TextView tv that is declared in MainActivity.java.
The bug I'm getting is that when I press the button, the string in the SecondActivity.java is not shown.
Instead, It goes from "Hello World!" to no text displayed.
FYI, i'm going to add strings to MainActivity.java from multiple activities, so I want it this particular way for my organization.
Thanks!
SecondActivity.java
public class SecondActivity extends AppCompatActivity{
public String stringPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stringPass = "this is from SecondActivity";
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv = findViewById(R.id.tv);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(new SecondActivity().stringPass);
}
});
}
}
activity_main.xml
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Is there much content in the second activity? Is it an actual activity with much going on? If not replace it with a dialog box, when the ok button is clicked it can update the text box.

Android Studio error: #Override not applicable to field

I am fairly new to android development and as my first app I want to make a flashlight app. So the first steps I want to do is to make a button in the center such that it changes it's text to "ON" and "OFF" alternately after every click. I made the java code but it Android studio gives me this error: '#Override' not applicable to field. Here is my java code:
package com.danielfernandzz.flashlight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
public boolean switchState = false;
Button switchbutton = (Button) findViewById(R.id.Switch);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Switched(View v){
if(!switchState){
switchState = true;
switchbutton.setText("OFF");
}else{
switchState = false;
switchbutton.setText("ON");
}
}
}
And here is my xml code (in case you need it):
<?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="com.danielfernandzz.flashlight.MainActivity">
<Button
android:id="#+id/Switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="8dp"
android:onClick="Switched"
android:text="ON"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I tried commenting out the #Override and no error came. But when I ran the app, it crashed so I assume that the app crashed because #Override wasn't there?
I don't understand why this is happening to me, I have seen other questions but their error is something different.
NOTE: I am using the latest version Android Studio 3.0
try this
1.move you switchbutton = (Button) findViewById(R.id.Switch); inside your onCreate() method
2.place #Override before onCreate()
sample code
public class MainActivity extends AppCompatActivity {
public boolean switchState = false;
Button switchbutton ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchbutton = (Button) findViewById(R.id.Switch);
}
public void Switched(View v){
if(!switchState){
switchState = true;
switchbutton.setText("OFF");
}else{
switchState = false;
switchbutton.setText("ON");
}
}
}
As according #Jerrol you can place the #Override before onCreate. There is no need to place it before variable initialization.Could you give us the crash log that you are getting after removal.

Accept user input from Activity

I have some experience with Java, but I am now trying to create an Android app and I do not know how to accept user input. The id of my Edit Text is enterRequestMessage and the name of my XML file is activity_score_entry.xml. Here is the beginning of my Java file.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ScoreEntry extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
}
}
You need to get access to the controls in the xml
public class ScoreEntry extends AppCompatActivity implements View.OnClickListener {
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
String value = editText.getText().toString();
// use the value here
Log.d(ScoreEntry.class.getCanonicalName(), "The value is: " + value);
}
}
}
And in the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_score_entry"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
You can adjust the code according to your needs.

Android, set text for an EditText on startup

So I have a simple android app where I take text from a text file (that part is working) and I want to set that text to EditText.setText(). The problem I'm having is that I cannot do this in the onCreate() method because the EditText field and the UI hasn't been created yet(from what it seems).
My question is where would be a good place to do this? Is there a function that is called right after the GUI elements are created?
public class MainActivity extends ActionBarActivity
{
private final String FILE_NAME = "awayReply";
private EditText myEditMessage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
protected void onStart()
{
String message = readMessage();
myEditMessage = (EditText)findViewById(R.id.edit_message);
if(myEditMessage != null)
{
myEditMessage.setText(message, TextView.BufferType.EDITABLE);
}
}
XML Layout:
<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:orientation="horizontal"
android:paddingBottom="16dp"
android:paddingTop="16dp" >
<EditText
android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/lbl_message"
android:inputType="textImeMultiLine" />
<Button
android:id="#+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/edit_message"
android:onClick="updateMessage"
android:text="#string/lbl_update" />
<ToggleButton
android:id="#+id/toggle_away"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/lbl_enable"
android:layout_alignBottom="#+id/lbl_enable"
android:layout_toRightOf="#+id/edit_message"
android:textOff="Disabled"
android:textOn="Enabled"
android:onClick="toggleEnabled" />
</RelativeLayout>
You can't set your text in a TextView until you inflate your layout with
setContentView(R.layout.main_activity);
in the Activity's OnCreate
Once that happens you can do:
EditText editText = (EditText)findViewById(R.id.myEditText)
Full Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // this needs to happen first
EditText editText = (EditText)findViewById(R.id.myEditText)
editText.setText("my text", TextView.BufferType.EDITABLE); // <-- needs that second parameter
}
Edit: updated for EditText instead of TextView
I think I figured out my problem. I need to do this work in the PlaceholderFragment where onCreateView is defined. When I call findviewbyid here it dosen't return null.

"Unfortunately, <App Name> has stopped." Common unexplained Error

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

Categories