0

I'm new to Android and am experimenting with navigating and displaying information. I successfully put a spinner on the main view of this app, but when I click to another view (via a butoton that executes goFilter) and return (via a button that executes goHome), a place-holder appears instead. I'm sure it has something to do with goHome not loading the spinner class info, but I don't know how to do it differently.

Suggestions? .java code below:

package com.example.hellorelative;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;


public class HelloRelative extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.planets_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

    }
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
          Toast.makeText(parent.getContext(), "The planet is " +
              parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
        }

        public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }
    public void goFilter(View view) {
        setContentView(R.layout.c_filter);
    }
    public void goHome(View view) {
        setContentView(R.layout.main);
    }
}
Mike
  • 1
  • Not related, but it's preferred to declare inner classes as static (and probably private as well)- `private static class MyOnItemSelectedListener ...` – MByD May 12 '12 at 18:29

1 Answers1

0

Your go Methods actually dont seem to make the app go anywhere, you just change the layout of your activity.

I guess the 2nd layout doesnt have the spinner element with the id. Thats why its gone.

And since you never start another activity and return to this one the onCreate() method wont be called and your spinner wont be setup again.

What you wanna do is create an extra activity for your filter view and navigate with

startActivity(new Intent(this, filterActivity.class)

or

provide the spinner in your filter layout "might" work. If you dont want it to be visible just set it gone.

spinner.setVisibility(View.GONE);
Ostkontentitan
  • 6,930
  • 5
  • 53
  • 71