I have made updates to this Llama or Duck game (a recreation of an already-existing game) and the app very inconsistently closes out due to an outOfMemory error. I have made multiple attempts to clear up memory such as using addFlags from Intent and researching different solutions and yet the errors keep coming. By the way, this is one of the two screens (essentially identical) that will be constantly recreated throughout the game as the user is playing. The goal is for the user to select which animal is being shown on the screen, and if correct they will keep playing. Any help is appreciated, thank you.
package com.example.ryan.llamaorduck;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class DuckScreen extends AppCompatActivity {
boolean isLlamaScreen = false; //false because this is the Duck screen
int duck_score;
Intent intent;
int screen; // variable used just for finding the next random screen
int pic; //not currently implemented
SharedPreferences pref; //used for storing score
SharedPreferences.Editor editor;
Timer timer; //used to change window if time runs out
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duck_screen);
pref = getApplicationContext().getSharedPreferences("MY_PREF",MODE_PRIVATE);
editor=pref.edit();
duck_score=pref.getInt("tempDuckScore",0);
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
timer.cancel();
//below are my attempts to clear up memory space to make
//the app perform better.
intent = new Intent(DuckScreen.this,GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
};
timer.schedule(timerTask,2000);
}
// user clicked on the llama button.
//method implementation decides if they are correct and either ends the
//game or moves them onto the next random page.
public void llamaClick(View view){
timer.cancel();
if (isLlamaScreen){
Random r = new Random();
screen = r.nextInt(2);
if (screen == 1){ //DUCK
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,DuckScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,LlamaScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
//user clicked on the button indicating that they think the animal is a
//duck. Same idea as method before, testing other button.
public void duckClick(View view){
timer.cancel();
if (!isLlamaScreen){
Random r = new Random();
screen = r.nextInt(2);
if (screen == 1){ //DUCK
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,DuckScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,LlamaScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
public int getDuckScore(){
return duck_score;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.ryan.llamaorduck.DuckScreen">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:src="#drawable/duck"
android:scaleType="centerCrop"
android:id="#+id/duck"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/duck"
android:orientation="vertical"
>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Duck"
android:textSize="40sp"
android:textColor="#ffffff"
android:onClick="duckClick"
/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Llama"
android:textSize="40sp"
android:textColor="#ffffff"
android:onClick="llamaClick"
/>
</RadioGroup>
</RelativeLayout>
ERROR MSG:
04-05 11:57:59.451 6438-6438/com.example.ryan.llamaorduck E/dalvikvm-heap: Out of memory on a 8748016-byte allocation.
04-05 11:57:59.601 6438-6438/com.example.ryan.llamaorduck E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:605)
at android.graphics.Bitmap.createBitmap(Bitmap.java:551)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437)
at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:524)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773)
at android.content.res.Resources.loadDrawable(Resources.java:1940)
at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
at android.widget.ImageView.<init>(ImageView.java:119)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:57)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:53)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:972)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1031)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:668)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.ryan.llamaorduck.DuckScreen.onCreate(DuckScreen.java:28)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Try setting
android:largeHeap="true"
Inside of the <application> tag of your manifest; this will launch the application with more memory allocated to the heap.
Android Docs.
Note: Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.
If you are gettin an OOM, you have a fundamental issue with your code - this is simply a bandaid.
Related
i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_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.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm attempting to create an application that keeps track of statistics throughout your golf game and generates a tip catered to your golf game if need be. I am keeping track of the holes by putting them into an array list. I found that you can pass objects between activities using googles GSON, I followed the tutorial but I feel that this passing of the array between activities is what ultimately is causing the NPE, but I am not sure.
Here is the full stack trace
11-04 11:06:02.218: E/Trace(774): error opening trace file: No such file or directory (2)
11-04 11:06:02.949: D/dalvikvm(774): GC_FOR_ALLOC freed 77K, 2% free 10958K/11143K, paused 46ms, total 48ms
11-04 11:06:03.048: D/dalvikvm(774): GC_CONCURRENT freed 168K, 3% free 11241K/11527K, paused >25ms+5ms, total 65ms
11-04 11:06:03.058: D/dalvikvm(774): WAIT_FOR_CONCURRENT_GC blocked 29ms
11-04 11:06:03.448: D/gralloc_goldfish(774): Emulator without GPU emulation detected.
11-04 11:06:06.168: D/AndroidRuntime(774): Shutting down VM
11-04 11:06:06.168: W/dalvikvm(774): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-04 11:06:06.208: E/AndroidRuntime(774): FATAL EXCEPTION: main
11-04 11:06:06.208: E/AndroidRuntime(774): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.testapp/com.example.testapp.StatActivity}: java.lang.NullPointerException
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.os.Looper.loop(Looper.java:137)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.reflect.Method.invoke(Method.java:511)
11-04 11:06:06.208: E/AndroidRuntime(774): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-04 11:06:06.208: E/AndroidRuntime(774): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 11:06:06.208: E/AndroidRuntime(774): at dalvik.system.NativeStart.main(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774): Caused by: java.lang.NullPointerException
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.Activity.findViewById(Activity.java:1825)
11-04 11:06:06.208: E/AndroidRuntime(774): at com.example.testapp.StatActivity.<init>(StatActivity.java:38)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.Class.newInstanceImpl(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774): at java.lang.Class.newInstance(Class.java:1319)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-04 11:06:06.208: E/AndroidRuntime(774): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-04 11:06:06.208: E/AndroidRuntime(774): ... 11 more
11-04 11:06:06.388: D/dalvikvm(774): GC_CONCURRENT freed 266K, 4% free 11366K/11719K, paused >17ms+64ms, total 142ms
11-04 11:11:06.349: I/Process(774): Sending signal. PID: 774 SIG: 9
and the relevant activities
StatActivity
package com.example.testapp;
import java.util.ArrayList;
import java.util.List;
import com.example.testapp.StatActivity;
import com.example.testapp.CustomOnItemSelectedListener;
import com.example.testapp.R;
import com.google.gson.Gson;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class StatActivity extends Activity implements OnClickListener {
private Spinner driving_spinner;
private Spinner approach_spinner;
private Spinner chipping_spinner;
private Spinner sandshot_spinner;
private Spinner putting_spinner;
private int hole = 1;
private boolean driving_spinner_selected = false;
private boolean approach_spinner_selected = false;
private boolean chipping_spinner_selected = false;
private boolean sandshot_spinner_selected = false;
private boolean putting_spinner_selected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stat);
Button homeButton = (Button) findViewById(R.id.homeButton);
Button helpButton = (Button) findViewById(R.id.helpButton);
Button nextHoleButton = (Button) findViewById(R.id.nextHoleButton);
driving_spinner = (Spinner) findViewById(R.id.drivingSpinner);
approach_spinner = (Spinner) findViewById(R.id.approachSpinner);
chipping_spinner = (Spinner) findViewById(R.id.chippingSpinner);
sandshot_spinner = (Spinner) findViewById(R.id.sandShotSpinner);
putting_spinner = (Spinner) findViewById(R.id.puttingSpinner);
nextHoleButton.setOnClickListener(this);
helpButton.setOnClickListener(this);
homeButton.setOnClickListener(this);
addItemsToDrivingSpinner();
addItemsToChippingSpinner();
addItemsToPuttingSpinner();
addItemsToApproachSpinner();
addItemsToSandShotSpinner();
addListenerOnDrivingSpinnerItemSelection();
addListenerOnChippingSpinnerItemSelection();
addListenerOnPuttingSpinnerItemSelection();
addListenerOnApproachSpinnerItemSelection();
addListenerOnSandShotSpinnerItemSelection();
}
Gson gS = new Gson();
String src = getIntent().getStringExtra("round");
Round round = gS.fromJson(src, Round.class);
// add items into spinner dynamically
public void addItemsToDrivingSpinner() {
List<String> list = new ArrayList<String>();
list.add("Left");
list.add("Right");
list.add("Fairway Hit");
list.add("Par Three");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
driving_spinner.setAdapter(dataAdapter);
}
public void addItemsToApproachSpinner() {
List<String> list = new ArrayList<String>();
list.add("Left");
list.add("Right");
list.add("Short");
list.add("Long");
list.add("Green Hit");
list.add("No Oppurtunity");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
approach_spinner.setAdapter(dataAdapter);
}
public void addItemsToChippingSpinner() {
List<String> list = new ArrayList<String>();
list.add("Yes Up and Down");
list.add("No Up and Down");
list.add("No Oppurtunity");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
chipping_spinner.setAdapter(dataAdapter);
}
public void addItemsToSandShotSpinner() {
List<String> list = new ArrayList<String>();
list.add("Yes Sand Save");
list.add("No Sand Save");
list.add("No Oppurtunity");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sandshot_spinner.setAdapter(dataAdapter);
}
public void addItemsToPuttingSpinner() {
List<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5+");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
putting_spinner.setAdapter(dataAdapter);
}
public void addListenerOnDrivingSpinnerItemSelection() {
driving_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
driving_spinner_selected = true;
}
public void addListenerOnApproachSpinnerItemSelection() {
approach_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
approach_spinner_selected = true;
}
public void addListenerOnChippingSpinnerItemSelection() {
chipping_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
chipping_spinner_selected = true;
}
public void addListenerOnPuttingSpinnerItemSelection() {
putting_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
putting_spinner_selected = true;
}
public void addListenerOnSandShotSpinnerItemSelection() {
sandshot_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
sandshot_spinner_selected = true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.stat, 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);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.homeButton){
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}else if(v.getId() == R.id.helpButton){
Intent intent = new Intent(getApplicationContext(), InstructionsActivity.class);
startActivity(intent);
}else if(v.getId() == R.id.nextHoleButton){
boolean filledIn = false;
if(driving_spinner_selected && chipping_spinner_selected && putting_spinner_selected && sandshot_spinner_selected && approach_spinner_selected)
filledIn = true;
if(filledIn) {
hole++;
round.setStats(String.valueOf(driving_spinner.getSelectedItem()),String.valueOf(putting_spinner.getSelectedItem()),String.valueOf(sandshot_spinner.getSelectedItem()),String.valueOf(chipping_spinner.getSelectedItem()),String.valueOf(approach_spinner.getSelectedItem()),hole);
Intent intent = new Intent(getApplicationContext(), StatActivity.class);
String target = gS.toJson(round);
intent.putExtra("round", target);
if(round.needTip()) {
String tip = round.generateTip();
Toast.makeText(StatActivity.this,
tip,
Toast.LENGTH_LONG).show();
}
startActivity(intent);
}
else {
Toast.makeText(StatActivity.this,
"Please fill in all statistics before continuing.",
Toast.LENGTH_SHORT).show();
}
}
}
}
HomeActivity
package com.example.testapp;
import com.google.gson.Gson;
import android.app.Activity;
import android.content.Intent;
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;
public class HomeActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button startRoundButton = (Button) findViewById(R.id.startRoundButton);
Button homeHelpButton = (Button) findViewById(R.id.homeHelpButton);
homeHelpButton.setOnClickListener(this);
startRoundButton.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.home, menu);
return true;
}
public void onClick(View v)
{
if(v.getId() == R.id.startRoundButton){
Round round = new Round();
Intent i = new Intent(getApplicationContext(),StatActivity.class);
Gson gS = new Gson();
String target = gS.toJson(round);
i.putExtra("round", target);
startActivity(i);
}else if(v.getId() == R.id.homeHelpButton){
Intent intent = new Intent(getApplicationContext(), InstructionsActivity.class);
startActivity(intent);
}
}
#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);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HomeActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".StatActivity"
android:label="#string/title_activity_stat" >
</activity>
<activity
android:name=".InstructionsActivity"
android:label="#string/title_activity_instructions" >
</activity>
</application>
</manifest>
Activity_Stat.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:background="#drawable/here_link"
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.testapp.StatActivity" >
<Spinner
android:id="#+id/puttingSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/approachSpinner"
android:layout_alignLeft="#+id/approachSpinner"
android:entries="#array/puttArr"
android:prompt="#string/putting" />
<Button
android:id="#+id/nextHoleButton"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/next_button_background" />
<Spinner
android:id="#+id/approachSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/sandShotSpinner"
android:layout_alignLeft="#+id/sandShotSpinner"
android:entries="#array/approachArr"
android:prompt="#string/aproach" />
<Spinner
android:id="#+id/sandShotSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/nextHoleButton"
android:layout_alignLeft="#+id/drivingSpinner"
android:layout_marginBottom="19dp"
android:entries="#array/sandShotArr"
android:prompt="#string/sand_shot" />
<Spinner
android:id="#+id/drivingSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/puttingSpinner"
android:layout_centerHorizontal="true"
android:entries="#array/drivingArr"
android:prompt="#string/driving" />
<Button
android:id="#+id/helpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/sandShotSpinner"
android:layout_alignTop="#+id/homeButton"
android:text="#string/help" />
<Button
android:id="#+id/homeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/nextHoleButton"
android:layout_alignParentLeft="true"
android:text="#string/home" />
<Spinner
android:id="#+id/chippingSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/drivingSpinner"
android:entries="#array/chippingArr"
android:prompt="#array/chippingArr" />
</RelativeLayout>
the Home activity is launched upon opening the app (which works) then the stat activity is started when Start round button is clicked and this is when the app stops.
any thoughts or ideas will be helpful. Thank you!
This line
String src = getIntent().getStringExtra("round");
is your problem. When it's invoked, there's no intent to get.
All setup that needs the intent needs to be done inside onCreate(), by which time the intent is available. Your code is being run at construction time, which is too early.
You haven't really provided enough info to determine whether this is what's generating the NPE that you're hitting, but it's certainly going to need fixing even if there's something else wrong too.
I have a custom class that extends DialogPreference. It works perfectly if launched from the Preference menu. I want to be able to launch it from an Activity as well. Below is my DialogPreference class in which I exposed the showDialog() method suggested by this thread. When I call it I get a Null Pointer Exception but haven't been able to figure out why.
The error is thrown at line 27 which is in onBindDialogView() where hText.setText() is called.
package com.jumptuck.recipebrowser;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
// Pop-up dialog used to set and modify host and login credentials
public class HostCredentialsDialogPreference extends DialogPreference {
static final String TAG = "HostCredentialsDialogPreference";
EditText hText, uText, pText;
public HostCredentialsDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_host_credentials);
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
Log.d(TAG,"onBindDialogView");
SharedPreferences sp = getSharedPreferences();
hText.setText(sp.getString("host", ""));
uText.setText(sp.getString("username", ""));
pText.setText(sp.getString("password", ""));
}
#Override
protected View onCreateDialogView() {
// Guide for this technique found at:
// http://alexfu.tumblr.com/post/23683149440/android-dev-custom-dialogpreference
Log.d(TAG,"onCreateDialogView");
View root = super.onCreateDialogView();
hText = (EditText) root.findViewById(R.id.host);
uText = (EditText) root.findViewById(R.id.username);
pText = (EditText) root.findViewById(R.id.password);
return root;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult){
Log.d(TAG,"Clicked Save");
SharedPreferences sp = getSharedPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putString("host", hText.getText().toString());
editor.putString("username", uText.getText().toString());
editor.putString("password", pText.getText().toString());
editor.commit();
}
else {
Log.d(TAG,"Clicked Cancel");
}
}
void show() {
showDialog(null);
}
}
I'm using a "Testing" button try to launch the dialog from another Activity:
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.item_prefs:
startActivity(new Intent(this, PrefsActivity.class));
return true;
case R.id.refresh:
if (credentialsExist()) {
refreshListView();
}
return true;
case R.id.recipe_dir:
startActivity(new Intent(this, RecipeDisplayActivity.class));
return true;
case R.id.testing:
HostCredentialsDialogPreference hc = new HostCredentialsDialogPreference(this, null);
hc.show();
return true;
default:
return false;
}
}
Here are the xml files for my Preference and the Dialog Preference:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<com.jumptuck.recipebrowser.HostCredentialsDialogPreference
android:key="dialog_credentials"
android:title="Server Address and Login"
android:summary="Set Host, Username and Password" />
</PreferenceScreen>
and
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/dialog_hostname_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dialog_hint_uri" />
<EditText
android:id="#+id/host"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri" />
<TextView
android:id="#+id/dialog_username_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dialog_hint_user" />
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<TextView
android:id="#+id/dialog_password_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dialog_hint_password" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:inputType="textPassword" />
</LinearLayout>
And finally the Logcat:
D/RecipeListActivity( 5894): onOptionsItemSelected
D/HostCredentialsDialogPreference( 5894): onCreateDialogView
D/HostCredentialsDialogPreference( 5894): onBindDialogView
D/AndroidRuntime( 5894): Shutting down VM
W/dalvikvm( 5894): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
E/AndroidRuntime( 5894): FATAL EXCEPTION: main
E/AndroidRuntime( 5894): java.lang.NullPointerException
E/AndroidRuntime( 5894): at com.jumptuck.recipebrowser.HostCredentialsDialogPreference.onBindDialogView(HostCredentialsDialogPreference.java:27)
E/AndroidRuntime( 5894): at android.preference.DialogPreference.showDialog(DialogPreference.java:289)
E/AndroidRuntime( 5894): at com.jumptuck.recipebrowser.HostCredentialsDialogPreference.show(HostCredentialsDialogPreference.java:62)
E/AndroidRuntime( 5894): at com.jumptuck.recipebrowser.RecipeListActivity.onOptionsItemSelected(RecipeListActivity.java:192)
E/AndroidRuntime( 5894): at android.app.Activity.onMenuItemSelected(Activity.java:2534)
E/AndroidRuntime( 5894): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:958)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:166)
E/AndroidRuntime( 5894): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
E/AndroidRuntime( 5894): at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
E/AndroidRuntime( 5894): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2859)
E/AndroidRuntime( 5894): at android.widget.AbsListView$1.run(AbsListView.java:3533)
E/AndroidRuntime( 5894): at android.os.Handler.handleCallback(Handler.java:615)
E/AndroidRuntime( 5894): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 5894): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 5894): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 5894): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 5894): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 5894): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 5894): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 5894): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 148): Force finishing activity com.jumptuck.recipebrowser/.RecipeListActivity
W/WindowManager( 148): Failure taking screenshot for (246x410) to layer 21025
W/ActivityManager( 148): Activity pause timeout for ActivityRecord{412097e0 com.jumptuck.recipebrowser/.RecipeListActivity}
I/Choreographer( 281): Skipped 39 frames! The application may be doing too much work on its main thread.
W/ActivityManager( 148): Activity destroy timeout for ActivityRecord{412097e0 com.jumptuck.recipebrowser/.RecipeListActivity}
Anyone idea what I'm doing wrong? Thanks!
The best answer can be found here but I think it needs just a bit of clarification because that answer wrongly suggests two different style declarations for the manifest.
If you want to launch one dialog from an Activity and still be able to launch it form a Preference you just need to create an Activity that launches the Dialog. That Activity can then be launched as an intent in the Preference XML or from another Activity. The trick comes in how you style it. You want to style the Activity as a Dialog. This way the dialog that your Activity launches will looks right. The side effect of this approach is that a floating Action Bar will be show in the middle of the screen behind your Dialog. The fix for that is to use a Dialog style with no ActionBar. I'm using Holo.Light theme so I put this in my AndroidManifest
<activity android:name=".DemoDialogActivity"
android:theme="#android:style/Theme.Holo.Light.Dialog.NoActionBar" />
The other part of the puzzle is to make sure you call finish(); when you're done (It's the last thing I did in the OnClickListener for both of my buttons). If you don't, the dialog will close but the Activity will still be open, leaving a small blank rectangle in the middle of a darkened screen.
Here's a working example of the Activity:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
public class DemoDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater lf = LayoutInflater.from(this);
// This adds XML elements as a custom view (optional):
final View customElementsView = lf.inflate(
R.layout.activity_credentials, null);
AlertDialog alert = new AlertDialog.Builder(this)
// This adds the custom view to the Dialog (optional):
.setView(customElementsView)
.setTitle("This is the Title")
.setMessage("This is the AlertDialog message (optional)")
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// Cancel was clicked; do something
// Close Activity
finish();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// OK was clicked; do something
// Close Activity
finish();
}
}).create();
// Show the dialog
alert.show();
}
}
Launch it programmatically:
Intent launch_dialog = new Intent(getApplicationContext(),
DemoDialogActivity.class);
startActivity(launch_dialog);
Or as a Preference in XML:
<Preference
android:key="demo_dialog"
android:title="Title of item on Prefs screen"
android:summary="This will be small text below the title">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.example.package.DemoDialogActivity"
android:targetPackage="com.example.package" />
</Preference>
I've been working on this for some time now. There is one workaround which I find entirely inelegant. I can just use the xml layout to build a DialogFragment by making changes in the Activity:
class HCDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_host_credentials, null);
builder.setView(view);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setTitle(R.string.dialog_title);
return builder.create();
}
}
The DialogFragment can be launched from a button like this (case statement is from the code pasted as part my original question):
case R.id.testing:
FragmentManager fm = getFragmentManager();
HCDialog hack_dialog = new HCDialog();
hack_dialog.show(fm, null);
return true;
This works. But to me it seems rather silly and I imagine I'm taking the long way around. Especially because now I'll be coding to handle persistent preference values for two versions of what appears to be the exact same dialog.
Is there a better way?
When I start the activity on my phone, it says that the app is not responding. The problem is the back button which I can't seem to program to make it gather the previous text from the textView.
Xml code for activity
<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:background="#drawable/background"
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=".Author" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:text="#string/Getstarted"
android:textColor="#FFFFFF"
android:textSize="23sp" />
<ImageButton
android:id="#+id/next"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="14dp"
android:background="#drawable/button_shape"
android:contentDescription="#string/Next"
android:onClick="NextQuote"
android:src="#drawable/navigationnextitem" />
<ImageButton
android:id="#+id/share"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/next"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:contentDescription="#string/share"
android:onClick="Sharing"
android:src="#drawable/socialshare" />
<ImageButton
android:id="#+id/back"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/next"
android:background="#drawable/button_shape"
android:contentDescription="#string/Back"
android:onClick="PreviousQuote"
android:src="#drawable/navigationpreviousitem" />
</RelativeLayout>
Java code for activity
package com.android.motivateme3;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
public class Author extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
Button NextQuote = (Button)findViewById(R.id.next);
final TextView display = (TextView) findViewById(R.id.textView1);
NextQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(10);
if (rNumber == 0)
{
display.setText(R.string.Author1);
}
else if (rNumber == 1)
{
display.setText(R.string.Author2);
}
else if (rNumber == 2)
{
display.setText(R.string.Author3);
}
else if (rNumber == 3)
{
display.setText(R.string.Author4);
}
else if (rNumber == 4)
{
display.setText(R.string.Author5);
}
else if (rNumber == 5)
{
display.setText(R.string.Author6);
}
else if (rNumber == 6)
{
display.setText(R.string.Author7);
}
else if (rNumber == 7)
{
display.setText(R.string.Author8);
}
else if (rNumber == 8)
{
display.setText(R.string.Author9);
}
else if (rNumber == 9)
{
display.setText(R.string.Author10);
} }
});
}
ImageButton Sharing = (ImageButton)findViewById(R.id.share);
Sharing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
TextView text = (TextView)findViewById(R.id.textView1);
String quote = text.getText().toString();{
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("plain/text");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "This is a great quote (from the Motivate Me! app)");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, quote);
startActivity(Intent.createChooser(shareIntent, "Share via:"));}}});
Button BackQuote = (Button)findViewById(R.id.back);
final TextView display = (TextView) findViewById(R.id.textView1);
BackQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String prev = (String) display.getText();
display.setText(prev);
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.author, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the stack trace
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.main(ActivityThread.java:4441)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invoke(Method.java:511)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
04-03 14:29:34.174: E/AndroidRuntime(17383): at dalvik.system.NativeStart.main(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.setupActionBar(Author.java:36)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.onCreate(Author.java:25)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Activity.performCreate(Activity.java:4465)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
04-03 14:29:34.174: E/AndroidRuntime(17383): ... 11 more
04-03 14:29:41.664: I/Process(17383): Sending signal. PID: 17383 SIG: 9
It seems to me that R.id.next refers to an ImageButton, which cannot be cast into a Button, since it is not a subclass of a Button
Do you happen to see a ClassCastException?
To fix that particular issue, replace:
Button NextQuote = (Button)findViewById(R.id.next);
with
ImageButton NextQuote = (ImageButton)findViewById(R.id.next);
need some help with creating my main menu. I have successfully made one on click listener that switches to a different activity but im having troubles getting the second one to work. The application runs fine in the simulation but when i go to click the weight gin button nothing happens. I just cant seem to find the problem
package com.example.bmiworking;
import android.app.Activity;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainMenu extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button btn,btn1,btn2,btn3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
btn = (Button) findViewById(R.id.buttonBMI);
btn.setOnClickListener(this);
btn1 = (Button) findViewById(R.id.buttonGain);
btn1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.buttonBMI) {
startActivity(new Intent(this, MainActivity.class));
}
}
public void onClick1(View d) {
if (d.getId() == R.id.buttonGain) {
startActivity(new Intent(this, weightgain.class));
}
}
}
package com.example.bmiworking;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class weightgain extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weightgain);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".StartingPoint"
android:background="#drawable/grunge">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Main Menu"
android:textSize="45dp"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/tvDisplay"/>
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="BMI Goal"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bSub"/>
<Button
android:id="#+id/buttonBMI"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="BMI Calculator"
android:textSize="20dp" />
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Muscle Loss Workouts"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bSub"/>
<Button
android:id="#+id/buttonGain"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Muscle Gain Workouts"
android:textSize="20dp" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bmiworking"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.bmiworking.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.bmiworking.MainMenu"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.bmiworking.weightgain"
android:label="#string/app_name" >
</activity>
</application>
Edit with stack trace:
01-24 02:34:34.739: D/dalvikvm(808): newInstance failed: p0 i0 [0 a1
01-24 02:34:34.754: D/AndroidRuntime(808): Shutting down VM
01-24 02:34:34.754: W/dalvikvm(808): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
01-24 02:34:34.819: E/AndroidRuntime(808): FATAL EXCEPTION: main
01-24 02:34:34.819: E/AndroidRuntime(808): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.bmiworking/com.example.bmiworking.MainMenu}: java.lang.InstantiationException: can't instantiate class com.example.bmiworking.MainMenu
01-24 02:34:34.819: E/AndroidRuntime(808): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.os.Handler.dispatchMessage(Handler.java:99)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.os.Looper.loop(Looper.java:137)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-24 02:34:34.819: E/AndroidRuntime(808): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 02:34:34.819: E/AndroidRuntime(808): at java.lang.reflect.Method.invoke(Method.java:511)
01-24 02:34:34.819: E/AndroidRuntime(808): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-24 02:34:34.819: E/AndroidRuntime(808): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-24 02:34:34.819: E/AndroidRuntime(808): at dalvik.system.NativeStart.main(Native Method)
01-24 02:34:34.819: E/AndroidRuntime(808): Caused by: java.lang.InstantiationException: can't instantiate class com.example.bmiworking.MainMenu
01-24 02:34:34.819: E/AndroidRuntime(808): at java.lang.Class.newInstanceImpl(Native Method)
01-24 02:34:34.819: E/AndroidRuntime(808): at java.lang.Class.newInstance(Class.java:1319)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
01-24 02:34:34.819: E/AndroidRuntime(808): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
01-24 02:34:34.819: E/AndroidRuntime(808): ... 11 more
change onClick code as using switch case instead of if-else :
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonBMI:
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.buttonGain:
startActivity(new Intent(this, weightgain.class));
break;
}
}
Change it so it is like this:
#Override
public void onClick(View v) {
if (v.getId() == R.id.buttonBMI) {
startActivity(new Intent(this, MainActivity.class));
}
if (v.getId() == R.id.buttonGain) {
startActivity(new Intent(this, weightgain.class));
}
}
You only really override onClick(View v) and so, both button presses make onClick(View v) called (onClick1() never gets used). Then since you have an if, the second button doesn't get to start anything. Of course, if you have a lot of buttons, consider using a switch statement (like ρяσѕρєяK outlined). However, the idea is the same, you only use 1 method.
I think you missed something like the correct implement about the Intent and the OnClick method. Please try this on replacinging your code into mine and you will get a good result;
#Override
public void onClick(View v) {
if (v.equals(btn)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (v.equals(btn1)) {
Intent intent = new Intent(this, weightgain.class);
startActivity(intent);
}
}
In above, "btn" and "btn1" are your buttons.
Please let me know your result.
First Change onClick code as,
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonBMI:
startActivity(new Intent(MainMenu.this, MainActivity.class));
break;
case R.id.buttonGain:
startActivity(new Intent(MainMenu.this, weightgain.class));
break;
}
}
Dont pass this when creating new instance, pass it as ActivityName.this
You Can Try This Code
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonBMI:
startActivity(new Intent(MainMenu.this, MainActivity.class));
break;
case R.id.buttonGain:
startActivity(new Intent(MainMenu.this, weightgain.class));
break;
}
}
Or
Try This 2nd Approach
public void buttonBMIClick(View view){
startActivity(new Intent(MainMenu.this, MainActivity.class));
}
public void buttonGainClick(View view){
startActivity(new Intent(MainMenu.this, weightgain.class));
}
and make you layout XML
<Button
android:id="#+id/buttonBMI"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="BMI Calculator"
android:onClick="buttonBMIClick"
android:textSize="20dp" />
<Button
android:id="#+id/buttonGain"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Muscle Gain Workouts"
android:onClick="buttonGainClick"
android:textSize="20dp" />