java - Android app crashes when button is pressed - java

I am trying to get a part of a simple Android app working. I am confused as to why I am getting the error "Unfortunately, this app has stopped working".
Basically, I need the total value to increase when I click on a button based on what value they have. For example coffee adds 2 to the total. Every time I click a button that adds to the total value, the app crashes.
Here is the source code. I have just copied the parts that are specific to this problem.
package com.example.pp.application;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener {
TextView tv01;
Double Total = 0.00;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = (TextView) findViewById(R.id.tv01);
}
#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);
}
public void sendMessage(View view)
{
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
public void addCoffee() {
Total = Total + 2.20;
tv01.setText(""+Total+"");
}
public void addBus() {
Total = Total + 1.90;
tv01.setText(""+Total+"");
}
public void addMilk() {
Total = Total + 1.50;
tv01.setText(""+Total+"");
}
}
And here is the Manifest:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="#+id/label">
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Coffee"
android:id="#+id/button"
android:onClick="addCoffee"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="42dp" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Bus"
android:onClick="addBus"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Milk"
android:onClick="addMilk"
android:id="#+id/button4"
android:layout_below="#+id/button3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:onClick="sendMessage"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/button5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="------------------"
android:id="#+id/tv01"
android:layout_alignRight="#+id/button"
android:layout_alignEnd="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Total"
android:id="#+id/textView"
android:layout_toStartOf="#+id/tv01"
android:layout_toLeftOf="#+id/tv01" />

Instead of public void addCoffee() your onClick method definition should look like public void addCoffee(View v), where v is the widget you clicked on (in this case the Button). Take the same approach when updating other onClick methods. This requirement applies only to callbacks defined via android:onClick attribute in XML layout.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = (TextView) findViewById(R.id.tv01);
public void addCoffee(View v) {
Total = Total + 2.20;
tv01.setText(""+Total+"");
}
}
and continue with another function with same way

Since you haven't posted the stack trace of the LogCat, I have no way of telling when in the code your error has been.
But it's likely to have occured before. These links contain similar stances and documentations about exceptions.
My Android App Keeps Crashing
https://developers.google.com/analytics/devguides/collection/android/v4/exceptions
https://developer.android.com/distribute/essentials/optimizing-your-app.html
Android App Crashes on Button Click

Related

application is crashing when pressing button [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
number format exception
(2 answers)
Closed 6 years ago.
Hello everyone i'm new here so this is my first post
I want to build my first android app and that would be a GPA calculator to be exact but every time I press the calculate button the app crashes I use android studio and here is the java code
package com.example.mac.gpacalculator;
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.EditText;
import android.widget.TextView;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
TextView result;
EditText grade1;
EditText grade2;
EditText grade3;
EditText grade4;
EditText grade5;
#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();
}
});
result=(TextView) findViewById(R.id.total);
grade1=(EditText)findViewById(R.id.num1);
grade2=(EditText)findViewById(R.id.num2);
grade3=(EditText)findViewById(R.id.num3);
grade4=(EditText)findViewById(R.id.num4);
grade5=(EditText)findViewById(R.id.num5);
final Button calcbtn= (Button) findViewById(R.id.calc);
calcbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
double c1 = Float.parseFloat(grade1.getText().toString());
c1=convert(String.valueOf(grade1));
double c2 = Float.parseFloat(grade2.getText().toString());
c1=convert(String.valueOf(grade2));
double c3 = Float.parseFloat(grade3.getText().toString());
c1=convert(String.valueOf(grade3));
double c4 = Float.parseFloat(grade4.getText().toString());
c1=convert(String.valueOf(grade4));
double c5 = Float.parseFloat(grade5.getText().toString());
c1=convert(String.valueOf(grade5));
double c6=calculation(c1,c2,c3,c4,c5);
result.setText((int) c6);
}
});
}
#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;
}
public static double convert(String grade)
{
double a=0.0;
//checking the conditions
if(grade.equalsIgnoreCase("A"))
{
a=4.0;
}
if(grade.equalsIgnoreCase("A-"))
{
a=3.7;
}
if(grade.equalsIgnoreCase("B+"))
{
a=3.3;
}
else if(grade.equalsIgnoreCase("B"))
{
a=3.0;
}
if(grade.equalsIgnoreCase("B-"))
{
a=2.7;
}
if(grade.equalsIgnoreCase("C+"))
{
a=2.3;
}
else if(grade.equalsIgnoreCase("C"))
{
a=2.0;
}
if(grade.equalsIgnoreCase("C-"))
{
a=1.7;
}
if(grade.equalsIgnoreCase("D+"))
{
a=1.3;
}
else if(grade.equalsIgnoreCase("D"))
{
a=1.0;
}
else if(grade.equalsIgnoreCase("F"))
{
a=0.0;
}
return a;
}
public static double calculation(double c1, double c2, double c3, double c4, double c5)
{
double operation;
operation=(c1+c2+c3+c4+c5)/5;//calculating the GPA
return operation;
}
#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);
}
}
and here is the XML
<?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/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.mac.gpacalculator.MainActivity"
tools:showIn="#layout/activity_main">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num4"
android:layout_below="#+id/num3"
android:layout_alignStart="#+id/num3"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:hint="Grade"
android:inputType="text" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num5"
android:layout_below="#+id/num4"
android:layout_alignStart="#+id/num4"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:hint="Grade"
android:inputType="text" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num2"
android:layout_below="#+id/num1"
android:layout_alignStart="#+id/num1"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:hint="Grade"
android:inputType="text" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num3"
android:inputType="text"
android:textAlignment="center"
android:hint="Grade"
android:layout_below="#+id/num2"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:layout_alignStart="#+id/num2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num1"
android:hint="Grade"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:layout_marginTop="49dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="text" />
<Button
android:text="CALCULATE"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calc"
android:layout_marginTop="24dp"
android:layout_below="#+id/num5"
android:layout_centerHorizontal="true"
android:onClick="calculation"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:id="#+id/total"
android:hint="0"
android:layout_below="#+id/calc"
android:layout_centerHorizontal="true"
android:textSize="50sp" />
</RelativeLayout>
Also where can i learn more about android development can you recommend me some resources like books, websites, etc. that would me much appreciated.
Thanks in advance.
oh sorry I didn't include the error message
FATAL EXCEPTION: main
Process: com.example.mac.gpacalculator, PID: 2327
java.lang.NumberFormatException: empty String
at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1071)
at java.lang.Float.parseFloat(Float.java:459)
at com.example.mac.gpacalculator.MainActivity$2.onClick(MainActivity.java:51)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
You have to have Button btn = (Button) findViewById(R.id.button); otherwise you will throw a NullPointerException. Check the android monitor to see if that matches the error there.
You have added android:onClick="calculation" in your XML <Button>tag so define a method called calculation which accepts view in your code ..
or simply use calcbtn.setOnClickListener... in your code and remove android:onClick="calculation" from the button tag
Don't use Both android:onClick="calculation and view.setOnClick.. for a same View..
There is no id called fab in your XML so add a FloatingActionButton and give that id to it or comment FloatingActionButton fab ....});
I see multiple error here:
As answered by #charuka, you have added a method in your button android:onClick="calculation, which couldn't be found by android and causes crash.
you are trying to parse EditText into String, which is not String, here: convert(String.valueOf(grade1));, change it to convert(grade1.getText().toString());

java.lang.IllegalStateException: Could not find method

I think that is a dumb error, and I am new to programming. I was making an app to learn: there are 2 radio buttons to choose what text show in an hidden TextView, 2 check box to choose the background and text color of the TextView and a button, that do a check of the check box and the radio buttons and print the text in the TextView. But when in the emulator I try to click something, the app crashes, and the logcat says that it can't find the id and the onClick. Why do I get this?
The program:
package com.bauapp.lory.bauapp;
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.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
import android.graphics.Color;
public class MainActivity extends AppCompatActivity {
#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();
}
});
}
#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);
}
public void cambiaTesto (View v) {
TextView baubau = (TextView) findViewById(R.id.bauText);
RadioButton bau1 = (RadioButton) findViewById(R.id.bauRadio1);
RadioButton bau2 = (RadioButton) findViewById(R.id.bauRadio2);
CheckBox testoRosso = (CheckBox)findViewById(R.id.c1);
CheckBox sfondoGiallo = (CheckBox)findViewById(R.id.c2);
if(bau1.isChecked()) {
baubau.setText("BAU");
}
else
if (bau2.isChecked()) {
baubau.setText("BAUUUUUUU");
}
if(testoRosso.isChecked())
baubau.setTextColor(Color.RED);
else
baubau.setTextColor(Color.BLACK);
if (sfondoGiallo.isChecked())
baubau.setBackgroundColor(Color.YELLOW);
else
baubau.setBackgroundColor(Color.WHITE);
}
}
The XML:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bauapp.lory.bauapp.MainActivity"
tools:showIn="#layout/activity_main">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="43dp">
<TextView
android:layout_width="342dp"
android:layout_height="191dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/bauText"
android:layout_gravity="center_horizontal|bottom"
android:onClick="baubau" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testo rosso"
android:id="#+id/c1"
android:layout_gravity="left|center_vertical"
android:onClick="testoRosso"
android:checked="false"
android:clickable="true" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sfondo giallo"
android:id="#+id/c2"
android:layout_gravity="right|center_vertical"
android:onClick="sfondoGiallo"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAU BAU?"
android:id="#+id/bauButton"
android:layout_gravity="right|top"
android:onClick="cambiaTesto" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|top">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAU"
android:id="#+id/bauRadio1"
android:layout_gravity="left|top"
android:onClick="bau1"
android:checked="false"
android:clickable="true" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAUUUUUUU"
android:id="#+id/bauRadio2"
android:layout_gravity="left|top"
android:onClick="bau2"
android:checked="false"
android:clickable="true" />
</RadioGroup>
</FrameLayout>
And the logcat:
http://textuploader.com/5blrn
(I leave an external link because it doesn't paste correctly for a bug in stackoverflow).
The crash logcat is the same for all the other buttons, but, obviously, change the ID and the OnClick.
Sorry for my bad English.
My suggestion would be to remove android:onClick=... from your RadioButtons, and instead use onCheckedChangeListener on the RadioGroup and then determine which RadioButton was checked and then do whatever you need to do. Your code changes are then as follows:
<RadioGroup
android:id="#+id/bauRadioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|top">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAU"
android:id="#+id/bauRadio1"
android:layout_gravity="left|top"
android:checked="false"
android:clickable="true" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAUUUUUUU"
android:id="#+id/bauRadio2"
android:layout_gravity="left|top"
android:checked="false"
android:clickable="true" />
</RadioGroup>
Then in your MainActivity onCreate you add this code:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.bauRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.bauRadio1){
//radio button bauRadio1 was clicked
baubau.setText("BAU");
}
else if(checkedId == R.id.bauRadio2 ){
//radio button bauRadio2 was clicked
baubau.setText("BAUUUUUUU");
}
}
});
//The rest of your code ...
Please give this a try and let us know if this helps.
As already suggested, How to set On click listener on the Radio Button in Android is a good example for this.
The Radio Button needs a method to handle its onClick event.
You have given the onClick method as android:onClick="bau1" for android:id="#+id/bauRadio1", but the MainActivity class needs to implement the bau1 method.
Hence the IllegalStateException of cannot find method bau1.
Check this link for more details on RadioButton and Responding to Click Events:
https://developer.android.com/guide/topics/ui/controls/radiobutton.html
Ciao Lorenzo,
I noticed at the end of your XML file: you forgot to close the RelativeLayout with the proper closetag </RelativeLayout> .
It's only a copy-paste mystake or your xml file is incorrect?
I give you a tip. Avoid filling the xml file with too many layout when with a few changes you can get the same view with fewer elements.
In your example the FrameLayout is completely useless.
EDIT: In your layout i didn't see the <FloatingActionButton> .
Make sure to add the support library dependence in your build.grandle file:
Remember to change the version based on your api target *
compile 'com.android.support:design:23.2.1'
After that you can add the FAB in you layout like this:
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:src="#drawable/my_icon" />
Either create
public void bau1(View view){
//Perform some code
}
In your MainActivity
OR
Remove android:onClick="bau1" from XML
Specially I prefer using OnCheckedChangeListener instead of onClick in case of RadioGroup like shown here.

unfortunately app has stopped , android

i have given the code here . and when i run it in genymotion it just stops working. please help .
i dont see any display in logcat also . it remains blank and the emulator only shows an error that is "unfortulately, SharedprefrencEexample has stoped working. and the app dont even starts. so i dont get any clue of what might be the error in this code .
here i have used the reference creation at the start and i think it might be the error. so please do see the code and help me.
thanks.
Main_Activity
package com.example.sharedprefrenceexample;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText name,phone,email;
Button submit;
Intent intent;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText) findViewById(R.id.editText1);
phone=(EditText) findViewById(R.id.editText2);
email=(EditText) findViewById(R.id.editText3);
submit=(Button) findViewById(R.id.button1);
submit.setText("#string/button_name_activity_one");
name.setHint("name");
phone.setHint("phone");
email.setHint("email id");
sharedPreferences=getSharedPreferences("#string/database_name", MODE_PRIVATE);
editor=sharedPreferences.edit();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
editor.putString("name", name.getText().toString());
editor.putString("phone", phone.getText().toString());
editor.commit();
intent=new Intent(MainActivity.this,Secondactivity.class);
intent.putExtra("email", email.getText().toString());
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);
}
}
activity_main.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sharedprefrenceexample.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:ems="10"
android:inputType="numberPassword" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText2"
android:ems="10"
android:inputType="textEmailAddress" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="#string/button_name_activity_one" />
</RelativeLayout>
secondactivity
package com.example.sharedprefrenceexample;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Secondactivity extends Activity {
TextView result;
SharedPreferences sharedPreferences;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondactivity);
result=(TextView) findViewById(R.id.textView1);
sharedPreferences=getSharedPreferences("database", MODE_PRIVATE);
String res = null;
res=res+sharedPreferences.getString("name", "no name");
res=res+sharedPreferences.getString("phone", "no phone");
intent=getIntent();
res=res+intent.getStringExtra("email");
result.setText(res);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.secondactivity, 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);
}
}
activity_secondactivity.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sharedprefrenceexample.Secondactivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
submit.setText("#string/button_name_activity_one");
// (...)
sharedPreferences=getSharedPreferences("#string/database_name", MODE_PRIVATE);
That syntax is only valid in XML. In Java code, to use a string reference you should use
submit.setText(R.string.button_name_activity_one);
So fix those string references and it should work.
More info: String resources # Android Developers

Why isnt my implementation of OnClickListener working?

Nothing inside of my OnClick method is working as far as I can tell and I have no idea why. Im using an emulator to test out the code. The page loads properly and there are two buttons. As seen in the code, I'd log to do an info log saying two different things depending on which button was pressed. I also tried adding android:clickable="true" in the layout. Heres the code:
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class UserOnboardActivity extends ActionBarActivity implements OnClickListener {
private Button selectMaleAvtr;
private Button selectFemaleAvtr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_onboard);
selectMaleAvtr = (Button)findViewById(R.id.select_male_avatar_btn);
selectFemaleAvtr = (Button)findViewById(R.id.select_female_avatar_btn);
selectMaleAvtr.setOnClickListener(this);
selectFemaleAvtr.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_user_onboard, 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 v) {
Log.i("whaaat", v.toString());
Log.i("whaaat", "hello");
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
.show();
if(v==selectMaleAvtr) {
Log.i("UserOnboardActivity", "male avatar button pressed");
} else if (v==selectFemaleAvtr) {
Log.i("UserOnboardActivity", "female avatar button pressed");
}
}
}
XML:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.incubatorcle.dinahealth.UserOnboardActivity">
<TextView android:text="#string/select_avatar_user_onboard" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/select_avatar_tv"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:soundEffectsEnabled="true"
android:gravity="center_horizontal"
android:textSize="20sp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/select_avatar_btns_lin_lay">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="#+id/select_female_avatar_btn"
android:layout_alignTop="#+id/select_male_avatar_btn"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:id="#+id/select_male_avatar_btn"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</LinearLayout>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I guess the issue is you have to look for the viewids instead of the view itself:
You can either do:
public void onClick(View v) {
Log.i("whaaat", v.toString());
Log.i("whaaat", "hello");
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
.show();
if(v.getId()==R.id.selectMaleAvtr) {
Log.i("UserOnboardActivity", "male avatar button pressed");
} else if (v.getId()==R.id.selectFemaleAvtr) {
Log.i("UserOnboardActivity", "female avatar button pressed");
}
}
OR
public void onClick(View v) {
switch (v.getId()) {
case R.id.selectMaleAvtr:
// Things you want do
break;
case R.id.selectFemaleAvtr:
// Things you want to do
break;
default:
break;
}
}
The problem was I was using a different activity to open the view so the code in this activity was never getting loaded. I solved it by using an intent and then startActivity to solve the problem.

How can i remove a imageView when i run my program on smaller devices

So i have this application, and i want to remove the logo when i run it on smaller devices sine its pressing the rest of the ui and making things look strange. It is the first application im making, so not sure how to get this done.
Here is my code for the main_activity:
package no.flammbaert.flammbaert;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener{
ImageButton btn_settings;
ImageButton btn_voksen;
ImageButton btn_barn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
#Override
public void onClick(View v) {
if(v.getId() == btn_voksen.getId()){
Intent i = new Intent(MainActivity.this, VoksenActivity.class);
startActivity(i);
}
if(v.getId() == btn_settings.getId()){
Intent i = new Intent(MainActivity.this, Preferences.class);
startActivity(i);
}
if(v.getId() == btn_barn.getId()){
Intent i = new Intent(MainActivity.this, BarnActivity.class);
startActivity(i);
}
}
public void Init(){
btn_settings = (ImageButton)findViewById(R.id.btn_settings);
btn_voksen = (ImageButton) findViewById(R.id.btn_voksen);
btn_barn = (ImageButton) findViewById(R.id.btn_barn);
btn_settings.setOnClickListener(this);
btn_voksen.setOnClickListener(this);
btn_barn.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_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) {
Intent i = new Intent(MainActivity.this, Preferences.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is the xml file:
<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:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#drawable/bg_blue_sky">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativeLayout"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_above="#+id/btn_settings">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_barn"
android:background="#drawable/knapp_1"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="10dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_voksen"
android:background="#drawable/knapp_2"
android:layout_below="#+id/btn_barn"
android:layout_alignLeft="#+id/btn_barn"
android:layout_alignStart="#+id/btn_barn"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:background="#drawable/logo_flammbaert"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"/>
</RelativeLayout>
<ImageButton
android:id="#+id/btn_settings"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/gear"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:scaleType="fitXY"/>
</RelativeLayout>
Thanks for help.
I think you can check this way weather the app is running in a small or large screen using the below code snippet.
Configuration config = getResources().getConfiguration();
if((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_SMALL)
{
//small screen
// Here you can remove/invisible the image view by using
imageView.setVisible(View.GONE);
}
This can be a aproaching to what you need:
First obtain the size of the screen take a look to this post --> Get screen dimensions in pixels
Once you get the size, you have tos et your "small screen size", and make the Imageview "dissapear.
imageview = (ImageView)findViewByID(R.id.imageView)
imageview.setVisivility(View.GONE);
Take care because there are 2 ways to make "dissapear" a view:
View.GONE This view is invisible, and it doesn't take any space for
layout purposes. View.INVISIBLE This view is invisible, but it still
takes up space for layout purposes.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
String screenSize = dm.widthPixels
+ " "
+ dm.heightPixels;
Now if you get the smaller device resolution simply use
setVisivility(View.GONE);
But I suggest to use
Supporting Different Screen Sizes

Categories