listview与android中的片段

时间:2014-02-04 09:26:43

标签: android listview android-listview android-fragments fragment

我的android活动中的用户片段,我在活动中实现listview,当我点击listview项目时,它无法调用新活动。 它产生错误::

java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.tabsswipe/info.androidhive.tabsswipe.Order}: java.lang.NullPointerException

Java代码:

 package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Plywood extends Fragment{
     ListView lv1;
        String lv_arr[]={"ORDER","SELLING","SUMMARY","SETTING"};
        private FragmentActivity fa;
        @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.plywood, container, false);
        //addlistview(rootView);
        lv1 = (ListView)rootView.findViewById(R.id.listView1);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,lv_arr);
            lv1.setAdapter(adapter);


           lv1.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View view,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub

                    Toast.makeText(getActivity(), "position:"+arg2,Toast.LENGTH_LONG).show();
                    if(arg2==0)
                    {
                        try {
                            startActivity(new Intent(rootView.getContext(),Order.class));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "error:"+e,Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
            return rootView;
        }



}

2 个答案:

答案 0 :(得分:0)

除了使用rootView.getContext()使用以下getActivity()启动order活动

 startActivity(new Intent(getActivity(),Order.class));

另外,请确保您已在清单中注册了自己的活动。

答案 1 :(得分:0)

尝试使用getApplicationContext()而不是

 startActivity(new Intent(getApplicationContext(),Order.class));

并确保您的申请中已有订单活动。