Problems to use Views on Android - java

I'm trying to declare buttons and EditTexts in the OnCreate() function, calling the function findViewById(). But when I try to use the button in the emulator the application fails. When I use the findViewById() in the function of the treatment of the event (I used android:onClick because the treatment in java wasn't working either) the aplication worked normally. Why I can't only use the findViewById() one time, inside the onCreate?
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
status.setText("HA");
}
});
Button b2 = (Button) findViewById(R.id.b2);
b2.setActivated(false);
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Display any data about the persons
}
});
Button b3 = (Button) findViewById(R.id.b3);
b3.setActivated(false);
b3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Start the sensors lecture
}
});
Button b4 = (Button) findViewById(R.id.b4);
b4.setActivated(false);
b4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Execute the music
}
});
}
public void treatment_button(View v){
status = (EditText) findViewById(R.id.text);
status.setText("Connect");
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}

Inside oncreate() you have again define Button b1 like:
Button b1 = (Button) findViewById(R.id.b1);
Change it to:
b1 = (Button) findViewById(R.id.b1);
As you are creating the Button variable inside onCreate(),it will not work outside that method.So use the global reference variable of the Button that you have created.

try this hope it's worked:
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity {
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
status.setText("HA");
}
});
b2 = (Button) findViewById(R.id.b2);
b2.setActivated(false);
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Display any data about the persons
}
});
b3 = (Button) findViewById(R.id.b3);
b3.setActivated(false);
b3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Start the sensors lecture
}
});
b4 = (Button) findViewById(R.id.b4);
b4.setActivated(false);
b4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Execute the music
}
});
}
public void treatment_button(View v){
status = (EditText) findViewById(R.id.text);
status.setText("Connect");
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}

Related

Issue with a simple app

I'm new in coding, and I was trying to make a simple app that make a subtraction from 2 variable, but when I click the button to calculate, the app crashes... Can someone help me finding the problem in the code? (Android Studio)
Here's the code:
package apps.ste.resto;
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.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import static apps.ste.resto.R.id.risultato;
public class MainActivity extends AppCompatActivity {
TextView importo;
TextView conto;
TextView risultato;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
TextView risultato = (TextView) findViewById(R.id.textView);
TextView importo = (TextView) findViewById(R.id.editText);
TextView conto = (TextView) findViewById(R.id.editText2);
Button bottone = (Button) findViewById(R.id.button);
bottone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result();
}
});
}
public void result(){
float result = Float.parseFloat(importo.getText().toString()) - Float.parseFloat(conto.getText().toString());
risultato.setText(Float.toString(result));
}
#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_main, 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);
}
I think you are getting null value for getText()..
SO you can try this :
public void result(){
boolean digitsOnly1 = TextUtils.isDigitsOnly(importo.getText()+"");
boolean digitsOnly2 = TextUtils.isDigitsOnly(conto.getText()+"");
if(digitsOnly1 && digitsOnly2){
float result = Float.parseFloat(importo.getText().toString()) - Float.parseFloat(conto.getText().toString());
risultato.setText(result+""));
}else{
risultato.setText("Please provide inputs");
}
}

Android Studio Java code

I'm trying to replace a part of the text after clicking the bottom but I can't make it work. When I click the bottom without entering a name the message should say "Hello Username", and if I enter a name the "Username" should be replace by the name. Here is the code so far. Thanks
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class HelloAndroid extends AppCompatActivity implements OnClickListener {
private EditText name;
private TextView display;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_android);
name = (EditText) findViewById(R.id.name);
display = (TextView) findViewById(R.id.display);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#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_hello_android, 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);
}
#Override
public void onClick(View view) {
if (button == view) {
String message = "Hello, Username " + name.getText().toString() + "!";
if (button == view) {
String username = "Hello " + name.getText().toString() + "";
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
display.setText(message);
}
}
}
}
You are enable to do this because may be you are not getting click here . Here is my code change it .
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class HelloAndroid extends AppCompatActivity implements View.OnClickListener {
private EditText name;
private TextView display;
private Button button;
String message ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy);
name = (EditText) findViewById(R.id.name);
display = (TextView) findViewById(R.id.display);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button :
if (name.getText().toString().isEmpty())
{
message = "Hello username" ;
}
else {
message = "Hello "+name.getText().toString() ;
}
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
display.setText(message);
break;
}
}
}

android app, Java - Overflow Menu Error and it's not displaying in the action bar

I did not expect an error to come up but the 3-dot ActionBar menu is not displaying and I am getting an unexpected error. I am not sure where I went wrong in my code.
Please help,
thanks in advance!
MainActivity.java
package com.example.it5.foothillers;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
Button button2;
Button button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Display app icon in the ActionBar
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.ic_launcher);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(this);
}
private void buttonClick() {
startActivity(new Intent("it5.foothillers.news"));
}
private void button2Click() {
startActivity(new Intent("it5.foothillers.sports"));
}
private void button3Click() {
startActivity(new Intent("it5.foothillers.events"));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
buttonClick();
break;
case R.id.button2:
button2Click();
break;
case R.id.button3:
button3Click();
break;
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(MenuItem item) {
int id = item.getItemId();
}
}
You have 3 onCreateOptionsMenu methods. Remove the last 2, you only need the first one with inflater. Also, Override the onOptionsItemSelected method to control the actions.

Android app crashes, due to count down timer?

I have made an app recently and I added a count down timer one day and made a few changes here and there and now when I run the app on my (actual) Galaxy Note 3 it crashes as soon as I hit the Play button below are my LevelOne.java file and my MainActivity.Java file. By the way the logcat shows nothing as if it doesn't realize it crashed.
LevelOne.java
package com.parker.orangedot;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class LevelOne extends ActionBarActivity {
Button myButton;
LevelOne context;
CountDownTimer timer = new CountDownTimer(1500, 1500)
{
#Override
public void onFinish() {
Intent intent = new Intent(context, Scores.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_level_one);
//ass soon as this activity is created, I start my timer.
timer.start();
myButton = (Button) findViewById(R.id.button2);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
timer.cancel();
}});
}
#Override
public void onBackPressed() {
}
public void next(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelTwo.class);
startActivity(intent);
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level_one, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_level_one,
container, false);
return rootView;
}
}
}
MainActivity.java
package com.parker.orangedot;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
public void play(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelOne.class);
startActivity(intent);
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
UPDATE:
When using the emulater for the Galaxy Nexus, pressing "play" does absolutely nothing.

Button does nothing, but why?

I am basically only trying to get R.id.button1 to open up Google in a web browser, not sure whats wrong!
No errors, it just does nothing when pressing the button, I am using the emulator.
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button btn;
#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();
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
}
public void onClick(View v)
{
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
It seems to me your button is in your fragment layout (right?)
then you should handle your button's events in your fragment, not in the activity!
Your onCreate() method should be like this :
#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();
}
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener( new OnClickListener{
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
});
}
The problem is here :
btn.setOnClickListener((OnClickListener) this);
replace it with :
btn.setOnClickListener(this);
And implement View.OnClickListner in order to get the onClick method
public class MainActivity extends ActionBarActivity implements View.OnClickListner {
/*
some code here
*/
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
}
You can also do it like this :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
});
Implement OnClickListner
public class MainActivity extends ActionBarActivity implements OnClickListner {
Button btn;
Define the listener to your button1.
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
use a switch in onClick() method to handle several views:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
break;
default:
//code..
break;
};
}
other way to set the listener to your button:
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener( new OnClickListener{
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}

Categories