pindol
pindol

Reputation: 2110

Include xml file and associate an activity android

I have a bottom part of my app that is the same in every activity. So I create an xml file and i included it in each xml file of the activities with

<include layout="@layout/menu_bottom"/>

then i create a class called Main Activity that extends Activity in which i write this:

public class MainActivity extends Activity{

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

    Bundle b = getIntent().getExtras();
    int res = b.getInt("layout", R.layout.home);

    setContentView(res);

    Button itinerari = (Button) findViewById(R.id.itinerari);

    itinerari.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getApplicationContext(), Itinerari.class);
            startActivity(i);
        }
    });


    Button spostamenti = (Button) findViewById(R.id.spostamenti);

    spostamenti.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getApplicationContext(), Spostamenti.class);
            startActivity(i);
        }
    });


    Button mappa = (Button) findViewById(R.id.mappa);

    mappa.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getApplicationContext(), Mappa.class);
            startActivity(i);
        }
    });


    Button info = (Button) findViewById(R.id.info);

    info.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getApplicationContext(), Info.class);
            startActivity(i);
        }
    });
}
}

the problem is that when i start the application i get an error on int res = b.getInt("layout", R.layout.home);. It says the problem is NullPointerException.

Then if i set manually setContentView(R.layout.home) it works

Upvotes: 0

Views: 1061

Answers (2)

Tarsem Singh
Tarsem Singh

Reputation: 14199

try

Bundle b = getIntent().getExtras();
if(b!=null)
{
int res = b.getInt("layout", R.layout.home);
}
else
 {
 Log.d("b","Bundle b is null");
 }

Upvotes: 0

esentsov
esentsov

Reputation: 6522

Bundle b = getIntent().getExtras();
int res = b.getInt("layout", R.layout.home);

b may be null (if there is no extra information in intent). So you should check it for null value vefore using.

Upvotes: 2

Related Questions