user3523322
user3523322

Reputation: 11

By clicking on ListView item, it should move to next activity

I am trying to create an app which should go to another activity on the click of a listview item and also pass the value of selected item to next activity. So far my code is:

    package com.ara.quickaccess;

    import android.app.Activity;
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;
    import android.widget.AdapterView.OnItemClickListener;

    public class View_Stud extends Activity{

    ListView lv1;
    String str[]={"abc SEM-VI","pqr SEM-VI","xyz SEM-V"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_stud);
        lv1=(ListView) findViewById(R.id.listView1);
        ArrayAdapter<String> ad=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,str);

        lv1.setAdapter(ad);
        lv1.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                    Intent i=new Intent(getApplicationContext(),Approve_Stud.class);
                    i.putExtra("data2", str[arg2]);
                    startActivity(i);
         }
            }

        });

    }
}

But on executing the above code, the application crashes.

package com.ara.quickaccess;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Approve_Stud extends Activity {

Intent i=getIntent();
String det=i.getStringExtra("data2");
TextView tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.approve_stud);
    tv2=(TextView) findViewById(R.id.textView2);
    tv2.setText(det);
}

}

Upvotes: 0

Views: 1074

Answers (1)

majk
majk

Reputation: 183

An Activity is not created until onCreate() call. You are trying to use getStringExtra() before onCreate(). You need to move it to onCreate(), also move Intent i = getIntent(); to onCreate()

Upvotes: 1

Related Questions