Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Need help for my android app - Converter

I'm trying to make a simple converter app in Android. At first, I created a basic app, that worked fine. Now I'm trying to attach a spinner, instead of the fixed textView field.

Now, the app is crashing before it appears on the screen. (I also have seen this type of problem while making the basic app and it happens when I change position of any widget in the layout.)

Java Code: public class MainActivity extends Activity {

int mPosition;
TextView textView = (TextView) findViewById(R.id.textView3);
EditText editFieldOne = (EditText) findViewById(R.id.editKms);        
EditText editFieldTwo = (EditText) findViewById(R.id.editMiles);        
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
Spinner spinnerKmMile = (Spinner) findViewById(R.id.spinner1);

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);        
    setContentView(R.layout.activity_main);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(), 
            R.array.spinner_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinnerKmMile.setAdapter(adapter);
    spinnerKmMile.setOnItemSelectedListener(new OnSpinnerItemSelect());

    buttonConvert.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {               
            handleConvertCalculation();                         
        }           
    });
}   
public class OnSpinnerItemSelect implements OnItemSelectedListener {

    @Override
    public void onItemSelected(AdapterView<?> parent, View arg1, int position,
            long id) {
        mPosition = position;
        switch (mPosition) {
        case 0:
            String str1 = parent.getItemAtPosition(1).toString();
            textView.setText(str1);
            break;
        case 1:
            String str2 = parent.getItemAtPosition(0).toString();
            textView.setText(str2);
            break;
        default:
            break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // Auto-generated method stub
    }
}
public void handleConvertCalculation() {
    if (mPosition == 0) {
        try {                   
            double kms = Double.valueOf (editFieldOne.getText().toString());                
            double miles = kms * 0.621371192;                   
            editFieldTwo.setText(String.valueOf(miles));        
        }                   
        catch (Exception e) {   
            editFieldTwo.setText("");
            Toast.makeText(getApplicationContext(), "Enter a number!", 
                                                Toast.LENGTH_LONG).show();                  
        }
    }
    else if (mPosition == 1) {
        try {                   
            double miles = Double.valueOf (editFieldOne.getText().toString());              
            double kms = miles * 1.609344;                  
            editFieldTwo.setText(String.valueOf(kms));      
        }                   
        catch (Exception e) {   
            editFieldTwo.setText("");
            Toast.makeText(getApplicationContext(), "Enter a number!", 
                                                Toast.LENGTH_LONG).show();  
        }
    }
    else {
        Toast.makeText(getApplicationContext(), "Bug in Code! mPosition = " +
                mPosition, Toast.LENGTH_LONG).show();
    }
}

}

Need help.

1 Answer

Can you post the stacktrace from logcat?

There are exceptions like FATAL Exception: main , NullPointerException etc. but dunno why. Here it is,

10-02 11:42:32.261: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property 10-02 11:42:32.381: E/Trace(825): error opening trace file: No such file or directory (2) 10-02 11:42:32.921: E/AndroidRuntime(825): FATAL EXCEPTION: main 10-02 11:42:32.921: E/AndroidRuntime(825): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.afrinrahman.converter/com.afrinrahman.converter.MainActivity}: java.lang.NullPointerException 10-02 11:42:32.921: E/AndroidRuntime(825): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106) 10-02 11:42:32.921: E/AndroidRuntime(825): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)

[[ If you need to see the entire stack trace, please let me know. ]]

The problem is that you cannot call findViewById(R.id.yourView) before setContentView. Why? Well, because since you haven't set the layout yet. If you haven't set a layout, then how can it find the views by id?

One option is:

int mPosition;
TextView textView;
EditText editFieldOne;
EditText editFieldTwo;
Button buttonConvert;
Spinner spinnerKmMile;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);        
    setContentView(R.layout.activity_main);

   //Set up your views after setting the layout
textView = (TextView) findViewById(R.id.textView3);
editFieldOne = (EditText) findViewById(R.id.editKms);        
editFieldTwo = (EditText) findViewById(R.id.editMiles);        
buttonConvert = (Button) findViewById(R.id.buttonConvert);
spinnerKmMile = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(), 
            R.array.spinner_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinnerKmMile.setAdapter(adapter);
    spinnerKmMile.setOnItemSelectedListener(new OnSpinnerItemSelect());

    buttonConvert.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {               
            handleConvertCalculation();                         
        }           
    });
}   

Thanks a lot!! It was really helpful.