简体   繁体   中英

How do I display information in my second activity in Android

this is my first attempt at programming for Android. Ive been working on creating an activity which has a list of countries, and once any of them are clicked, a new activity is opened with information regarding that country.

I am trying to use the intent function to do this, I have all the information I want in different arrays, all in the correct order, but my problem seems to be with the "position" function to be able to display them.

This is my MainActivity code regarding the intent:

public class MainActivity extends ListActivity {

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


    setContentView(R.layout.activity_main);

    String[] CountryArray = {"Egypt", "Jordan", "Kuwait", "Saudi Arabia"};     


    setListAdapter(new MyArrayAdapter(this, CountryArray));


    final ListView CountryList = getListView();

    CountryList.setOnItemClickListener(new OnItemClickListener() {



        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {


            final String Country = (String) getListAdapter().getItem(position);
                {

                    Intent myIntent = new Intent(view.getContext(), SecondActivity.class);
                    myIntent.putExtra(Country, position);
                    startActivity(myIntent);

and this is the code in my second activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    String[] CountryArray = {"Egypt", "Jordan", "Kuwait", "Saudi Arabia"};     
    String[] CapitalArray = {"Cairo", "Amman", "Kuwait City", "Riyadh"};
    String[] CurrencyArray = {"EGP", "Jordanian Dinar", "Kuwait Dinar", "Riyal"};
    String[] PopulationlArray = {"90 Million", "6.3 Million", "3.25 Million", "29 Million"};

    Intent i = getIntent();
    int position = i.getIntExtra("Country", 0);

You need to grab the View that you wish to display the information in. If you have a TextView defined in the XML for your second activity this can be done by:

TextView textView = (TextView)findViewById(R.id.myTextView); // Using ID you set in XML
textView.setText("My information"); // Display your information

I'm guessing you would probably set the text to something like CountryArray[position] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM