Get value from object in a inner class

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 4569 Views - Last Post: 18 October 2011 - 10:52 AM

#1 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Get value from object in a inner class

Posted 14 October 2011 - 01:29 PM

Hi, my first post here! :)

I'm learning Java, Android development and want to do a dialog with a number picker.
So far I have an number picker in a dialog box, but i don't get out the value from the number picker.


My dialog code:
    public int numberGameEngine = 5;
        private int promptForNumber(String dialogTitle)
        {
                final NumberPicker np = new NumberPicker(this, null); //Start the number picker
        final Dialog dialog   = new Dialog(GameEngine.this);
       
       
        //Layout, etc
        dialog.setContentView(R.layout.pick_a_number_dialog);
        dialog.setTitle(dialogTitle);
        dialog.setCancelable(true);
       
        //Cancel button
        Button button = (Button) dialog.findViewById(R.id.cnfrm);
        button.setonclickListener(new onclickListener() {
                public void onclick(View v) {        
                        dialog.dismiss();
                        numberGameEngine = np.getValue(); //HERE! Want the value, but dont work. Just get 0.
            }
        });
       
        //Show it!
        dialog.show();
       
        return numberGameEngine;
        }




public class NumberPicker extends LinearLayout {
 
        private final long REPEAT_DELAY = 50;
       
        private final int ELEMENT_HEIGHT   = 70;
        private final int ELEMENT_WIDTH    =  ELEMENT_HEIGHT; // you're all squares, yo
        private final int NUM_FIELD_HEIGHT = 70;        //La till 2011-10-13
        private final int NUM_FIELD_WIDTH  = 100;       //La till 2011-10-13
       
        private final int MINIMUM = 0;
        private final int MAXIMUM = 10000;
       
        public Integer value;   //WANT THIS VALUE!!!! <-------------------------------------------
       
        Button decrement;
        Button increment;
        public EditText valueText;
       
        private Handler repeatUpdateHandler = new Handler();
       
        private boolean autoIncrement = false;
        private boolean autoDecrement = false;
 
        /**
         * @author Jeffrey F. Cole
         *
         */
       
        public NumberPicker( Context context, AttributeSet attributeSet) {
                super(context, attributeSet);
               
                this.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
                LayoutParams elementParams = new LinearLayout.LayoutParams( ELEMENT_WIDTH, ELEMENT_HEIGHT ); //Byte plats på WIDTH och HEIGHT
               
                LayoutParams elementNumFieldParams = new LinearLayout.LayoutParams( NUM_FIELD_WIDTH, NUM_FIELD_HEIGHT );//La till 2011-10-13
               
                // init the individual elements
                initDecrementButton( context );
                initValueEditText( context );
                initIncrementButton( context );
               
                // Can be configured to be vertical or horizontal
                // Thanks for the help, LinearLayout!  
                if( getOrientation() == VERTICAL ){
                        addView( increment, elementParams );
                        addView( valueText, elementNumFieldParams ); //Ändrade 2011-10-13
                        addView( decrement, elementParams );
                } else {
                        addView( decrement, elementParams );
                        addView( valueText, elementNumFieldParams ); //Ändrade 2011-10-13
                        addView( increment, elementParams );
                }
        }
       
        private void initIncrementButton( Context context){
                increment = new Button( context );
                increment.setTextSize( 25 );
                increment.setText( "+" );
               
                // Increment once for a click
                increment.setonclickListener(new View.onclickListener() {
            public void onclick(View v) {
                increment();
            }
        });
        }
       
      
       
        private void initDecrementButton( Context context){
                decrement = new Button( context );
                decrement.setTextSize( 25 );
                decrement.setText( "-" );
               
 
                // Decrement once for a click
                decrement.setonclickListener(new View.onclickListener() {
            public void onclick(View v) {
                decrement();
            }
        });

        }
       
        public void increment(){
                if( value < MAXIMUM ){
                        value = value + 1;
                        valueText.setText( value.toString() );
                }
        }
 
        public void decrement(){
                if( value > MINIMUM ){
                        value = value - 1;
                        valueText.setText( value.toString() );
                }
        }
       
        public int getValue(){
                return this.value; //DONT WORK! <-----------------------------------------------------
        }
       
}


(found on the internet, I cuted away some of the code).

How do I get the NumberPicker.value?

Btw, finnaly a forum with good smiles :clap:

Is This A Good Question/Topic? 0
  • +

Replies To: Get value from object in a inner class

#2 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: Get value from object in a inner class

Posted 14 October 2011 - 01:42 PM

Is '0' wrong? If yes, how do you know?
Was This Post Helpful? 0
  • +
  • -

#3 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Get value from object in a inner class

Posted 14 October 2011 - 10:19 PM

public Integer value;

is an object so it is null and thus does not have a value, or it will generate a null pointer exception if you try to access it

public int value;

is a basic datatype, it would be initialized to 0

View PostGregBrannon, on 14 October 2011 - 04:42 PM, said:

Is '0' wrong? If yes, how do you know?

surely not :)

This post has been edited by pbl: 14 October 2011 - 10:20 PM

Was This Post Helpful? 0
  • +
  • -

#4 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Re: Get value from object in a inner class

Posted 15 October 2011 - 12:58 AM

View PostGregBrannon, on 14 October 2011 - 01:42 PM, said:

Is '0' wrong? If yes, how do you know?


View Postpbl, on 14 October 2011 - 10:19 PM, said:

public Integer value;

is an object so it is null and thus does not have a value, or it will generate a null pointer exception if you try to access it

public int value;

is a basic datatype, it would be initialized to 0

View PostGregBrannon, on 14 October 2011 - 04:42 PM, said:

Is '0' wrong? If yes, how do you know?

surely not :)



Yes, because I click the "+" button in the app so the value should be more.

        private void initIncrementButton( Context context){
                increment = new Button( context ); // "+" button
                increment.setTextSize( 25 );
                increment.setText( "+" );  
               
                // Increment once for a click
                increment.setonclickListener(new View.onclickListener() {
                    public void onclick(View v) {
                        increment(); //<----- When i click the "+" button the value increment and it work, because I see the number increment.
                    }
                });
        }
		
		public void increment(){ 
                if( value < MAXIMUM ){
                        value = value + 1; <-- Value + 1
                        valueText.setText( value.toString() ); //<--- I see  that it work here
                }
        }


So if i click the "+" three times the value is 3. But when I try to get it I just get 0.
Do you understand what I mean?
Was This Post Helpful? 0
  • +
  • -

#5 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Re: Get value from object in a inner class

Posted 16 October 2011 - 10:14 AM

bump
Was This Post Helpful? 0
  • +
  • -

#6 farrell2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 874
  • View blog
  • Posts: 2,706
  • Joined: 29-July 11

Re: Get value from object in a inner class

Posted 16 October 2011 - 10:56 PM

You're on the right track, but your code doesn't even compile. Did you try pbl's suggestion? Value should be an int. What's the purpose of that handler?

This is actually an easy compound component to make. If I have time this week, I'll make on for you, if you don't figure it out in the meantime. Have you read the Android custom components and custom dialogs tutorial?
Was This Post Helpful? 0
  • +
  • -

#7 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Re: Get value from object in a inner class

Posted 17 October 2011 - 06:36 AM

View Postfarrell2k, on 16 October 2011 - 10:56 PM, said:

You're on the right track, but your code doesn't even compile. Did you try pbl's suggestion? Value should be an int. What's the purpose of that handler?

This is actually an easy compound component to make. If I have time this week, I'll make on for you, if you don't figure it out in the meantime. Have you read the Android custom components and custom dialogs tutorial?

1. "even compile" what do youy mean?
2. It don't work.
3. Witch handler? do you mean NumberPicker np = new NumberPicker();?
4. I would be really happy if you helped me with this, so I can learn and understand. I have tried really many solutions now.. :)
5. A little, but I maybe should read more. With my tests i have figured out that the NumberPicker.java class run when i load the XML file, so I think "NumberPicker np = new NumberPicker();" is unnecessarily. But how do i then get tha value, without any object to refer to?
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12680
  • View blog
  • Posts: 45,861
  • Joined: 27-December 08

Re: Get value from object in a inner class

Posted 17 October 2011 - 06:48 AM

Are you sure increment() is called? Have you checked to see what value is in relation to MAXIMUM? Also, why do you store value as an Integer over an int? And I don't see where you initialize value either.
Was This Post Helpful? 0
  • +
  • -

#9 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Re: Get value from object in a inner class

Posted 17 October 2011 - 07:27 AM

View Postmacosxnerd101, on 17 October 2011 - 06:48 AM, said:

Are you sure increment() is called? Have you checked to see what value is in relation to MAXIMUM? Also, why do you store value as an Integer over an int? And I don't see where you initialize value either.

1. Yes, I use Log.d() and it increment() is called. If i use Log.d("debug", value); in increment() i get out the value i want. But now in the GameEngine.java class.
2. What do you mean?
3. Not me, i found the script at the internet. But I have tried to change that, no different.
4. Look in initIncrement(). "private void initValueEditText( Context context){ value = new Integer( 0 );"
Was This Post Helpful? 0
  • +
  • -

#10 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12680
  • View blog
  • Posts: 45,861
  • Joined: 27-December 08

Re: Get value from object in a inner class

Posted 17 October 2011 - 07:35 AM

Quote

4. Look in initIncrement(). "private void initValueEditText( Context context){ value = new Integer( 0 );"

You didn't post that method.

Let's do this- post all your code. I'll take a look at it.

Quote

3. Not me, i found the script at the internet. But I have tried to change that, no different.

How about actually writing code yourself rather than copying someone else's work.
Was This Post Helpful? 0
  • +
  • -

#11 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Re: Get value from object in a inner class

Posted 17 October 2011 - 08:34 AM

View Postmacosxnerd101, on 17 October 2011 - 07:35 AM, said:

Quote

4. Look in initIncrement(). "private void initValueEditText( Context context){ value = new Integer( 0 );"

You didn't post that method.

Let's do this- post all your code. I'll take a look at it.

Quote

3. Not me, i found the script at the internet. But I have tried to change that, no different.

How about actually writing code yourself rather than copying someone else's work.


1. Oh, sorry.

2. Yeah, good idéa. I will start write all my programs in binary 01010100010111001.
My main point with this app is to patch a GuessANumber game from console to android, to learn me about Android dialogs , layout etc. Not to learn me program numberpickers that I think should be built in.

Anyway full code can be find here: http://pastebin.com/dLRem5Jw

I'm really glad if u can get it work :)
Was This Post Helpful? 0
  • +
  • -

#12 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12680
  • View blog
  • Posts: 45,861
  • Joined: 27-December 08

Re: Get value from object in a inner class

Posted 17 October 2011 - 08:40 AM

Post your code using code tags: :code:.

Quote

2. Yeah, good idéa. I will start write all my programs in binary 01010100010111001... Not to learn me program numberpickers that I think should be built in.

It is quite easily possible to write a guessing game in Android without a NumberPicker. Beyond that- it doesn't matter if you or I think they should be built-in or not. The fact is, they aren't. So if you want to work with them, you need to learn how to use them. If all you do is copy/paste, then you won't learn how to write code on your own. So when you're thrown into a situation in the classroom, workplace, etc., and can't write code, that's a problem.
Was This Post Helpful? 0
  • +
  • -

#13 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Re: Get value from object in a inner class

Posted 17 October 2011 - 10:25 AM

( Code from http://www.technologichron.net/?p=42, with modifications. )




/*
 * Copyright (c) 2010, Jeffrey F. Cole
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 * 	Redistributions of source code must retain the above copyright notice, this
 * 	list of conditions and the following disclaimer.
 * 
 * 	Redistributions in binary form must reproduce the above copyright notice, 
 * 	this list of conditions and the following disclaimer in the documentation 
 * 	and/or other materials provided with the distribution.
 * 
 * 	Neither the name of the technologichron.net nor the names of its contributors 
 * 	may be used to endorse or promote products derived from this software 
 * 	without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.android.GissaSiffran;

import android.content.Context;
import android.os.Handler;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * A simple layout group that provides a numeric text area with two buttons to
 * increment or decrement the value in the text area. Holding either button
 * will auto increment the value up or down appropriately. 
 * 
 * @author Jeffrey F. Cole
 *
 */
public class NumberPicker extends LinearLayout {

	private final long REPEAT_DELAY = 50;
	
	private final int ELEMENT_HEIGHT   = 70;
	private final int ELEMENT_WIDTH    =  ELEMENT_HEIGHT; // you're all squares, yo
	private final int NUM_FIELD_HEIGHT = 70; 	//La till 2011-10-13
	private final int NUM_FIELD_WIDTH  = 100;	//La till 2011-10-13
	
	private final int MINIMUM = 0;
	private final int MAXIMUM = 10000;
	
	public Integer value;	//WANT THIS VALUE!!!
	
	Button decrement;
	Button increment;
	public EditText valueText;
	
	private Handler repeatUpdateHandler = new Handler();
	
	private boolean autoIncrement = false;
	private boolean autoDecrement = false;

	/**
	 * This little guy handles the auto part of the auto incrementing feature.
	 * In doing so it instantiates itself. There has to be a pattern name for
	 * that...
	 * 
	 * @author Jeffrey F. Cole
	 *
	 */
	class RepetetiveUpdater implements Runnable {
		public void run() {
			if( autoIncrement ){
				increment();
				repeatUpdateHandler.postDelayed( new RepetetiveUpdater(), REPEAT_DELAY );
			} else if( autoDecrement ){
				decrement();
				repeatUpdateHandler.postDelayed( new RepetetiveUpdater(), REPEAT_DELAY );
			}
		}
	}
	
	public NumberPicker( Context context, AttributeSet attributeSet) {
		super(context, attributeSet);
		
		this.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
		LayoutParams elementParams = new LinearLayout.LayoutParams( ELEMENT_WIDTH, ELEMENT_HEIGHT ); //Byte plats på WIDTH och HEIGHT
		
		LayoutParams elementNumFieldParams = new LinearLayout.LayoutParams( NUM_FIELD_WIDTH, NUM_FIELD_HEIGHT );//La till 2011-10-13
		
		// init the individual elements
		initDecrementButton( context );
		initValueEditText( context );
		initIncrementButton( context );
		
		// Can be configured to be vertical or horizontal
		// Thanks for the help, LinearLayout!	
		if( getOrientation() == VERTICAL ){
			addView( increment, elementParams );
			addView( valueText, elementNumFieldParams ); //Ändrade 2011-10-13
			addView( decrement, elementParams );
		} else {
			addView( decrement, elementParams );
			addView( valueText, elementNumFieldParams ); //Ändrade 2011-10-13
			addView( increment, elementParams );
		}
	}
	
	private void initIncrementButton( Context context){
		increment = new Button( context );
		increment.setTextSize( 25 );
		increment.setText( "+" );
		
		// Increment once for a click
		increment.setonclickListener(new View.onclickListener() {
            public void onclick(View v) {
            	increment();
            }
        });
		
		// Auto increment for a long click
		increment.setOnLongClickListener( 
				new View.OnLongClickListener(){
					public boolean onLongClick(View arg0) {
						autoIncrement = true;
						repeatUpdateHandler.post( new RepetetiveUpdater() );
						return false;
					}
				}
		);
		
		// When the button is released, if we're auto incrementing, stop
		increment.setOnTouchListener( new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if( event.getAction() == MotionEvent.ACTION_UP && autoIncrement ){
					autoIncrement = false;
				}
				return false;
			}
		});
	}
	
	private void initValueEditText( Context context){
		
		value = new Integer( 0 );
		
		valueText = new EditText( context );
		valueText.setId(R.id.number_picker_value);
		valueText.setTextSize(25);
		
		Log.d("****1*****", "initValueEditText!!!!!");
		Log.d("****1*****", "Context ="+ String.valueOf(context));

		
		// Since we're a number that gets affected by the button, we need to be
		// ready to change the numeric value with a simple ++/--, so whenever
		// the value is changed with a keyboard, convert that text value to a
		// number. We can set the text area to only allow numeric input, but 
		// even so, a carriage return can get hacked through. To prevent this
		// little quirk from causing a crash, store the value of the internal
		// number before attempting to parse the changed value in the text area
		// so we can revert to that in case the text change causes an invalid
		// number
		valueText.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int arg1, KeyEvent event) {
				int backupValue = value;
				try {
					value = Integer.parseInt( ((EditText)v).getText().toString() );
				} catch( NumberFormatException nfe ){
					value = backupValue;
				}
				return false;
			}
		});
		
		// Highlight the number when we get focus
		valueText.setonfocusChangeListener(new View.onfocusChangeListener() {
			public void onfocusChange(View v, boolean hasFocus) {
				if( hasFocus ){
					((EditText)v).selectAll();
				}
			}
		});
		valueText.setGravity( Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL );
		valueText.setText( value.toString() );
		valueText.setInputType( InputType.TYPE_CLASS_NUMBER );
	}
	
	private void initDecrementButton( Context context){
		decrement = new Button( context );
		decrement.setTextSize( 25 );
		decrement.setText( "-" );
		

		// Decrement once for a click
		decrement.setonclickListener(new View.onclickListener() {
            public void onclick(View v) {
            	decrement();
            }
        });
		

		// Auto Decrement for a long click
		decrement.setOnLongClickListener( 
				new View.OnLongClickListener(){
					public boolean onLongClick(View arg0) {
						autoDecrement = true;
						repeatUpdateHandler.post( new RepetetiveUpdater() );
						return false;
					}
				}
		);
		
		// When the button is released, if we're auto decrementing, stop
		decrement.setOnTouchListener( new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if( event.getAction() == MotionEvent.ACTION_UP && autoDecrement ){
					autoDecrement = false;
				}
				return false;
			}
		});
	}
	
	public void increment() {
		if( value < MAXIMUM ){
			value = value + 1;
			valueText.setText( value.toString() );
			
			Log.d("****1*****", "++!");
			Log.d("****1*****", "Value = "+ value);
		}
	}

	public void decrement() {
		if( value > MINIMUM ){
			value = value - 1;
			valueText.setText( value.toString() );
			
			Log.d("****1*****", "--!");
			Log.d("****1*****", "Value = "+ value);
		}
	}
	
	public int getValue(){
		return value;
	}
	
	public void setValue( int value ){
		if( value > MAXIMUM ) value = MAXIMUM;
		if( value >= 0 ){
			this.value = value;
			valueText.setText( this.value.toString() );
		}
	}
	
}



View Postmacosxnerd101, on 17 October 2011 - 08:40 AM, said:

Post your code using code tags: :code:.

Quote

2. Yeah, good idéa. I will start write all my programs in binary 01010100010111001... Not to learn me program numberpickers that I think should be built in.

It is quite easily possible to write a guessing game in Android without a NumberPicker. Beyond that- it doesn't matter if you or I think they should be built-in or not. The fact is, they aren't. So if you want to work with them, you need to learn how to use them. If all you do is copy/paste, then you won't learn how to write code on your own. So when you're thrown into a situation in the classroom, workplace, etc., and can't write code, that's a problem.


Yes, and if I / you / someone don't success to get out the NumberPicker.value I will do an simple EditText, but it's more nice with a number picker.
Some code is okay to copy, I can learn that later, I will not have problem with that later, I will learn it.

Gah when I try argue towards you I realize you maybe have right. I maybe should do my own number picker now, it's just a text field, two buttons.. ~4 functions.
Was This Post Helpful? 0
  • +
  • -

#14 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12680
  • View blog
  • Posts: 45,861
  • Joined: 27-December 08

Re: Get value from object in a inner class

Posted 17 October 2011 - 11:09 AM

I ran the code you copied and it worked fine for me.
Was This Post Helpful? 0
  • +
  • -

#15 Sawny   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-October 11

Re: Get value from object in a inner class

Posted 17 October 2011 - 12:16 PM

View Postmacosxnerd101, on 17 October 2011 - 11:09 AM, said:

I ran the code you copied and it worked fine for me.

Could you get the value from the number picker, when it was in a dialogbox?
If yes, how?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2