Advertising (This ad goes away for registered users. You can Login or Register)

Android App Force closed when building an AlertDialog

Programming for your favorite smartphone or tablet? Post here
failbit
Posts: 48
Joined: Fri Apr 08, 2011 1:43 pm

Android App Force closed when building an AlertDialog

Post by failbit »

Hello. While I'm porting my game Mobile Skat to Android my App got force closed when I try to build an AlertDialog from another class than my main Activity.
When I debug the app it gives me a NullPointerException at the creation of the AlertDialog. I think it is a problem with the Context passed to the AlertDialog.Builder(context) function. Maybe you can help me. Here is the part of the code which contains the error.

Code: Select all

package mskat.android;

import java.util.Arrays;
import java.util.Vector;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class Bid extends Activity{
	
	private int bidstep;
	private BidStruct bid1;
	private BidStruct bid2;
	private BidStruct bid3;
	private int winner;
	
	public Bid() {
		this.bidstep     = 0;
		StartBidding();
	}
	
    private void Player1Says() {
    	
    	String text = getString(R.string.currentbid_str) + " " + Integer.toString(this.bidstep) + " " + getString(R.string.wantincrease_str);
		
    	String highbutton = "";
    	String lowbutton  = ""; 
    	
    	if(this.bid1.bid >= this.bidstep) {
    		highbutton = getString(R.string.yes_str);
    		lowbutton  = getString(R.string.no_str);
    	}
    	else {
    		highbutton = getString(R.string.no_str);
    		lowbutton  = getString(R.string.yes_str);
    	}
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(MobileSkatActivity.context);
    	builder.setMessage(text);
    	builder.setCancelable(false);
    	builder.setTitle(R.string.bid_str);
    	builder.setPositiveButton(highbutton, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                bidstep = GetBidstep(bidstep);
    	                Player3Answers();
    	                Player1Says();
    	           }
    	       });
    	builder.setNegativeButton(lowbutton, new DialogInterface.OnClickListener() {
    			   public void onClick(DialogInterface dialog, int id) {
    				   dialog.cancel();
    			   }
    		   });
    	
    	AlertDialog alert = builder.create();
    	alert.show();
    }
	
	private void Player3Answers() {
		
    	String text = "";
    	
    	if(this.bid3.bid >= this.bidstep) {
    		text = getString(R.string.yes_str);
    	}
    	
    	else {
    		text = getString(R.string.player3_str) + getString(R.string.says_str) + getString(R.string.passe_str);
    	}
    	
    	Context context = MobileSkatActivity.context;
    	int duration    = Toast.LENGTH_LONG;

    	Toast toast = Toast.makeText(context, text, duration);
    	toast.show();
	}
	
	private void Player2Says() {
		
	}
	
	private void Player3Says() {
		
	}
	
	public int StartBidding() {
		
		this.bid1 = GetBid(MobileSkatActivity.deck.GetHand(1));
		this.bid2 = GetBid(MobileSkatActivity.deck.GetHand(2));
		this.bid3 = GetBid(MobileSkatActivity.deck.GetHand(3));
		Player1Says();
		return this.winner;
		
	}
Advertising
MIPS: Misleading Information to Promote Sales
Play Skat on your PSP:
viewtopic.php?f=26&t=5085
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: Android App Force closed when building an AlertDialog

Post by m0skit0 »

You mean the NullPointerException is triggered here?

Code: Select all

AlertDialog.Builder builder = new AlertDialog.Builder(MobileSkatActivity.context);
And what is MobileSkatActivity?
Advertising
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"
wololo
Site Admin
Posts: 3621
Joined: Wed Oct 15, 2008 12:42 am
Location: Japan

Re: Android App Force closed when building an AlertDialog

Post by wololo »

as m0skit0 said you need to show us more.
MobileSkatActivity is not in your code sample...is it a class, is it an object? Where is it initialized? Maybe add some asserts here and there to help you debugging.
If you need US PSN Codes, this technique is what I recommend.

Looking for guest bloggers and news hunters here at wololo.net, PM me!
irfanhb7
Posts: 466
Joined: Wed Jan 26, 2011 2:46 pm
Location: In your nightmares

Re: Android App Force closed when building an AlertDialog

Post by irfanhb7 »

If you are using eclipse then you can find out the lines of code where you are getting an error , after that you can try exception handling ("try and catch" ).
Languages I know : C , C++ & Java
Image
Boy : There is something wrong with my phone.
Girl : What ?
Boy: It don't have your Phone Number.
Image
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: Android App Force closed when building an AlertDialog

Post by m0skit0 »

@irfanhb7: please abstain of useless talking. Catching the exception doesn't solve the problem.
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"
wololo
Site Admin
Posts: 3621
Joined: Wed Oct 15, 2008 12:42 am
Location: Japan

Re: Android App Force closed when building an AlertDialog

Post by wololo »

He's making a good point though. Failbit: the eclipse+android combination is fairly efficient for debugging. you can plug your phone to the debugger extremely easily, and then add a bunch of breakpoints in your code to track the root of your problem.
But I'd still like to see where you get MobileSkatActivity from.
If you need US PSN Codes, this technique is what I recommend.

Looking for guest bloggers and news hunters here at wololo.net, PM me!
failbit
Posts: 48
Joined: Fri Apr 08, 2011 1:43 pm

Re: Android App Force closed when building an AlertDialog

Post by failbit »

You mean the NullPointerException is triggered here?

Code: Select all

AlertDialog.Builder builder = new AlertDialog.Builder(MobileSkatActivity.context);
Yes it is triggered there. Well, MobileSkatActivity is my main class. I createt a static variable in it which contains the context of my app(thats MobileSkatActivity.context, its updated by a timer every 10ms) because if I called

Code: Select all

AlertDialog.Builder builder = new AlertDialog.Builder(this);
(as in the android documentation) it also gave me a NullPointerException.
So I thought I have to pass the context from my main class, but this failed, like you see. I also tried to debug but it gave me only this:

Code: Select all

08-29 14:16:05.929: ERROR/AndroidRuntime(18757): FATAL EXCEPTION: main
08-29 14:16:05.929: ERROR/AndroidRuntime(18757): java.lang.NullPointerException
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.content.Context.getString(Context.java:183)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at mskat.android.Bid.Player1Says(Bid.java:26)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at mskat.android.Bid.StartBidding(Bid.java:93)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at mskat.android.Bid.<init>(Bid.java:21)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at mskat.android.MobileSkatActivity$1.onClick(MobileSkatActivity.java:81)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.view.View.performClick(View.java:2501)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.view.View$PerformClick.run(View.java:9107)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.os.Handler.handleCallback(Handler.java:587)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.os.Looper.loop(Looper.java:130)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at android.app.ActivityThread.main(ActivityThread.java:3835)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at java.lang.reflect.Method.invokeNative(Native Method)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at java.lang.reflect.Method.invoke(Method.java:507)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
08-29 14:16:05.929: ERROR/AndroidRuntime(18757):     at dalvik.system.NativeStart.main(Native Method)
and then the debugger was disconnected because of the force closing of my app
MIPS: Misleading Information to Promote Sales
Play Skat on your PSP:
viewtopic.php?f=26&t=5085
irfanhb7
Posts: 466
Joined: Wed Jan 26, 2011 2:46 pm
Location: In your nightmares

Re: Android App Force closed when building an AlertDialog

Post by irfanhb7 »

@m0skit0
He is probably missing some block of code and as it is an exception, it must be put between a try and catch statement.
I am happy that Wololo agrees with me and that is what matters to me.
Languages I know : C , C++ & Java
Image
Boy : There is something wrong with my phone.
Girl : What ?
Boy: It don't have your Phone Number.
Image
wololo
Site Admin
Posts: 3621
Joined: Wed Oct 15, 2008 12:42 am
Location: Japan

Re: Android App Force closed when building an AlertDialog

Post by wololo »

Can you show the entire source code or is it too big? Either your context is null, or something inside it required by the builder hasn't been initialized properly...
If you need US PSN Codes, this technique is what I recommend.

Looking for guest bloggers and news hunters here at wololo.net, PM me!
failbit
Posts: 48
Joined: Fri Apr 08, 2011 1:43 pm

Re: Android App Force closed when building an AlertDialog

Post by failbit »

this is MobileSkatActivity.java(made little changes but didn't work anyway, so now context isn't updated anymore because it should not change)
as you can see in this class the AlertDialog works.

Code: Select all

package mskat.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;

public class MobileSkatActivity extends Activity{
    /** Called when the activity is first created. */
	
	public static Deck deck;
	private static Context context;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) { 
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.help:
	        ShowHelp();
	        return true;
	    case R.id.tomenu:
	    	ShowMainMenu();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	// Create an anonymous implementation of OnClickListener
	public OnClickListener ContinueListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			setContentView(R.layout.game);
	        ImageButton[] p1deck = new ImageButton[10];
	        deck = new Deck();
	        
	        p1deck[0] = (ImageButton) findViewById(R.id.ImageButton01);
	        p1deck[1] = (ImageButton) findViewById(R.id.ImageButton02);
	        p1deck[2] = (ImageButton) findViewById(R.id.ImageButton03);
	        p1deck[3] = (ImageButton) findViewById(R.id.ImageButton04);
	        p1deck[4] = (ImageButton) findViewById(R.id.ImageButton05);
	        p1deck[5] = (ImageButton) findViewById(R.id.ImageButton06);
	        p1deck[6] = (ImageButton) findViewById(R.id.ImageButton07);
	        p1deck[7] = (ImageButton) findViewById(R.id.ImageButton08);
	        p1deck[8] = (ImageButton) findViewById(R.id.ImageButton09);
	        p1deck[9] = (ImageButton) findViewById(R.id.ImageButton10);
	        
	        p1deck[0].setImageResource(deck.GetCard(1, 0).GetImage());
	        p1deck[1].setImageResource(deck.GetCard(1, 1).GetImage());
	        p1deck[2].setImageResource(deck.GetCard(1, 2).GetImage());
	        p1deck[3].setImageResource(deck.GetCard(1, 3).GetImage());
	        p1deck[4].setImageResource(deck.GetCard(1, 4).GetImage());
	        p1deck[5].setImageResource(deck.GetCard(1, 5).GetImage());
	        p1deck[6].setImageResource(deck.GetCard(1, 6).GetImage());
	        p1deck[7].setImageResource(deck.GetCard(1, 7).GetImage());
	        p1deck[8].setImageResource(deck.GetCard(1, 8).GetImage());
	        p1deck[9].setImageResource(deck.GetCard(1, 9).GetImage());
	        
	        Bid test2 = new Bid();
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        MobileSkatActivity.context = getApplicationContext();
        ShowMainMenu();
    }
    
    public static Context GetContext() {	
    	return MobileSkatActivity.context;
    }
    
    private void ShowMainMenu() {
        setContentView(R.layout.main);
        Button ContinueButton = (Button) findViewById(R.id.Button0);
        ContinueButton.setOnClickListener(ContinueListener);
    }
	
    private void ShowHelp() {
    	
    	CharSequence text = getString(R.string.helptext_str);
    			
    	final SpannableString s = new SpannableString(text);
    	Linkify.addLinks(s, Linkify.ALL);
		
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage(s)
    		   .setTitle(R.string.help_str)
    	       .setCancelable(false)
    	       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	
    	AlertDialog alert = builder.create();
    	alert.show();
	    ((TextView)alert.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
    }
}

MIPS: Misleading Information to Promote Sales
Play Skat on your PSP:
viewtopic.php?f=26&t=5085
Locked

Return to “Programming”