I'm new to android and am currently attempting to create a simple application which calculates the area of a rectangle.
When the calculation is performed, the result is shown on the TextView specified.
This is my current code for calculating the area of the rectangle:
package org.me.myandroidstuff;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.app.Activity;
import android.os.Bundle;
public class CalculateRectangleArea2Activity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText length = (EditText) findViewById(R.id.txtLength);
EditText width = (EditText) findViewById(R.id.txtWidth);
TextView result = (TextView) findViewById(R.id.lblResult);
Button calculate = (Button) findViewById(R.id.btnCalculate);
calculate.setOnClickListener(this);
}
public void onClick(View v){
EditText length = (EditText) findViewById(R.id.txtLength);
EditText width = (EditText) findViewById(R.id.txtWidth);
calculateArea(length.getText().toString(), width.getText().toString());
}
private void calculateArea(String clength, String cwidth){
TextView result = (TextView) findViewById(R.id.lblResult);
int area = Integer.parseInt(clength)*Integer.parseInt(cwidth);
result.setText(area);
}}
Here is my main.xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/txtLength"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"/>
<EditText
android:id="#+id/txtWidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"/>
<TextView
android:id="#+id/lblResult"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnCalculate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
When clicking the button to calculate, the application has the error "The application calculateRectangleArea2 has stopped unexpectedly. Please try again."
I believe this has something to do with NullPointerException, though attempting to trace the error through logCat and breakpoints hasn't helped.
Any help would be hugely appreciated :), thanks!
Try using:
result.setText(String.valueOf(area));
instead of:
result.setText(area);
setText() expects a String or CharSequence argument, while you're passing it an int. This is likely causing your crash.
Also, you don't need to get a reference to each View over and over again. Assigning them once to an instance variable in onCreate() is enough.
Related
I have a weather app that requires you to take the text from a edit text field and display it in a text view, I'm trying to make it so when I enter a place it will generate random weather for them along with displaying their input.
I haven't tried much apart from examples online as I recently started learning android development.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
/**
* Implementation for the main activity
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// member variable for the user provided location
private String location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the Get Forecast button
Button btnGetForecast = (Button) findViewById(R.id.btnGetForecast);
// set the click listener to the btnGetForecast Button
btnGetForecast.setOnClickListener(this);
EditText loc = findViewById(R.id.etLocationInput);
location = loc.getText().toString();
}
#Override
public void onClick(View view) {
// view is the View (Button, ExitText, TextView, etc) that was clicked
// if it was the btnGetForecast
if (view.getId() == R.id.btnGetForecast){
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvTitle" />
<TextView
android:id="#+id/tvInstructions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter a location below for the forecast" />
<EditText
android:id="#+id/etLocationInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="#+id/btnGetForecast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Forecast" />
<TextView
android:id="#+id/tvLocationDisplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="The weather in " />
</LinearLayout>
I expect the app to show input from user and display it in text view
This line in your onCreate: 'location = loc.getText().toString()' will only get the current text in loc, which at onCreate will be an empty string.
You should look into TextWatcher: https://developer.android.com/reference/android/text/TextWatcher. This will allow you to get a callback when the text of loc changes and you can then carry out your weather generation.
Well, all you need to do is to add this code in onClick method:
#Override
public void onClick(View view) {
// view is the View (Button, ExitText, TextView, etc) that was clicked
// if it was the btnGetForecast
if (view.getId() == R.id.btnGetForecast){
String text = loc.getText().toString();
yourTextView.setText(text);
}
}
And don't forget to make view variables global, so you could access them outside onCreate method, without using findViewById() again.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView yourTextView;
private EditText loc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the Get Forecast button
Button btnGetForecast = (Button) findViewById(R.id.btnGetForecast);
// set the click listener to the btnGetForecast Button
btnGetForecast.setOnClickListener(this);
loc = findViewById(R.id.etLocationInput);
yourTextView = findViewById(R.id.tvLocationDisplay);
}
...
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
I cannot figure out how to correctly initialize a button (button) I'm trying to create. The button stays null which in turn causes a NullPointerException on the line below it.
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SetCounter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_counter);
//The code when the setButton is clicked.
//Todo 1: define the setButton and create its setOnClickListener. inside it past the following code:-
//On clicking the button the value of counterValueText should be sent to the MainActivity and it should be called.
final Button button = (Button) findViewById(R.id.countButton);
button.setOnClickListener(new View.OnClickListener() { //exception occurs on this line
public void onClick(View v) {
EditText counterValueText = (EditText) findViewById(R.id.counterValueText);
int number = Integer.parseInt(counterValueText.getText().toString());
Intent activityChangeIntent = new Intent(SetCounter.this, MainActivity.class);
//Todo 2: use putExtra("Value",number); to pass values to the MainActivity.
activityChangeIntent.putExtra("Value", number);
startActivity(activityChangeIntent);
}
});
}
}
the error occurs with the line
button.setOnClickListener(new View.OnClickListener() {
but I believe the error is actually in this line
final Button button = (Button) findViewById(R.id.countButton);
Finally, I have another class, MainActivity, in which I declare countButton which looks like this
final Button countButton = (Button) findViewById(R.id.countButton);
Added XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="***.*****.******.lab11skeletontwo.SetCounter">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_adddoc"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mishra.sripath.wecareforuclient.Adddoc">
<Button
android:id="#+id/setButton"
android:layout_width="88dp"
android:layout_height="48dp"
android:layout_marginStart="140dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="400dp"
android:text="Set" />
<EditText
android:id="#+id/counterValueText"
android:layout_width="215dp"
android:layout_height="46dp"
android:ems="10"
android:inputType="number"
android:hint="Enter Value of Counter"
android:layout_marginStart="70dp"
android:layout_marginLeft="70dp"
android:layout_marginTop="230dp" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
Change id of the button from #+id/setButton to #+id/countButton in your xml
<Button
android:id="#+id/setButton"
android:layout_width="88dp"
android:layout_height="48dp"
android:layout_marginStart="140dp"
android:layout_marginLeft="140dp"
android:layout_marginTo
Here is my MainActivity.java code :
package com.dg.buttontest3;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("dg","button was clicked");
}
}
And here is the activity_main.xml code :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="18dp"
android:text="Button" />
</LinearLayout>
I am getting the following error while running this code on Eclipse ADT : button1 cannot be resolved or is not a field.
I don't understand what is wrong with my code. Please help.
You haven't posted your XML code, but as this code seems to be working properly:
button = (Button)findViewById(R.id.button1);
I'd guess that in your activity_main.xml you never create something called button1, or that you don't use the #+id/ prefix.
It should look something like:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button1"/>
Just realised something else, you need to change your LinearLayout opening tag so it has a >.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
That might cause the button to never properly be recognised.
I have a simple Activity/ LinearLayout combination that has two buttons and changes the background colour when each button is clicked. The code is as below
It appears to me that there is a lot of high-level duplication of code. For example, I should not need to define and make variables out of the buttons and the LinearLayout background in my Java file. When I express my intention to couple them, I should be getting them automatically
So, lines like btnBlue = (Button) findViewById(R.id.btnBlue); should not be necessary. A good framework should allow me to use some conventions (like give me a Java variable btnBlue if my resource file #+id/ resource is named as btnBlue, etc
Where can I find a framework that achieves these for me in Android programming?
Thanks
Layout 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"
android:background="#ff000000"
android:weightSum="1"
android:id="#+id/background">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Linear Layout Tutorial"
android:textColor="#ff33ff"
android:textSize="32sp"
/>
<Button
android:id="#+id/btnGreen"
android:layout_width="177dp"
android:layout_height="wrap_content"
android:text="Change to Green"
android:layout_weight="0.07" />
<Button
android:id="#+id/btnBlue"
android:layout_width="400sp"
android:layout_height="wrap_content"
android:text="Change12 to Blue"
android:layout_weight="0.19" />
</LinearLayout>
Activity Java code
package com.example.xxx.testandroid;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.renderscript.Sampler;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private final String TAG = "TKT";
LinearLayout background;
Button btnGreen, btnBlue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.som_linear);
Log.d(TAG, "onCreate");
background = (LinearLayout) findViewById(R.id.background);
btnBlue = (Button) findViewById(R.id.btnBlue);
btnGreen = (Button) findViewById(R.id.btnGreen);
btnGreen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// click button code here
background.setBackgroundColor(Color.parseColor("#00ff00"));
}
});
btnBlue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// click button code here
background.setBackgroundColor(Color.parseColor("#006699"));
}
});
}
}
ButterKnife by Jake Wharton seems a good solution for your problem.
I have a simple jokes application. When you press the button you get new joke. If the previous one was bigger than the screen you can scroll it down. If you go down to the bottom and you go to the next joke, you are transfered to the bottom of the newly generated joke, but i want it to go to the top, and automatically display the start of the joke. How can i do this ?
I assume it would be done via the java code.
Thank you for your time.
Use the scrollTo(int x, int y) method, i like to have ScrollView around my TextView but i think the same thing will work for a TextView only. hope you understand!
Rolf
Example
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/scroll"
android:layout_width="fill_parent"
android:layout_height="130dp" >
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="long\n\n\n\n\n\n\n\n long\n\n\n\n\n\n\n very text here!" />
</ScrollView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="joke" />
</LinearLayout>
java:
package org.sample.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
public class AutoscrollActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private Button new_joke;
private TextView joke;
private ScrollView scroll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new_joke = (Button) this.findViewById(R.id.button);
new_joke.setOnClickListener(this);
joke = (TextView) this.findViewById(R.id.text);
scroll = (ScrollView) this.findViewById(R.id.scroll);
}
#Override
public void onClick(View v) {
joke.setText("Long\n\n\n\n\n\n\n\n joke \n\n\n\n\n\n\n\nlong joke joke");
scroll.scrollTo(0, 0);
}
}