无法在AsyncTask中找到ViewById

时间:2014-06-05 17:27:24

标签: java android android-intent android-fragments android-asynctask

在FragmentPagerAdapter内的SherlockListFragment里面的ArrayAdapter costum listAdapter里面的AsyncTask中找不到ViewById。 !!!

好的方案是:

我有一个像这样的片段:

public class Fragment_Conversation_Section extends SherlockListFragment {

    View myFragmentView;

    public Fragment_Conversation_Section() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListAdapter listAdapter = new Adapter_ConversationFragmentAdapter(getActivity(), R.layout.items_conversation,myFragmentView);
        setListAdapter(listAdapter);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        myFragmentView = inflater.inflate(R.layout.fragment_conversation, container, false);
        return myFragmentView;
    }


}

我创建了myFragmentView变量,将其传递给我的自定义ListAdapter。

ListAdapter listAdapter = new Adapter_ConversationFragmentAdapter(getActivity(), R.layout.items_conversation,myFragmentView);

现在这是我的自定义ListAdapter

public class Adapter_ConversationFragmentAdapter extends ArrayAdapter<Array_Object_Chat_Interface> {

    Context context;
    int layoutResourceId;   
    int conversationsNo;
    List<Array_Object_Chat_Interface> conversationsItems;
    View rootView;

    public Adapter_ConversationFragmentAdapter(Context context, int layoutResourceId,View myView) {
        super(context, layoutResourceId);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.rootView = myView;
        this.conversationsNo = 0;

        conversationsItems = new ArrayList<Array_Object_Chat_Interface>();
        ArrayList<String> fName = new ArrayList<String>();

        AsyncTask<Void, Integer, String> getConversationsTask = new AsyncTask<Void, Integer, String>(){

            private ProgressBar pb;
            @Override
            protected String doInBackground(Void... params) {

              //doing some http request stuff in background
            }
            @Override
            protected void onPostExecute(String result)
            {
                Log.d("result.>>>", result);
            }


            @Override
            protected void onPreExecute() {

                pb = (ProgressBar) rootView.findViewById(R.id.progressbar2); // this is causing the error
            }


            @Override
            protected void onProgressUpdate(Integer... values) {
                pb.setProgress(values[0]);
            }

        };
        getConversationsTask.execute();



        for (int i = 0; i < conversationsNo; i++){
            Array_Object_Chat_Interface item = new Array_Object_Chat_Interface(fName.get(i));
            conversationsItems.add(item);

        }

    }


    /*private view holder class*/
    private class ViewHolder {
        TextView FName;
    }

    @Override
    public int getCount() {
        return this.conversationsNo;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
       // Check if an existing view is being reused, otherwise inflate the view
       if (convertView == null) {
           LayoutInflater inflater = ((Activity)context).getLayoutInflater();
           convertView = inflater.inflate(layoutResourceId, parent, false);

          holder = new ViewHolder();
          holder.FName = (TextView) convertView.findViewById(R.id.fName);

          convertView.setTag(holder);
       } else {
           holder = (ViewHolder) convertView.getTag();
       }

       Array_Object_Chat_Interface ChatInterface = conversationsItems.get(position);

       holder.FriendName.setText(ChatInterface.fName);

       return convertView;
   }
}

我将myFragmentView从片段传递到列表适配器,它通过构造部分传递给新变量(myView),最后传递给变量&#34; rootView&#34;。 现在在onPreExecute()里面我想找到布局里面的进度条R.layout.fragment_conversation,它在片段的onCreateView()里面膨胀了。

但是在运行时它会崩溃并显示这些错误:

logcat的:

06-05 17:19:18.854: E/AndroidRuntime(324): FATAL EXCEPTION: main
06-05 17:19:18.854: E/AndroidRuntime(324): java.lang.NullPointerException
06-05 17:19:18.854: E/AndroidRuntime(324):  at com.example.android.Fragments.Adapter_ConversationFragmentAdapter$1.onPreExecute(Adapter_ConversationFragmentAdapter.java:146)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.os.AsyncTask.execute(AsyncTask.java:391)
06-05 17:19:18.854: E/AndroidRuntime(324):  at com.example.android.Fragments.Adapter_ConversationFragmentAdapter.<init>(Adapter_ConversationFragmentAdapter.java:156)
06-05 17:19:18.854: E/AndroidRuntime(324):  at com.example.android.Fragments.Fragment_Conversation_Section.onCreate(Fragment_Conversation_Section.java:26)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:834)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.view.ViewPager.populate(ViewPager.java:804)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.View.measure(View.java:8313)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:581)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:365)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.View.measure(View.java:8313)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.View.measure(View.java:8313)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.View.measure(View.java:8313)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.View.measure(View.java:8313)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.View.measure(View.java:8313)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.ViewRoot.performTraversals(ViewRoot.java:839)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.os.Looper.loop(Looper.java:123)
06-05 17:19:18.854: E/AndroidRuntime(324):  at android.app.ActivityThread.main(ActivityThread.java:3683)
06-05 17:19:18.854: E/AndroidRuntime(324):  at java.lang.reflect.Method.invokeNative(Native Method)
06-05 17:19:18.854: E/AndroidRuntime(324):  at java.lang.reflect.Method.invoke(Method.java:507)
06-05 17:19:18.854: E/AndroidRuntime(324):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-05 17:19:18.854: E/AndroidRuntime(324):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-05 17:19:18.854: E/AndroidRuntime(324):  at dalvik.system.NativeStart.main(Native Method) 

Adapter_ConversationFragmentAdapter.java:146是onPreExecute()中的这一行:

pb = (ProgressBar) rootView.findViewById(R.id.progressbar2);

2 个答案:

答案 0 :(得分:2)

onCreate

之前调用

onCreateView

Android Developer Site

的更多信息

在您的场景中,您在onCreate方法中创建适配器,但是您在onCreateView中启动了视图,因此您获得了NPE,因为rootView在适配器类中为null

您在onCreate方法中调用以下代码:

ListAdapter listAdapter = new Adapter_ConversationFragmentAdapter(getActivity(), R.layout.items_conversation,myFragmentView);
setListAdapter(listAdapter);

myFragmentView在onCreateView中初始化,因此在onCreate方法中为null,因此您可以使用以下代码:

将以下代码复制到onCreate方法:

myFragmentView = inflater.inflate(R.layout.fragment_conversation, container, false);

或在该行之后移动适配器初始化

<强>更新

将您的代码更改为:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        myFragmentView = inflater.inflate(R.layout.fragment_conversation, container, false);

        ListAdapter listAdapter = new Adapter_ConversationFragmentAdapter(getActivity(), R.layout.items_conversation,myFragmentView);
        setListAdapter(listAdapter);

        return myFragmentView;
    }

并删除onCreate部分

答案 1 :(得分:0)

这是因为如果在xml布局文件中找不到输入id,findViewById可以返回空值。

Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).

Returns
The view if found or null otherwise.

我建议你检查一下你是否附上了正确的布局文件,如果里面有正确的id。

同时检查rootview是否为空(您可以使用if(rootview == null)

进行检查