I'm trying to show an about page to the users of my wallpaper app when they click the about button however i get leaked window errors in a log cat and the activity quits before it shows the dialog.
Here is the code:
/*
*
* Sensational Wallpapers Pack 1
*
* Wallpaper Designed by AZ2ENVY
*
*/
package com.death2all110.SensationalWallpapers1;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.widget.Button;
import android.content.DialogInterface;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import com.death2all110.SensationalWallpapers1.R;
public class wallpaper extends Activity implements AdapterView.OnItemSelectedListener,
OnClickListener {
private Gallery mGallery;
private ImageView mImageView;
private boolean mIsWallpaperSet;
private Bitmap mBitmap;
private ArrayList<Integer> mThumbs;
private ArrayList<Integer> mImages;
private WallpaperLoader mLoader;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
findWallpapers();
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setCallbackDuringFling(false);
findViewById(R.id.set).setOnClickListener(this);
mImageView = (ImageView) findViewById(R.id.wallpaper);
Button alert = (Button) findViewById(R.id.about_page);
alert.setOnClickListener(this);
}
private void findWallpapers() {
mThumbs = new ArrayList<Integer>(24);
mImages = new ArrayList<Integer>(24);
final Resources resources = getResources();
final String packageName = getApplication().getPackageName();
addWallpapers(resources, packageName, R.array.wallpapers);
addWallpapers(resources, packageName, R.array.extra_wallpapers);
}
private void addWallpapers(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra + "_small",
"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
mImages.add(res);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel(true);
mLoader = null;
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel();
}
mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
}
/*
* When using touch if you tap an image it triggers both the onItemClick and
* the onTouchEvent causing the wallpaper to be set twice. Ensure we only
* set the wallpaper once.
*/
private void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(mImages.get(position));
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e("Paperless System", "Failed to set wallpaper: " + e);
}
}
public void onNothingSelected(AdapterView parent) {
}
private class ImageAdapter extends BaseAdapter {
private LayoutInflater mLayoutInflater;
ImageAdapter(wallpaper context) {
mLayoutInflater = context.getLayoutInflater();
}
public int getCount() {
return mThumbs.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if (convertView == null) {
image = (ImageView) mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
} else {
image = (ImageView) convertView;
}
int thumbRes = mThumbs.get(position);
image.setImageResource(thumbRes);
Drawable thumbDrawable = image.getDrawable();
if (thumbDrawable != null) {
thumbDrawable.setDither(true);
} else {
Log.e("Paperless System", String.format(
"Error decoding thumbnail resId=%d for wallpaper #%d",
thumbRes, position));
}
return image;
}
}
public void onClick(View v) {
selectWallpaper(mGallery.getSelectedItemPosition());
}
public void onClick1(View about) {
// If "About was clicked.....
if (about == findViewById(R.id.about_page)) {
// Prepare the alert box!!
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set message to display...
alertbox.setMessage("Test.....");
// Add a neutral button to the alert box AND assign a listener for said button...
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener(){
// click listener for box
public void onClick(DialogInterface arg0, int arg1){
// Button was clicked!!
Toast.makeText(getApplicationContext(), "Dialog closed successfully!", Toast.LENGTH_LONG).show();
}
});
// show it!!!
alertbox.show();
}
}
class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
BitmapFactory.Options mOptions;
WallpaperLoader() {
mOptions = new BitmapFactory.Options();
mOptions.inDither = false;
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
protected Bitmap doInBackground(Integer... params) {
if (isCancelled()) return null;
try {
return BitmapFactory.decodeResource(getResources(),
mImages.get(params[0]), mOptions);
} catch (OutOfMemoryError e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap b) {
if (b == null) return;
if (!isCancelled() && !mOptions.mCancel) {
// Help the GC
if (mBitmap != null) {
mBitmap.recycle();
}
final ImageView view = mImageView;
view.setImageBitmap(b);
mBitmap = b;
final Drawable drawable = view.getDrawable();
drawable.setFilterBitmap(true);
drawable.setDither(true);
view.postInvalidate();
mLoader = null;
} else {
b.recycle();
}
}
void cancel() {
mOptions.requestCancelDecode();
super.cancel(true);
}
}
}
Here is the logcat:
I/ActivityManager( 59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.death2all110.SensationalWallpapers1/.wallpaper }
I/ActivityManager( 59): Displayed activity com.death2all110.SensationalWallpapers1/.wallpaper: 474 ms (total 474 ms)
D/dalvikvm( 286): GC freed 1448 objects / 151304 bytes in 131ms
D/dalvikvm( 106): GC freed 2485 objects / 144824 bytes in 245ms
D/dalvikvm( 59): threadid=15: bogus mon 1+0>0; adjusting
D/dalvikvm( 59): GC freed 3666 objects / 207344 bytes in 360ms
D/dalvikvm( 59): GC freed 459 objects / 21096 bytes in 357ms
E/WindowManager( 286): Activity com.death2all110.SensationalWallpapers1.wallpaper has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44c0f3d0 that was originally added here
E/WindowManager( 286): android.view.WindowLeaked: Activity com.death2all110.SensationalWallpapers1.wallpaper has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44c0f3d0 that was originally added here
E/WindowManager( 286): at android.view.ViewRoot.<init>(ViewRoot.java:227)
E/WindowManager( 286): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
E/WindowManager( 286): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
E/WindowManager( 286): at android.view.Window$LocalWindowManager.addView(Window.java:424)
E/WindowManager( 286): at android.app.Dialog.show(Dialog.java:239)
E/WindowManager( 286): at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
E/WindowManager( 286): at com.death2all110.SensationalWallpapers1.wallpaper.onClick(wallpaper.java:244)
E/WindowManager( 286): at android.view.View.performClick(View.java:2364)
E/WindowManager( 286): at android.view.View.onTouchEvent(View.java:4179)
E/WindowManager( 286): at android.widget.TextView.onTouchEvent(TextView.java:6541)
E/WindowManager( 286): at android.view.View.dispatchTouchEvent(View.java:3709)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
E/WindowManager( 286): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
E/WindowManager( 286): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
E/WindowManager( 286): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager( 286): at android.os.Looper.loop(Looper.java:123)
E/WindowManager( 286): at android.app.ActivityThread.main(ActivityThread.java:4363)
E/WindowManager( 286): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager( 286): at java.lang.reflect.Method.invoke(Method.java:521)
E/WindowManager( 286): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
E/WindowManager( 286): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
E/WindowManager( 286): at dalvik.system.NativeStart.main(Native Method)
D/dalvikvm( 286): GC freed 1704 objects / 168544 bytes in 330ms
Not only does it have a leaked window, but when that button is clicked it also sets the wallpaper...
Any help would be greatly appreciated
change this
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
with
AlertDialog.Builder alertbox = new AlertDialog.Builder(yourActivity.this);
EDITED:
Button alert = (Button) findViewById(R.id.about_page);
alert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do ur logic
});
make above change to your button click
The error shows that you are using the bad context here,
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
Try to use the right context here,
getApplicationContext(); or getParent() may solve your issue...
Thanks,
Suri Sahani.
Related
I'm making an app that by now should save and then get the value of a numeric Edit Text. When i put to load data from string.xml it went fine, but when i switched to SharedPreferences it didn't even start. Any help finding the problem would be appreciated. BTW .java is below and i'm sure layout .xml is fine.
package programmingandroidapps.brightnesscustomizationapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
final EditText mEditText1=(EditText)findViewById(R.id.editText1), mEditText2=(EditText)findViewById(R.id.editText2), mEditText3=(EditText)findViewById(R.id.editText3), mEditText4=(EditText)findViewById(R.id.editText4), mEditText5=(EditText)findViewById(R.id.editText5);
Button mButton1=(Button)findViewById(R.id.button1), mButton2=(Button)findViewById(R.id.button2), mButton3=(Button)findViewById(R.id.button3), mButton4=(Button)findViewById(R.id.button4), mButton5=(Button)findViewById(R.id.button5);
SharedPreferences storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE), storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE), storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE), storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE), storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
I believe this is the applications crash log. I'm new to Android so if it is not just say it, no need to get angry :P
05-01 13:24:53.061 1624-1624/programmingandroidapps.brightnesscustomizationapp D/dalvikvm: Not late-enabling CheckJNI (already on)
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp D/AndroidRuntime: Shutting down VM
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb3d11b20)
05-01 13:24:56.471 1624-1624/programmingandroidapps.brightnesscustomizationapp E/AndroidRuntime:
FATAL EXCEPTION: main
Process: programmingandroidapps.brightnesscustomizationapp, PID: 1624
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{programmingandroidapps.brightnesscustomizationapp/programmingandroidapps.brightnesscustomizationapp.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
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:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at programmingandroidapps.brightnesscustomizationapp.MainActivity.<init>(MainActivity.java:21)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
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:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
The problem is that you are calling findViewById and getSharedPreferences before layout has been applied and the activity (this) was initialized. You should put those method calls in onCreate after setContentView(R.layout.activity_main);.
Dejan is right about moving part of the code into the onCreate lifecycle method, specifically, your code should change to something like this:
package programmingandroidapps.brightnesscustomizationapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
private EditText mEditText1, mEditText2, mEditText3, mEditText4, mEditText5;
private Button mButton1,mButton2, mButton3, mButton4, mButton5;
private SharedPreferences storedBrightness1, storedBrightness2, storedBrightness3,storedBrightness4,storedBrightness5;
private SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton1 =(Button)findViewById(R.id.button1);
mButton2=(Button)findViewById(R.id.button2);
mButton3=(Button)findViewById(R.id.button3);
mButton4=(Button)findViewById(R.id.button4);
mButton5=(Button)findViewById(R.id.button5);
mEditText1 =(EditText)findViewById(R.id.editText1);
mEditText2=(EditText)findViewById(R.id.editText2);
mEditText3=(EditText)findViewById(R.id.editText3);
mEditText4=(EditText)findViewById(R.id.editText4);
mEditText5=(EditText)findViewById(R.id.editText5);
//instead of doing this, I'd rather use "named" SharedPreferences - call it "brightness" and will carry the five values
//something like SharedPreferences brightnessPreferences = this.getSharedPreferences("brightness", Context.MODE_PRIVATE);
//I ma just adding this here because that's the way you have it
storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE),
storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE),
storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE),
storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE),
storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
I have a list of Claim objects, each claim object is initialized with a name and an expense list.
i made an adapter for the listview for the claims. what I am trying to do now is create an adaptor for the expenses. Since each claim has its own expense list, i cannot just make a general adapter. i need to make an adapter for a specific Claim, or am thinking of this wrong? here is what I did..
JUST TO BE CLEAR< MY QUESTION IS: How do I make an adaptor for the list initializd with the expenses, and open that list-view to see the expenses of a specific claim when I click on it?
package app.zioueche_travelexpense;
import java.util.ArrayList;
import java.util.Collection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
//figure out how to add claim in different page. so we can add date range.
public class AddClaim extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_claim);
//adapter for claim view this one works. it is the expenses one that i do not know how to implement
ListView listView = (ListView) findViewById(R.id.claimListView);
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
final ArrayList<Claim> list = new ArrayList<Claim>(claims);
final ArrayAdapter<Claim> claimAdapter = new ArrayAdapter<Claim>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(claimAdapter);
//Added observer pattern
ClaimListController.getClaimList().addListener(new Listener(){
#Override
public void update(){
list.clear();
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
list.addAll(claims);
claimAdapter.notifyDataSetChanged();
}
});
//SINGLE TAP FUNCTION
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//adapter expenses I DO NOT KNOW HOW TO IMPLEMENT THIS
ListView expView = (ListView) findViewById(R.id.ExpenseListView);
Collection<Expense> expenses = list.get(position).getExpenses();
final ArrayList<Expense> expense = new ArrayList<Expense>(expenses);
final ArrayAdapter<Expense> expAdap = new ArrayAdapter<Expense>(AddClaim.this, android.R.layout.simple_list_item_1, expense);
expView.setAdapter(expAdap); //THIS IS MY LINE 64
}
});
//LONG CLICK FUNCTIONS
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view);
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true;
}
});
popup.show();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_claim, menu);
return true;
}
protected void onDeleteClick(final int position, final ArrayList<Claim> list){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(position).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(position);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}
#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);
}
public void addClaimView(MenuItem item){
Toast.makeText(this, "going to claim creation page", Toast.LENGTH_SHORT).show();
setContentView(R.layout.claim_add_page);
}
public void addClaims(View v){
ClaimListController ct = new ClaimListController();
EditText textView = (EditText) findViewById(R.id.add_claim_field);
String added = textView.getText().toString();
if (!TextUtils.isEmpty(added)){
final String t = format("added",added);
ct.addClaim(new Claim(added));
Toast.makeText(this, t, Toast.LENGTH_SHORT).show();
textView.setText("");
setContentView(R.layout.claim_list);
//Intent intent = new Intent(MainActivity.this, AddClaim.class);
//startActivity(intent);
}else{
Toast.makeText(AddClaim.this,"Please type something before adding", Toast.LENGTH_SHORT).show();
}
}
private String format(String string, String added) {
String formats = string +" "+ added;
return formats;
}
}
As you can see, i made my listview adapter for the expenses inside the onclick method, since i need the position to get the expense list out of the specific claim.
How can I do this/ when I run this code I get null pointer exceptions on line 64.
here is the log cat.
01-24 02:01:15.434: E/AndroidRuntime(1099): FATAL EXCEPTION: main
01-24 02:01:15.434: E/AndroidRuntime(1099): java.lang.NullPointerException
01-24 02:01:15.434: E/AndroidRuntime(1099): at app.zioueche_travelexpense.AddClaim$2.onItemClick(AddClaim.java:64)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$1.run(AbsListView.java:3423)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.handleCallback(Handler.java:725)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.dispatchMessage(Handler.java:92)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Looper.loop(Looper.java:137)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.app.ActivityThread.main(ActivityThread.java:5041)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invoke(Method.java:511)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-24 02:01:15.434: E/AndroidRuntime(1099): at dalvik.system.NativeStart.main(Native Method)
01-24 02:01:17.814: E/Trace(1117): error opening trace file: No such file or directory (2)
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>
I am working on a drawing app and following the online tutorial here:
http://mobile.tutsplus.com/tutorials/android/android-sdk-create-a-drawing-app-essential-functionality/
There are no problem until the last part (as above). Then, I have tried to Clean and import the project again (virtual device was restarted everytime), but the problem still exists.
Would you mind help me to take a look at this?
Thanks in advance!!
P.S. I am using Eclipse ADT
Here is the error log:
09-01 03:27:25.144: E/AndroidRuntime(788): FATAL EXCEPTION: main
09-01 03:27:25.144: E/AndroidRuntime(788): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.earth0102.luckydraw/com.earth0102.luckydraw.MainActivity}: java.lang.ClassCastException: com.earth0102.luckydraw.MainActivity cannot be cast to android.view.View$OnClickListener
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.os.Handler.dispatchMessage(Handler.java:99)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.os.Looper.loop(Looper.java:137)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-01 03:27:25.144: E/AndroidRuntime(788): at java.lang.reflect.Method.invokeNative(Native Method)
09-01 03:27:25.144: E/AndroidRuntime(788): at java.lang.reflect.Method.invoke(Method.java:511)
09-01 03:27:25.144: E/AndroidRuntime(788): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-01 03:27:25.144: E/AndroidRuntime(788): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-01 03:27:25.144: E/AndroidRuntime(788): at dalvik.system.NativeStart.main(Native Method)
09-01 03:27:25.144: E/AndroidRuntime(788): Caused by: java.lang.ClassCastException: com.earth0102.luckydraw.MainActivity cannot be cast to android.view.View$OnClickListener
09-01 03:27:25.144: E/AndroidRuntime(788): at com.earth0102.luckydraw.MainActivity.onCreate(MainActivity.java:56)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.Activity.performCreate(Activity.java:5104)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-01 03:27:25.144: E/AndroidRuntime(788): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-01 03:27:25.144: E/AndroidRuntime(788): ... 11 more
AndroidManifest.xml :
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/CustomTheme" >
<activity
android:name="com.earth0102.luckydraw.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity.java
package com.earth0102.luckydraw;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.view.Menu;
//implement the ability for the user to choose colors
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
//other features
import java.util.UUID;
import android.provider.MediaStore;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements onClickListener
{
//let user to choose colors from the palette
private DrawingView drawView;
//variable to represent the paint color button in the palette
private ImageButton currPaint, drawBtn, eraseBtn, newBtn, saveBtn;
//variable in three dimension
private float smallBrush,mediumBrush,largeBrush;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawView=(DrawingView)findViewById(R.id.drawing);
//1. retrieve the first paint color button in the palette area, which is initially going to be selected.
LinearLayout paintLayout = (LinearLayout) findViewById(R.id.paint_colors);
//2. get the first button and store it as the instance variable.
currPaint = (ImageButton) paintLayout.getChildAt(0);
//3. we use a different drawable image on the button to show that it is currently selected:
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
smallBrush=getResources().getInteger(R.integer.small_size);
mediumBrush=getResources().getInteger(R.integer.medium_size);
largeBrush=getResources().getInteger(R.integer.large_size);
//draw button
drawBtn = (ImageButton)findViewById(R.id.draw_btn);
drawBtn.setOnClickListener((OnClickListener)this);
//erase button
eraseBtn = (ImageButton)findViewById(R.id.erase_btn);
eraseBtn.setOnClickListener((OnClickListener)this);
//new painting
newBtn = (ImageButton)findViewById(R.id.new_btn);
newBtn.setOnClickListener((OnClickListener)this);
//new painting
saveBtn = (ImageButton)findViewById(R.id.save_btn);
saveBtn.setOnClickListener((OnClickListener)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.main, menu);
return true;
}
public void paintClicked(View view)
{
drawView.setBrushSize(drawView.getLastBrushSize());
//use chosen color
//1. check that the user has clicked a paint color
if(view!=currPaint)
{
//update color
ImageButton imgView = (ImageButton)view;
String color = view.getTag().toString();
drawView.setColor(color);
//update the UI to reflect the new chosen paint and set the previous one back to normal
imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint));
currPaint=(ImageButton)view;
}
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
if(view.getId()==R.id.draw_btn)
{
//draw button clicked
final Dialog brushDialog = new Dialog(this);
brushDialog.setTitle("Brush size");
brushDialog.setContentView(R.layout.brush_chooser);
//listen for clicks on size buttons - small, medium, large
ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
smallBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
drawView.setBrushSize(smallBrush);
drawView.setLastBrushSize(smallBrush);
brushDialog.dismiss();
}
});
ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
mediumBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
drawView.setBrushSize(mediumBrush);
drawView.setLastBrushSize(mediumBrush);
brushDialog.dismiss();
}
});
ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
largeBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
drawView.setBrushSize(largeBrush);
drawView.setLastBrushSize(largeBrush);
brushDialog.dismiss();
}
});
brushDialog.show();
}//end of draw button
else if (view.getId()==R.id.erase_btn)
{
//switch to erase - choose size
final Dialog brushDialog = new Dialog(this);
brushDialog.setTitle("Eraser size:");
brushDialog.setContentView(R.layout.brush_chooser);
//cancel - listen for clicks on size buttons
ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
smallBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
drawView.setBrushSize(smallBrush);
drawView.setLastBrushSize(smallBrush);
drawView.setErase(false);
brushDialog.dismiss();
}
});
ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
mediumBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
drawView.setBrushSize(mediumBrush);
drawView.setLastBrushSize(mediumBrush);
drawView.setErase(false);
brushDialog.dismiss();
}
});
//listen for clicks on size buttons
ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
largeBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
drawView.setBrushSize(largeBrush);
drawView.setLastBrushSize(largeBrush);
drawView.setErase(false);
brushDialog.dismiss();
}
});
brushDialog.show();
}//end of erase button
else if (view.getId()==R.id.new_btn)
{
String cancel = "Cancel";
//new button
AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
newDialog.setTitle("New drawing");
newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
newDialog.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
drawView.startNew();
dialog.dismiss();
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
newDialog.show();
}//end of new button
else if (view.getId()==R.id.save_btn)
{
AlertDialog.Builder saveDialog = new AlertDialog.Builder(this);
saveDialog.setTitle("Save drawing");
saveDialog.setMessage("Save drawing to device Gallery?");
saveDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
//save drawing-use insertImage to attempt to write the image to the media store
//for images on the device, which should save it to the user gallery.
//We pass the content resolver, drawing cache for the displayed View, a randomly generated
//UUID string for the filename with JPG extension and a short description.
drawView.setDrawingCacheEnabled(true);
String imgSaved=MediaStore.Images.Media.insertImage(
getContentResolver(),drawView.getDrawingCache(),
UUID.randomUUID().toString()+".jpg","drawing");
if(imgSaved!=null)
{
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
}
else
{
Toast unsavedToast = Toast.makeText(getApplicationContext(), "Oops! Image could not be saved.",
Toast.LENGTH_SHORT);
unsavedToast.show();
}
drawView.destroyDrawingCache();
}
});
saveDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
saveDialog.show();
}//end of save button
}//onClick method
}
DrawingView.java
package com.earth0102.luckydraw;
import android.content.Context;
import android.view.View;
import android.util.AttributeSet;
//for drawing
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
//other features
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.TypedValue;
public class DrawingView extends View
{
private float brushSize, lastBrushSize;
//eraser flag
private boolean erase=false;
//drawing path
private Path drawPath;
//drawing and canvas paint
private Paint drawPaint, canvasPaint;
//initial color
private int paintColor = 0xFF000000;
//canvas
private Canvas drawCanvas;
//canvas bitmap
private Bitmap canvasBitmap;
public DrawingView(Context context, AttributeSet attrs)
{
super(context, attrs);
setupDrawing();
}
private void setupDrawing()
{
//get drawing area setup for interaction
brushSize=getResources().getInteger(R.integer.medium_size);
lastBrushSize=brushSize;
//initial objects
drawPath=new Path();
drawPaint =new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(brushSize);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
//instantiating a canvas paint object
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
public void setBrushSize(float newSize)
{
//update size for each brush
float pixelAmount = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
newSize, getResources().getDisplayMetrics());
brushSize=pixelAmount;
drawPaint.setStrokeWidth(brushSize);
}
public void setLastBrushSize(float lastSize)
{
lastBrushSize=lastSize;
}
public float getLastBrushSize()
{
return lastBrushSize;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
// override a couple of methods to make
//the custom View function as a drawing View
//view given size
super.onSizeChanged(w,h,oldw,oldh);
canvasBitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
#Override
protected void onDraw(Canvas canvas)
{
//To allow the class to function as a custom drawing View,
//we also need to override the onDraw method
//draw view
canvas.drawBitmap(canvasBitmap, 0,0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
//detect user touch
float touchX=event.getX();
float touchY=event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
//redraw - Calling invalidate will cause the onDraw method to execute.
invalidate();
return true;
}
public void setColor(String newColor)
{
//set color and start by invalidating the view
invalidate();
//parse and set the color for drawing
paintColor = Color.parseColor(newColor);
drawPaint.setColor(paintColor);
}
public void setErase (Boolean isErase)
{
//set erase true or false
erase=isErase;
if(erase)
drawPaint.setXfermode(new PorterDuffXfermode (PorterDuff.Mode.CLEAR));
else
drawPaint.setXfermode(null);
}
public void startNew()
{
//set a new draw
drawCanvas.drawColor(0,PorterDuff.Mode.CLEAR);
invalidate();
}
}
OnClickListener.java - it's requested to add another class to implement onClickListener in MainActivity, and so on.
package com.earth0102.luckydraw;
import android.view.View;
public interface onClickListener
{
public void onClick(View view);
}
In MainActivity, you should implement View.OnClickListener.
in this case, you don't need your own interface OnClickListener.java, just use View.OnClickListener
I mean, change
public class MainActivity extends Activity implements onClickListener
to
public class MainActivity extends Activity implements View.OnClickListener
In the MainActivity onCreate function, you are doing:
drawBtn.setOnClickListener((OnClickListener)this);
Here you are casing this to OnClickListener which is giving error. this gives you the activity context. You can trying to cast the activity context to OnClickListener, which is creating the casting exception. You can try just passing in the Activity's context like:
drawBtn.setOnClickListener(this);
Do the same for all the other buttons and don't cast it to OnClickListener. See if this changes something.
You are casting your activity to on click listener.Do like this:
Button.setonclicklistener(commonclicklistener);
Onclicklistener commonclicklistener = new view.onclicklistener{
//add a switch case based on your buttons and perform the code here like
Switch(v.getid)
Case (draw button):
//code
Case(imagebuttpn):
//code
}
This is an rough idea .you can find code in net.I am typing through mobile otherwise would have provided with the code.
I have been working on a game for Android and I want to put highscores in. I think that this code should be working and cannot see why it isn't. I have got it set so that when the menu button is pressed a dialog box opens for the user to enter their name. This works but then when you press ok, the app crashes. The line it crashes on is ArrayList<Player> players= fs.getScores();
Here is the code for the activity class which is where it crashes:
package com.example.game;
import java.util.Collections;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.widget.EditText;
import android.view.LayoutInflater;
public class MyGame extends Activity {
GameView gv;
private final int DIALOG_TEXT_ENTRY = 1;
Filestore fs;
private String GAME_KEY= "game_key";
private Bundle sis;
TextView hscores;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
gv = new GameView(this);
setContentView(gv);
gv.setStarted(true);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
if (keyCode==KeyEvent.KEYCODE_DPAD_RIGHT)
gv.setSpriteState(2);
if (keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
gv.setSpriteState(1);
if (keyCode == KeyEvent.KEYCODE_MENU)
showDialog(DIALOG_TEXT_ENTRY);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
gv = new GameView(this);
gv.setStarted(true);
setContentView(gv);
return true;
case R.id.save:
showDialog(DIALOG_TEXT_ENTRY);
return true;
case R.id.quit:
finish();
return true;
case R.id.highscores:
setContentView(R.layout.highscores);
hscores = (TextView) findViewById(R.id.myhighscores);
ArrayList<Player> players= fs.getScores();
if(!(players==null))
{
Collections.sort(players);
String s=String.format("%15s%15s","NAME","SCORE\n");
for(Player p:players)
{
s+=String.format("%15s%15s",p.getName(),
p.getScore()+"\n");
}
hscores.setText(s);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_TEXT_ENTRY:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.save, null);
final EditText t = (EditText) textEntryView.findViewById(R.id.save_edit);
name = t.toString();
return new AlertDialog.Builder(MyGame.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_save_title)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
Player p= new Player(t.getText().toString(),gv.getTime());
ArrayList<Player> players= fs.getScores();
if(players==null)
players= new ArrayList<Player>();
players.add(p);
fs.saveScores(players);
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).create();
}
return null;
}
public void onClick(DialogInterface dialog,
int whichButton) {
Player p= new Player(name,gv.getTime());
ArrayList<Player> players= fs.getScores();
if(players==null)
players= new ArrayList<Player>();
players.add(p);
fs.saveScores(players);
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putBundle(GAME_KEY, gv.saveState());
sis=outState;
}
}
And here is the logcat:
07-08 20:56:24.799: E/AndroidRuntime(1649): FATAL EXCEPTION: main
07-08 20:56:24.799: E/AndroidRuntime(1649): java.lang.NullPointerException
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.example.game.MyGame$1.onClick(MyGame.java:117)
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
07-08 20:56:24.799: E/AndroidRuntime(1649): at android.os.Handler.dispatchMessage(Handler.java:99)
07-08 20:56:24.799: E/AndroidRuntime(1649): at android.os.Looper.loop(Looper.java:123)
07-08 20:56:24.799: E/AndroidRuntime(1649): at android.app.ActivityThread.main(ActivityThread.java:3687)
07-08 20:56:24.799: E/AndroidRuntime(1649): at java.lang.reflect.Method.invokeNative(Native Method)
07-08 20:56:24.799: E/AndroidRuntime(1649): at java.lang.reflect.Method.invoke(Method.java:507)
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
07-08 20:56:24.799: E/AndroidRuntime(1649): at dalvik.system.NativeStart.main(Native Method)
I have tried to include everything I could think of but I am new to this. Any help would be really appreciated.
ArrayList<Player> players= fs.getScores();
It seems fs is pointing to null and resulting in NullPointerException.
In your code you are no where pointing fs to valid instance/object.
The field fs (the file store) is not initialized. You need to create (or get) an instance first, maybe like you initialize the GameView in your onCreate method.