package com.example.first666;
import com.example.first666.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FullscreenActivity extends Activity {
int counter;
Button add, sub;
TextView display;
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Your total is " + counter);
}
});
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(
mDelayHideTouchListener);
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
public void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
nullpointerexception occurs when processing display = (TextView) findViewById(R.id.tvDisplay); which crashes the app saying 'unfortunately the app has stopped'. How do I fix NullPointerException?
Here's the XML file as requested. Any help appreciated.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textSize="200sp"
android:layout_gravity="center"
android:gravity="center"/>
<Button
android:layout_width="500sp"
android:layout_height="200sp"
android:text="#string/Add"
android:layout_gravity="center"
android:gravity="center"
android:textSize="75sp"
android:id="#+id/bAdd"/>
<Button
android:layout_width="500sp"
android:layout_height="200sp"
android:text="#string/Sub"
android:layout_gravity="center"
android:textSize="75sp"
android:id="#+id/bSub"/>
</LinearLayout>
Here's the LogCat as requested
06-05 14:52:46.269: E/Trace(466): error opening trace file: No such file or directory (2)
06-05 14:52:48.300: D/AndroidRuntime(466): Shutting down VM
06-05 14:52:48.309: W/dalvikvm(466): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-05 14:52:48.360: E/AndroidRuntime(466): FATAL EXCEPTION: main
06-05 14:52:48.360: E/AndroidRuntime(466): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.first666/com.example.first666.FullscreenActivity}: java.lang.NullPointerException
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.os.Handler.dispatchMessage(Handler.java:99)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.os.Looper.loop(Looper.java:137)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-05 14:52:48.360: E/AndroidRuntime(466): at java.lang.reflect.Method.invokeNative(Native Method)
06-05 14:52:48.360: E/AndroidRuntime(466): at java.lang.reflect.Method.invoke(Method.java:511)
06-05 14:52:48.360: E/AndroidRuntime(466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-05 14:52:48.360: E/AndroidRuntime(466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-05 14:52:48.360: E/AndroidRuntime(466): at dalvik.system.NativeStart.main(Native Method)
06-05 14:52:48.360: E/AndroidRuntime(466): Caused by: java.lang.NullPointerException
06-05 14:52:48.360: E/AndroidRuntime(466): at com.example.first666.FullscreenActivity.onCreate(FullscreenActivity.java:62)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.Activity.performCreate(Activity.java:5104)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-05 14:52:48.360: E/AndroidRuntime(466): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-05 14:52:48.360: E/AndroidRuntime(466): ... 11 more
06-05 14:53:28.219: I/Process(466): Sending signal. PID: 466 SIG: 9
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
does not belongs to the current view hierarchy
If line 62 is add.setOnClickListener(new View.OnClickListener() ...
Then check if this line is returning null:
add = (Button) findViewById(R.id.bAdd);
Related
I'm studying Android development. I have a problem in LogCat, it seems like it is unable to start settings activity:
05-06 09:40:37.323: E/AndroidRuntime(945): FATAL EXCEPTION: main
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.access$800(ActivityThread.java:144)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.os.Handler.dispatchMessage(Handler.java:102)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.os.Looper.loop(Looper.java:135)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.main(ActivityThread.java:5221)
05-06 09:40:37.323: E/AndroidRuntime(945): at java.lang.reflect.Method.invoke(Native Method)
05-06 09:40:37.323: E/AndroidRuntime(945): at java.lang.reflect.Method.invoke(Method.java:372)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-06 09:40:37.323: E/AndroidRuntime(945): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
05-06 09:40:37.323: E/AndroidRuntime(945): at com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity.setupActionBar(SettingsActivity.java:48)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity.onCreate(SettingsActivity.java:40)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.Activity.performCreate(Activity.java:5933)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
05-06 09:40:37.323: E/AndroidRuntime(945): ... 10 more
Here is class where make intent with function clickedSettings for calling SettingsActivity.class Activity ( in runtime when is clicked Settings on the actionBar on top of the screen) :
package com.androiddevbook.onyourbike_chapter5.activities;
import com.androiddevbook.onyourbike_chapter4.BuildConfig;
import com.androiddevbook.onyourbike_chapter4.R;
import com.androiddevbook.onyourbike_chapter5.model.TimerState;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TimerActivity extends ActionBarActivity {
private static String CLASS_NAME;
protected TextView counter;
protected Button start;
protected Button stop;
protected Handler handler;
protected UpdateTimer updateTimer;
private static long UPDATE_EVERY = 200;
protected Vibrator vibrate;
protected long lastSeconds;
private TimerState timer;
public TimerActivity(){
CLASS_NAME = getClass().getName();
timer = new TimerState();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
counter = (TextView) findViewById(R.id.timer);
start = (Button) findViewById(R.id.start_button);
stop = (Button) findViewById(R.id.stop_button);
Log.d(CLASS_NAME, "Setting text.");
if (BuildConfig.DEBUG){
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().penaltyDeath().build());
}
timer.reset();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(CLASS_NAME, "Showing 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) {
Log.d(CLASS_NAME, "SETTINGS PRESSED.");
System.out.println("Settings pressed.");
clickedSettings(null);
return true;
}
return super.onOptionsItemSelected(item);
}
public void clickedStart(View view){
Log.d(CLASS_NAME, "Clicked start button.");
timer.start();
enableButtons();
handler = new Handler();
updateTimer = new UpdateTimer();
handler.postDelayed(updateTimer, UPDATE_EVERY);
}
public void clickedStop(View view){
Log.d(CLASS_NAME, "Clicked stop button.");
timer.stop();
enableButtons();
handler.removeCallbacks(updateTimer);
updateTimer = null;
handler = null;
}
public void enableButtons(){
Log.d(CLASS_NAME, "Set buttons enabled/disabled.");
start.setEnabled(!timer.isRunning());
stop.setEnabled(timer.isRunning());
}
public class UpdateTimer implements Runnable {
public void run(){
Log.d(CLASS_NAME, "run");
setTimeDisplay();
if ( handler != null){
handler.postDelayed(this, UPDATE_EVERY);
}
if ( timer.isRunning() ){
vibrateCheck();
}
}
}
public void onStart(){
super.onStart();
Log.d(CLASS_NAME, "onStart");
if ( timer.isRunning() ){
handler = new Handler();
updateTimer = new UpdateTimer();
handler.postDelayed(updateTimer, UPDATE_EVERY);
}
vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrate == null){
Log.w(CLASS_NAME, "No vibrate service exists.");
}
}
public void onPause(){
super.onPause();
Log.d(CLASS_NAME, "onPause");
}
public void onResume(){
super.onResume();
Log.d(CLASS_NAME, "onResume");
}
public void onStop(){
super.onStop();
Log.d(CLASS_NAME, "onSop");
if ( timer.isRunning() ){
handler.removeCallbacks(updateTimer);
handler = null;
updateTimer = null;
}
}
public void onDestroy(){
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy");
}
public void onRestart(){
super.onRestart();
Log.d(CLASS_NAME, "onRestart");
}
protected void vibrateCheck(){
long diff = timer.elapsedTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
Log.d(CLASS_NAME, "vibrateCheck");
if ( vibrate != null && seconds == 0 && seconds != lastSeconds){
long[] once = { 0, 100 };
long[] twice= { 0, 100, 400, 100};
long[] thrice = { 0, 100, 400, 100, 400, 100 };
// every hour
if ( minutes == 0){
Log.d(CLASS_NAME, "Vibrate 3 times");
vibrate.vibrate(thrice, -1);
}
// every 15 minutes
else if ( minutes % 15 == 0 ){
Log.d(CLASS_NAME, "Vibrate 2 times");
vibrate.vibrate(twice, -1);
}
// every 1 minute
else if ( minutes == 1 ){
Log.d(CLASS_NAME, "Vibrate 1 time");
vibrate.vibrate(once, -1);
}
}
lastSeconds = seconds;
}
public void clickedSettings(View view){
Log.d(CLASS_NAME, "clickedSettings.");
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
}
public void setTimeDisplay(){
Log.d(CLASS_NAME, "setTimeDisplay");
counter.setText(timer.display());
}
}
And here is SettingsActivity class, where keep options for vibrate:
package com.androiddevbook.onyourbike_chapter5.activities;
import com.androiddevbook.onyourbike.chapter5.helpers.Toaster;
import com.androiddevbook.onyourbike_chapter4.R;
import com.androiddevbook.onyourbike_chapter5.OnYourBike;
import com.androiddevbook.onyourbike_chapter5.model.Settings;
import android.support.v7.app.ActionBarActivity;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
public class SettingsActivity extends ActionBarActivity {
private CheckBox vibrate;
private String CLASS_NAME = "dada";
public SettingsActivity(){
Log.d(CLASS_NAME, "SettingsActivity.class....");
CLASS_NAME = getClass().getName();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
vibrate = (CheckBox)
findViewById(R.id.vibrate_checkbox);
Settings settings = ((OnYourBike)getApplication()).getSettings();
vibrate.setChecked(settings.isVibrateOn(this));
setupActionBar();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, 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.home) {
goHome();
return true;
}
return super.onOptionsItemSelected(item);
}
private void goHome() {
Log.d(CLASS_NAME, "gotoHome");
Intent timer =
new Intent(this, TimerActivity.class);
timer.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(timer);
}
public void onStop(){
super.onStop();
Settings settings = ((OnYourBike)getApplication()).getSettings();
settings.setVibrate(this, vibrate.isChecked());
}
public void vibrateChanged(View view){
Toaster toast = new Toaster(getApplicationContext());
if(vibrate.isChecked())
toast.make(R.string.vibrate_on);
else
toast.make(R.string.vibrate_off);
}
public void goBack(View view){
finish();
}
}
And finnaly, spec about my virtual telephone:
CPU/ABI: ARM (armeabi-v7a)
Target: Android 5.0.1 ( API level 21)
As you Extends ActionBarActivity so you need to get ActionBar using
ActionBar actionBar = getSupportActionBar();
According to the error log:
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
ActionBar actionBar = getActionBar(); line returns a null object.
Reasons:
ActionBarActivity subclasses FragmentActivity which is a support component, change code to ActionBar actionBar = getSupportActionBar();
You might be using a theme like ...Light.NoActionBar, so this due to this also there is no ActionBar present for activities, change theme to a theme that support ActionBar.
Another thing to note, this isn't the reason of this issue but, is that ActionBarActivity is deprecated, use AppCompatActivity from now on.
Your error log says it all:
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
You are calling a method on a null object:
actionBar.setDisplayHomeAsUpEnabled(true);
So make sure you do a null check or you might need to use getSupportActionBar
change your setupActionBar method like this:
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
There is one button I set in Scene2.java.I want to use the button to get in other activities Scene3.java,GameOver.java Everything worked fine until its about to open the new activity,every time the app crashed there. I want to know if there're any mistake I made in the connection,which I mean the newIntent and getIntent inScene2.java GameOver.javaand Scene3.java
Scene2.java
package com.group5.littlered;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Scene2 extends Activity {
MediaPlayer bird;
MediaPlayer bgm;
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
final String[] ListStr = { "Wake up and ask her", "Peek her secretly" };
int plot = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene2);
Intent intent1 = getIntent();
conversation = getResources().getStringArray(R.array.scene2);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 2) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
if (plot < 1) {
AlertDialog choice = new AlertDialog.Builder(
Scene2.this).create();
choice.setTitle("Pick a choice");
choice.setMessage(" ");
choice.setButton("Get up and ask her what happened",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 1;
}
});
choice.setButton2("Peek her secretly",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 2;
position = 4;
}
});
choice.show();
} else {
if (plot < 2) {
if (position < 4) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent2 = new Intent(Scene2.this,
GameOver.class);
startActivity(intent2);
finish();
}
} else {
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent3 = new Intent(Scene2.this,
Scene3.class);
startActivity(intent3);
finish();
}
}
}
}
}
});
// BGM
bgm = MediaPlayer.create(Scene2.this, R.raw.voyager);
bgm.setLooping(true);
bgm.start();
// bird
bird = MediaPlayer.create(Scene2.this, R.raw.bird);
bird.setLooping(false);
bird.start();
}
}
Scene3.java
package com.group5.littlered;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Scene3 extends Activity {
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene3);
Intent intent3 = getIntent();
conversation = getResources().getStringArray(R.array.scene1);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
{
}
}
}
});
}
}
Again sorry for my poor ENGLISH, plz tell me what I need to post more to help you understand my problem.
my logcat
04-30 09:37:39.497: E/AndroidRuntime(4862): FATAL EXCEPTION: main
04-30 09:37:39.497: E/AndroidRuntime(4862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group5.littlered/com.group5.littlered.Scene3}: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Looper.loop(Looper.java:137)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invoke(Method.java:525)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-30 09:37:39.497: E/AndroidRuntime(4862): at dalvik.system.NativeStart.main(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): Caused by: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.group5.littlered.Scene3.onCreate(Scene3.java:45)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Activity.performCreate(Activity.java:5133)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-30 09:37:39.497: E/AndroidRuntime(4862): ... 11 more
The line that is crashing is the line 45 of Scene3:
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() { // <-- THIS ONE
...
});
The cause is a NullPointerException. This means that the identifier "wtf" exists in R (this wouldn't compile otherwise) but is not found in the layer activity_scene3, as we wave the following statement line 38 of Scene3.onCreate():
setContentView(R.layout.activity_scene3); // and later on findViewById() returns `null`
You have to revisit this layout to ensure that the Button you are willing to access to actually exists, with the ID wtf.
Generally speaking, this is the danger in using a same ID in different layouts. This is prone to hide errors that would easily be found otherwise as this would just not compile.
Check your manifest file and add Scene3.java in it
<activity
android:name=".Scene3" >
</activity>
Always post question with exception, second this is may be you have not mention your other activity in manifest file like:
<activity
android:name=".Scene3">
</activity>
<activity
android:name=".GameOver">
</activity>
Hello I am just getting started in Android. Help please, read all posts about this, nothing cant help. Tried all combinations naming activities in manifest. This app showing lifecycle of the app.
Log
02-11 01:07:36.538: W/dalvikvm(20921): threadid=1: thread exiting with uncaught exception (group=0x40ab6228)
02-11 01:07:36.558: E/AndroidRuntime(20921): FATAL EXCEPTION: main
02-11 01:07:36.558: E/AndroidRuntime(20921): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.lab1/com.example.lab1.MainActivity}: java.lang.NullPointerException
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.access$600(ActivityThread.java:139)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.os.Handler.dispatchMessage(Handler.java:99)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.os.Looper.loop(Looper.java:156)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.main(ActivityThread.java:4977)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.reflect.Method.invoke(Method.java:511)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-11 01:07:36.558: E/AndroidRuntime(20921): at dalvik.system.NativeStart.main(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): Caused by: java.lang.NullPointerException
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.content.ContextWrapper.getResources(ContextWrapper.java:81)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.view.View.<init>(View.java:2723)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.view.View.<init>(View.java:2771)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:504)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:494)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:489)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.example.lab1.MainActivity.<init>(MainActivity.java:30)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.Class.newInstanceImpl(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.Class.newInstance(Class.java:1319)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
02-11 01:07:36.558: E/AndroidRuntime(20921): ... 11 more
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="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="ActivityTwo"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
MainActivity
package com.example.lab1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
// String for LogCat documentation
private final static String TAG = "Lab-ActivityOne";
// Lifecycle counters
// TODO:
int mCreate=0;
int mResume=0;
int mRestart=0;
int mStart=0;
TextView textView1 = new TextView(this);
TextView textView2 = new TextView(this);
TextView textView3 = new TextView(this);
TextView textView4 = new TextView(this);
// TODO: Create variables for each of the TextViews, called
// mTvCreate, etc.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
// TODO: Assign the appropriate TextViews to the TextView variables
// Hint: Access the TextView by calling Activity's findViewById()
textView1 = (TextView) findViewById(R.id.create);
textView2 = (TextView) findViewById(R.id.start);
textView3 = (TextView) findViewById(R.id.resume);
textView4 = (TextView) findViewById(R.id.restart);
Button launchActivityTwoButton = new Button(this);
launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
launchActivityTwoButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
// TODO:
// Launch Activity Two
// Hint: use Context's startActivity() method
// Create an intent stating which Activity you would like to start
// Launch the Activity using the intent
Intent myIntent=new Intent(view.getContext(),ActivityTwo.class);
startActivity(myIntent);
}
});
// Check for previously saved state
if (savedInstanceState != null) {
mCreate=savedInstanceState.getInt(CREATE_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
// TODO: Emit LogCat message
Log.i(TAG,"OnCreate");
// TODO:
mCreate++;
//displayCounts();
}
// Lifecycle callback overrides
#Override
public void onStart() {
super.onStart();
// TODO: Emit LogCat message
Log.i(TAG,"OnStart");
// TODO:
mStart++;
//displayCounts();
}
#Override
public void onResume() {
super.onResume();
// TODO: Emit LogCat message
Log.i(TAG,"OnResume");
// TODO:
mResume++;
displayCounts();
}
#Override
public void onPause() {
super.onPause();
// TODO: Emit LogCat message
Log.i(TAG,"OnPause");
}
#Override
public void onStop() {
super.onStop();
// TODO: Emit LogCat message
Log.i(TAG,"OnStop");
}
#Override
public void onRestart() {
super.onRestart();
// TODO: Emit LogCat message
Log.i(TAG,"OnRestart");
// TODO:
mRestart++;
displayCounts();
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO: Emit LogCat message
Log.i(TAG,"OnDestroy");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// TODO:
// Save state information with a collection of key-value pairs
// 4 lines of code, one for every count variable
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);
savedInstanceState.putInt(CREATE_KEY,mCreate);
}
// Updates the displayed counters
public void displayCounts() {
textView1.setText("onCreate() calls: " + mCreate);
textView2.setText("onStart() calls: " + mStart);
textView3.setText("onResume() calls: " + mResume);
textView4.setText("onRestart() calls: " + mRestart);
}
}
ActivityTwo
package com.example.lab1;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ActivityTwo extends Activity {
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
// String for LogCat documentation
private final static String TAG = "Lab-ActivityTwo";
// Lifecycle counters
// TODO:
int mCreate=0;
int mResume=0;
int mRestart=0;
int mStart=0;
TextView textView1 = new TextView(this);
TextView textView2 = new TextView(this);
TextView textView3 = new TextView(this);
TextView textView4 = new TextView(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
textView1 = (TextView) findViewById(R.id.create);
textView2 = (TextView) findViewById(R.id.start);
textView3 = (TextView) findViewById(R.id.resume);
textView4 = (TextView) findViewById(R.id.restart);
Button closeButton = new Button(this);
closeButton= (Button) findViewById(R.id.bClose);
closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// Check for previously saved state
if (savedInstanceState != null) {
// TODO:
// Restore value of counters from saved state
// Only need 4 lines of code, one for every count variable
mCreate=savedInstanceState.getInt(CREATE_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
// TODO: Emit LogCat message
// TODO: Emit LogCat message
Log.i(TAG,"OnCreate");
// TODO:
mCreate++;
displayCounts();
// TODO:
// Update the appropriate count variable
// Update the user interface via the displayCounts() method
}
// Lifecycle callback methods overrides
#Override
public void onStart() {
super.onStart();
// TODO: Emit LogCat message
// TODO:
// Update the appropriate count variable
// Update the user interface
// TODO: Emit LogCat message
Log.i(TAG,"OnStart");
// TODO:
mStart++;
displayCounts();
}
#Override
public void onResume() {
super.onResume();
// TODO: Emit LogCat message
// TODO:
// Update the appropriate count variable
// Update the user interface
Log.i(TAG,"OnResume");
// TODO:
mResume++;
displayCounts();
}
#Override
public void onPause() {
super.onPause();
// TODO: Emit LogCat message
Log.i(TAG,"OnPause");
}
#Override
public void onStop() {
super.onStop();
// TODO: Emit LogCat message
Log.i(TAG,"OnStop");
}
#Override
public void onRestart() {
super.onRestart();
// TODO: Emit LogCat message
Log.i(TAG,"OnRestart");
// TODO:
mRestart++;
displayCounts();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG,"OnDestroy");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// TODO:
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);
savedInstanceState.putInt(CREATE_KEY,mCreate);
}
// Updates the displayed counters
public void displayCounts() {
textView1.setText("onCreate() calls: " + mCreate);
textView2.setText("onStart() calls: " + mStart);
textView3.setText("onResume() calls: " + mResume);
textView4.setText("onRestart() calls: " + mRestart);
}
}
I am a bit new to this myself so I could be talking rubbish....
I would get rid of the member initialisation on textView1 -> textView4 and move it until after the setContentView. Next I would place a breakpoint on super.OnCreate and see if it gets there. If you do single step every line you can until you see the null pointer.
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.
the activity crashes when I try and set any imageview image (either setImageBitmap or setImageView) it does this anywhere but in the one getview.
I am trying to get an imageview array that I can use in my adapter for my gridview (problem marked "problem here")
package joshpike.hsh.hsh_game;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class DisplayActivity extends MainActivity
{
int screenTileWidth = 3;
int nativeTileSize = 256;
int tileSize;
int numberColumn;
int numberRow;
int floorNum;
ImageView[][] topGridArray = null;
ImageView[][] bottomGridArray = null;
//sets tilesize, numberColumn and numberRow
#SuppressLint("NewApi")
public void setGridVars()
{
//set tileSize
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
int screenWidth;
if (android.os.Build.VERSION.SDK_INT >= 13)
{
display.getSize(size);
screenWidth = size.x;
}
else
{
screenWidth = display.getWidth();
}
tileSize = screenWidth / screenTileWidth;
//set numberColumn and numberRow
try
{
String dataFilePath = "floors/" + floorNum + "/FloorData.txt";
InputStream dataInputStream = getAssets().open(dataFilePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(dataInputStream));
String line = reader.readLine();
line = reader.readLine();
numberColumn = Integer.parseInt(line);
line = reader.readLine();
numberRow = Integer.parseInt(line);
dataInputStream.close();
}
catch (IOException e)
{
System.out.println("exception found in try/catch in DisplayActivity.setGridVars method");
}
for(int x = 0; x < numberColumn ; x++ )
{
for(int y = 0; y < numberRow ; y++ )
{
///***PROBLEM HERE***///
bottomGridArray[x][y].setImageBitmap(currentImageView("bottom", x, y));
topGridArray[x][y].setImageBitmap(currentImageView("top", x, y));
}
}
}
//returns the one imageView for gridViewForadapter
public Bitmap currentImageView(String layer, int X, int Y )
{
try
{
Bitmap returnBitmap = null;
String imgDirectory = "floors/" + floorNum + "/" + layer + "/" + X + "," + Y + ".png";
InputStream imageInputStream = getAssets().open(imgDirectory);
returnBitmap = BitmapFactory.decodeStream(imageInputStream);
imageInputStream.close();
return returnBitmap;
}
catch (IOException e)
{
System.out.println("exception found in try/catch in DisplayActivity.currentImageView method");
return null;
}
}
public int returnGridCord (int position, char whatCord)
{
position = position + 1;
float rowFromTop = (float) position / numberColumn;
if (rowFromTop != Math.round(rowFromTop))
{
rowFromTop = ((float) Math.ceil( rowFromTop));
}
int returnY = Math.abs( (int)rowFromTop - numberRow);
int returnX = (position - ( ( (int)rowFromTop -1 ) * numberColumn) ) - 1;
System.out.println(position + ":" + returnX + "x" + returnY);
if (whatCord == 'X')
{
return returnX;
}
else
{
return returnY;
}
}
public class ImageAdapter extends BaseAdapter
{
private Context mContext;
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null)
{
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(tileSize, tileSize));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
}
else
{
imageView = (ImageView) convertView;
}
System.out.println("endish of getview");
imageView.setImageResource(R.drawable.ic_launcher);
return imageView;
}
public ImageAdapter(Context c)
{
mContext = c;
}
#Override
public int getCount()
{
return numberColumn * numberRow;
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return 0;
}
}
// Inflate the menu; this adds items to the action bar if it is present.
//makes the options menu
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.display, menu);
return true;
}
//what happens if you select items from the options menu
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId() )
{
case R.id.miniMap:
return true;
}
return super.onOptionsItemSelected(item);
}
//called when activity is started for first time either for first time or after destoryed
#Override
protected void onCreate(Bundle savedInstanceState)
{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
setGridVars();
System.out.println("DisplayActivity test about to start");
//ImageAdapter test = null;
//returnGridCord(0,"X");
GridView bottomMapGrid = (GridView)findViewById(R.id.bottomMapGrid);
bottomMapGrid.setNumColumns(numberColumn);
bottomMapGrid.setColumnWidth( tileSize );
bottomMapGrid.setStretchMode( GridView.NO_STRETCH ) ;
bottomMapGrid.setAdapter(new ImageAdapter(this));
System.out.println("DisplayActivity onCreate done");
}
//called when Activity goes from paused to active
#Override
protected void onResume()
{
super.onResume();
System.out.println("DisplayActivity onResume done");
}
//called when Activity goes from active to paused
#Override
protected void onPause()
{
super.onPause();
System.out.println("DisplayActivity onPause done");
}
//called when Activity goes from paused to stopped
#Override
protected void onStop()
{
super.onStop();
System.out.println("DisplayActivity onStop done");
}
//called when Activity goes from stopped to destroyed
#Override
protected void onDestroy()
{
super.onDestroy();
System.out.println("DisplayActivity onDestroy done");
}
//called when Activity has been stopped, is going to be paused then active
#Override
protected void onRestart()
{
super.onRestart();
System.out.println("DisplayActivity onRestart done");
}
//called when Activity is transitioning to paused either for first time or after it has been stopped
#Override
protected void onStart()
{
super.onStart();
System.out.println("DisplayActivity onStart done");
}
}
logcat:
03-20 17:16:43.437: I/System.out(22850): MainActivity onCreate done
03-20 17:16:43.437: I/System.out(22850): MainActivity onStart done
03-20 17:16:43.437: I/System.out(22850): MainActivity onResume done
03-20 17:16:43.848: D/TextLayoutCache(22850): Using debug level: 0 - Debug Enabled: 0
03-20 17:16:44.088: D/libEGL(22850): loaded /system/lib/egl/libGLES_android.so
03-20 17:16:44.168: D/libEGL(22850): loaded /system/lib/egl/libEGL_mali.so
03-20 17:16:44.208: D/libEGL(22850): loaded /system/lib/egl/libGLESv1_CM_mali.so
03-20 17:16:44.218: D/libEGL(22850): loaded /system/lib/egl/libGLESv2_mali.so
03-20 17:16:44.358: D/OpenGLRenderer(22850): Enabling debug mode 0
03-20 17:16:48.973: I/System.out(22850): MainActivity onPause done
03-20 17:16:49.974: D/OpenGLRenderer(22850): Flushing caches (mode 0)
03-20 17:16:50.674: I/System.out(22850): MainActivity onCreate done
03-20 17:16:50.915: D/AndroidRuntime(22850): Shutting down VM
03-20 17:16:50.915: W/dalvikvm(22850): threadid=1: thread exiting with uncaught exception (group=0x40aa8210)
03-20 17:16:51.005: E/AndroidRuntime(22850): FATAL EXCEPTION: main
03-20 17:16:51.005: E/AndroidRuntime(22850): java.lang.RuntimeException: Unable to start activity ComponentInfo{joshpike.hsh.hsh_game/joshpike.hsh.hsh_game.DisplayActivity}: java.lang.NullPointerException
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.access$600(ActivityThread.java:127)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.os.Looper.loop(Looper.java:137)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.main(ActivityThread.java:4448)
03-20 17:16:51.005: E/AndroidRuntime(22850): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 17:16:51.005: E/AndroidRuntime(22850): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 17:16:51.005: E/AndroidRuntime(22850): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
03-20 17:16:51.005: E/AndroidRuntime(22850): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
03-20 17:16:51.005: E/AndroidRuntime(22850): at dalvik.system.NativeStart.main(Native Method)
03-20 17:16:51.005: E/AndroidRuntime(22850): Caused by: java.lang.NullPointerException
03-20 17:16:51.005: E/AndroidRuntime(22850): at joshpike.hsh.hsh_game.DisplayActivity.setGridVars(DisplayActivity.java:85)
03-20 17:16:51.005: E/AndroidRuntime(22850): at joshpike.hsh.hsh_game.DisplayActivity.onCreate(DisplayActivity.java:235)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.Activity.performCreate(Activity.java:4465)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
03-20 17:16:51.005: E/AndroidRuntime(22850): ... 11 more
03-20 17:16:56.510: I/Process(22850): Sending signal. PID: 22850 SIG: 9
You never initialize bottomGridArray. Nor topGridArray , for that matter. (Look at this topic in a basic Java tutorial to see how and why you need to initialize your arrays)
Before your line
for(int x = 0; x < numberColumn ; x++ )
{
for(int y = 0; y < numberRow ; y++ )
insert
bottomGridArray = new ImageGrid[numberColumn][numberRow];
topGridArray = new ImageGrid[numberColumn][numberRow];
Mind you: Your code probably will have a lot of trouble. You probably should take a look at Google's recommendations for Bitmaps in your UI.