FATAL ERROR when launching an activity on Android. SettingsActivity.class

3

I have a problem when launching an activity, I get this error.

  

E / AndroidRuntime: FATAL EXCEPTION: main                     Process: jhon.casique.baccus, PID: 2424                     java.lang.RuntimeException: Unable to start activity ComponentInfo {jhon.casique.baccus / jhon.casique.baccus.controller.SettingsActivity}:   java.lang.NullPointerException                         at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2195)                         at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2245)                         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:5017)                         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:779)                         at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:595)                         at dalvik.system.NativeStart.main (Native Method)                      Caused by: java.lang.NullPointerException                         at jhon.casique.baccus.controller.SettingsActivity.onCreate (SettingsActivity.java:32)                         at android.app.Activity.performCreate (Activity.java:5231)                         at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1087)                         at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2159)                         at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2245)                         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:5017)                         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:779)                         at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:595)                         at dalvik.system.NativeStart.main (Native Method) Application terminated.

package jhon.casique.baccus.controller;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;

import jhon.casique.baccus.R;


public class SettingsActivity extends Activity implements View.OnClickListener {
    public static final String EXTRA_WINE_IMAGE_SCALE_TYPE = "jhon.casique.baccus.controller.SettingsActivity.EXTRA_WINE_IMAGE_SCALE_TYPE";

    //Views
    private RadioGroup mRadioGroup = null;


     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_settings);


         if (getIntent().getSerializableExtra(EXTRA_WINE_IMAGE_SCALE_TYPE).equals(ImageView.ScaleType.FIT_XY)){
             mRadioGroup.check(R.id.fit_radio);
         }
         else if (getIntent().getSerializableExtra(EXTRA_WINE_IMAGE_SCALE_TYPE).equals(ImageView.ScaleType.FIT_CENTER)){
             mRadioGroup.check(R.id.center_radio);
         }

         //Created here because I just need to have the buttons references to respond to events or when the user pressed it
         Button cancelButton = (Button) findViewById(R.id.cancel_button);
         Button saveButton = (Button) findViewById(R.id.save_button);

         cancelButton.setOnClickListener(this);
         saveButton.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel_button:
                cancelSettings();
                break;
            case R.id.save_button:
                saveSettings();
                break;
        }
    }

    private void saveSettings() {
        Intent config = new Intent();
        if (mRadioGroup.getCheckedRadioButtonId() == R.id.fit_radio) {
            config.putExtra(EXTRA_WINE_IMAGE_SCALE_TYPE, ImageView.ScaleType.FIT_XY);
        }
        else if (mRadioGroup.getCheckedRadioButtonId() == R.id.center_radio) {
            config.putExtra(EXTRA_WINE_IMAGE_SCALE_TYPE, ImageView.ScaleType.FIT_CENTER);
        }
        setResult(RESULT_OK, config);

        finish();
    }

    private void cancelSettings() {
        setResult(RESULT_CANCELED);

        finish();
    }
}

This is my SettingsActivity.java , which is specifically the activity I want to run.

package jhon.casique.baccus.controller;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import jhon.casique.baccus.R;
import jhon.casique.baccus.model.Wine;


public class WineActivity extends AppCompatActivity {

    //Model
    private Wine mWine = null;


    //Views
    private ImageView mWineImage = null;
    private TextView mWineNameText = null;
    private TextView mWineTypeText = null;
    private TextView mWineOriginText = null;
    private RatingBar mRatingBar = null;
    private TextView mWineCompanyText = null;
    private TextView mWineNoteText = null;
    private ViewGroup mWineGrapesContainer = null;
    private ImageButton mGoToWebButton = null;


    private static final int SETTINGS_REQUEST = 1;
    private static final String STATE_IMAGE_SCALE_TYPE = "jhon.casique.baccus.controller.WineActivity.STATE_IMAGE_SCALE_TYPE";
    private static final String TAG = WineActivity.class.getSimpleName();


    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        //Creating model
        mWine = new Wine(
                "Bembibre",
                "Tinto",
                R.drawable.bembibre,
                "Dominio de Tares",
                "http://www.dominiodetares.com/portfolio/bembibre/",
                "Este vino muestra toda la complejidad y la elegancia de la variedad Mencía. En fase visual luce un color rojo picota muy cobierto con tonalidades violáceas en el menisco. En nariz aparecen recuerdos frutales muy intensos de frutas rojas (frambuesa, cereza) y una potente ciruela negra asi como tonos florales de la gama de las rosas y violetas, vegetales muy elegantes y complementarios, hojarasca verde, tabaco y maderas aromáticas (sándalo) que le brindan un troque ciertamente perfumado",
                "El Bierzo",
                5);
        mWine.addGrape("Mencía");


        //Accessing views from the controller file.
        mWineImage = (ImageView) findViewById(R.id.wine_image);
        mWineNameText = (TextView) findViewById(R.id.wine_name);
        mWineTypeText = (TextView) findViewById(R.id.wine_type);
        mWineOriginText = (TextView) findViewById(R.id.wine_origin);
        mRatingBar = (RatingBar) findViewById(R.id.wine_rating);
        mWineCompanyText = (TextView) findViewById(R.id.wine_company);
        mWineNoteText = (TextView) findViewById(R.id.wine_notes);
        mWineGrapesContainer = (ViewGroup) findViewById(R.id.grapes_container);
        mGoToWebButton = (ImageButton) findViewById(R.id.go_to_web_button);

        //Giving value to the views with the model
        mWineImage.setImageResource(mWine.getPhoto());
        mWineNameText.setText(mWine.getName());
        mWineTypeText.setText(mWine.getType());
        mWineOriginText.setText(mWine.getOrigin());
        mRatingBar.setRating(mWine.getRating());
        mWineCompanyText.setText(mWine.getCompanyName());
        mWineNoteText.setText(mWine.getNotes());

        //List grapes actualization.
        for (int i = 0; i < mWine.getGrapeCount(); i++) {
            TextView grapeText = new TextView(this);
            grapeText.setText(mWine.getGrape(i));
            grapeText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mWineGrapesContainer.addView(grapeText);
        }

        //Buttons configuration.
        mGoToWebButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent webIntent = new Intent(WineActivity.this, WebActivity.class);

                webIntent.putExtra(WebActivity.EXTRA_WINE, mWine);

                startActivity(webIntent);
            }
        });

        //Image view configuration.
        if (savedInstanceState != null && savedInstanceState.containsKey(STATE_IMAGE_SCALE_TYPE)) {
            mWineImage.setScaleType((ImageView.ScaleType) savedInstanceState.getSerializable(STATE_IMAGE_SCALE_TYPE));
        }

    }
    //Methods to create the menu settings image.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
         super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        if (item.getItemId()== R.id.action_settings) {
            Intent settingsIntent = new Intent(this, SettingsActivity.class);
            settingsIntent.putExtra(SettingsActivity.EXTRA_WINE_IMAGE_SCALE_TYPE, mWineImage.getScaleType());
            startActivityForResult(settingsIntent, SETTINGS_REQUEST);

            return true;
        }

        return false;
    }
    //Method to create the new activity trow the menu.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTINGS_REQUEST && resultCode == RESULT_OK) {
            ImageView.ScaleType scaleType = (ImageView.ScaleType) data.getSerializableExtra(SettingsActivity.EXTRA_WINE_IMAGE_SCALE_TYPE);
            mWineImage.setScaleType(scaleType);
        }
    }

    //Method for maintaining the user option to screen rotated.

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(STATE_IMAGE_SCALE_TYPE, mWineImage.getScaleType());
    }
}

And this is the screen where I will perform the activity. I think the problem that is in the call action_settings , which is on the line WineActivity 122 .

I understood that there is just a menu in my menu_main.xml with that name, but also in the values file, a file is created, ids.xml , which has the same option. By pressing Crtl + Click directly on the call, it takes me to this file, instead of the one I want the activity to start, when I rename them, I still get an error, so I do not know how to do it .

    
asked by Jhon 20.10.2016 в 11:54
source

2 answers

2

As I mentioned in your question, the error was in your Activity on line 32 specifically.

You declare private RadioGroup mRadioGroup = null; and then onCreate of your Activity

 mRadioGroup.check(R.id.fit_radio);

Without telling you before

mRadioGroup = (RadioGroup)findViewById(R.id.rdgGrupo);
    
answered by 20.10.2016 в 17:33
0

The problem is displayed in the LogCat message:

  

Caused by: java.lang.NullPointerException at   jhon.casique.baccus.controller.SettingsActivity.onCreate (SettingsActivity.java:32)   at android.app.Activity.performCreate (Activity.java:5231)

in SettingsActivity.java which would be this line:

 mRadioGroup.check(R.id.center_radio); 

The problem is that the variable mRadioGroup is defined but not initialized:

private RadioGroup mRadioGroup = null;

You must find the id within your layout activity_settings.xml

and obtain its instance before calling its methods:

mRadioGroup = (RadioGroup)findViewById(R.id.radiogGrupo);
...
...
mRadioGroup.check(R.id.center_radio);
    
answered by 20.10.2016 в 17:37