如何根据Android中asyn后台调用服务器的结果,在片段的onCreateView方法中返回两个不同的视图?

如何根据Android中asyn后台调用服务器的结果,在片段的onCreateView方法中返回两个不同的视图?,android,android-layout,android-fragments,Android,Android Layout,Android Fragments,我有一个片段,其中我们必须根据后台线程的结果返回视图。但目前我得到空指针异常 这是我们的片段类: public class ProductFragment extends Fragment { String ss = null; GridView gridView; ArrayList<ProductParameterBO> productlist; GridViewCustomAdapter gridViewCustomAdapter; ArrayList<View>

我有一个片段,其中我们必须根据后台线程的结果返回视图。但目前我得到空指针异常

这是我们的片段类:

public class ProductFragment extends Fragment {

String ss = null;
GridView gridView;
ArrayList<ProductParameterBO> productlist;
GridViewCustomAdapter gridViewCustomAdapter;
ArrayList<View> viewList;
public int itemSelected = 0;
private static boolean isFirstTime = false;
RequestObject requestObject;
JSONObject jsonObject1;


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

    String responseString = "{\"rqBody\" :" + "{"+ "}}" ;
    try {
        requestObject = new RequestObject();
        requestObject.setJsonSend(responseString);
        requestObject.setUrl(NetworkUrl.GETPRODUCTINFO_URL);

        new GetProductInfo().execute(requestObject);
    }
    catch (Exception e){
        e.printStackTrace();
    }

}

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




    if (jsonObject1.length()==0){
        View rootView =  inflater.inflate(R.layout.empty_catalog_item,null);

        TextView configure = (TextView)rootView.findViewById(R.id.text_conf);

        configure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(),SplitViewActivity.class);
                intent.putExtra("firstTab","1stTabs");
                startActivity(intent);

            }
        });

        TextView text_here = (TextView)rootView.findViewById(R.id.text_here);
        text_here.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), EditUploadActivity.class);
                startActivity(intent);

            }
        });

      return rootView;
    }else {

        View rootView =  inflater.inflate(R.layout.fragment_product,null);

        gridView =(GridView)rootView.findViewById(R.id.gridView);

        viewList = new ArrayList<View>();

        productlist = new ArrayList<ProductParameterBO>();

        productlist.add(new ProductParameterBO("Type","Numeric","yes","yes"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        gridViewCustomAdapter = new GridViewCustomAdapter(getActivity(),productlist);
        gridView.setAdapter(gridViewCustomAdapter);
        gridViewCustomAdapter.notifyDataSetChanged();

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

                if (isFirstTime) {
                    viewList.get(itemSelected).setVisibility(View.GONE);
                    Log.d("Inside", "Selected");
                }

                RelativeLayout relativeLayout = (RelativeLayout) v.findViewById(R.id.grid_img_ovrly);
                viewList.add(relativeLayout);
                relativeLayout.setVisibility(View.VISIBLE);
                itemSelected = position;
                isFirstTime = true;

                Log.d("outside", "Selected");

            }
        });


        FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), EditUploadActivity.class);
                startActivity(intent);

            }
        });


        return rootView;
    }

   // return inflater.inflate(R.layout.fragment_product,null);
}


private class GetProductInfo extends AsyncTask<RequestObject, Void, JSONObject> {
    private ProgressDialog pDialog;
    private Context context;


    @Override
    protected JSONObject doInBackground(RequestObject... arg0) {
        // Creating service handler class instance
        ServiceCallHandler sh = new ServiceCallHandler();
        // RequestObject requestObject = new RequestObject();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(arg0[0], ServiceCallHandler.POST);

        Log.d("Response: ", "> " + jsonStr);

        String status=null;
        JSONObject jsonObject = new JSONObject();

        if (jsonStr != null) {

            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                jsonObject = jsonObj.getJSONObject("rsBody");
               /* if (jsonObject.has("name")){
                    status = jsonObject.getString("status");

                }*/


            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return jsonObject;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);

        jsonObject1 = new JSONObject();
        jsonObject1 = result;



    }

}
公共类ProductFragment扩展了片段{
字符串ss=null;
GridView;
ArrayList产品列表;
GridViewCustomAdapter GridViewCustomAdapter;
ArrayList视图列表;
公共int itemSelected=0;
私有静态布尔值isFirstTime=false;
请求对象请求对象;
JSONObject JSONObject 1;
@凌驾
创建时的公共void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
字符串responseString=“{\'rqBody\”:“+”{“+”}}”;
试一试{
requestObject=新的requestObject();
setJsonSend(responseString);
setUrl(NetworkUrl.GETPRODUCTINFO\uURL);
新建GetProductInfo().execute(请求对象);
}
捕获(例外e){
e、 printStackTrace();
}
}
@可空
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
if(jsonObject1.length()=0){
视图根视图=充气机。充气(R.layout.empty\u catalog\u item,null);
TextView configure=(TextView)rootView.findviewbyd(R.id.text\u conf);
configure.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Intent Intent=new Intent(getActivity(),SplitViewActivity.class);
意向。额外(“第一个标签”、“第一个标签”);
星触觉(意向);
}
});
TextView text_here=(TextView)rootView.findViewById(R.id.text_here);
text_here.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
}
});
FloatingActionButton fab=(FloatingActionButton)rootView.findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Intent Intent=new Intent(getActivity(),EditUploadActivity.class);
星触觉(意向);
}
});
返回rootView;
}否则{
视图根视图=充气机。充气(R.layout.fragment\u product,null);
gridView=(gridView)rootView.findviewbyd(R.id.gridView);
viewList=newarraylist();
productlist=新的ArrayList();
添加(新的ProductParameterBO(“类型”、“数字”、“是”、“是”));
productlist.add(新的ProductParameterBO(“Typess”、“Numericss”、“yesss”、“yesss”));
productlist.add(新的ProductParameterBO(“Typess”、“Numericss”、“yesss”、“yesss”));
productlist.add(新的ProductParameterBO(“Typess”、“Numericss”、“yesss”、“yesss”));
gridViewCustomAdapter=新的gridViewCustomAdapter(getActivity(),productlist);
setAdapter(gridViewCustomAdapter);
gridViewCustomAdapter.notifyDataSetChanged();
setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView arg0,视图v,内部位置,长arg3){
如果(是第一次){
viewList.get(itemSelected).setVisibility(View.GONE);
日志d(“内部”、“选定”);
}
RelativeLayout RelativeLayout=(RelativeLayout)v.findViewById(R.id.grid\u img\u ovrly);
viewList.add(relativeLayout);
relativeLayout.setVisibility(View.VISIBLE);
itemSelected=位置;
isFirstTime=true;
日志d(“外部”、“选定”);
}
});
FloatingActionButton fab=(FloatingActionButton)rootView.findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Intent Intent=new Intent(getActivity(),EditUploadActivity.class);
星触觉(意向);
}
});
返回rootView;
}
//返回充气机。充气(R.layout.fragment_product,空);
}
私有类GetProductInfo扩展了异步任务{
私人对话;
私人语境;
@凌驾
受保护的JSONObject doInBackground(请求对象…arg0){
//创建服务处理程序类实例
ServiceCallHandler sh=新的ServiceCallHandler();
//RequestObject RequestObject=新的RequestObject();
//向url发出请求并获得响应
字符串jsonStr=sh.makeServiceCall(arg0[0],ServiceCallHandler.POST);
Log.d(“响应:”、“>”+jsonStr);
字符串状态=空;
JSONObject JSONObject=新的JSONObject();
if(jsonStr!=null){
试一试{
JSONObject jsonObj=新的JSONObject(jsonStr);
jsonObject=jsonObj.getJSONObject(“rsBody”);
/*if(jsonObject.has(“name”)){
status=jsonObject.getString(“status”);
}*/
}捕获(JSONException e){
e、 printStackTrace();
}
}否则{
Log.e(“ServiceHandler”,“无法从url获取任何数据”);
}
返回jsonObject;
}
@凌驾
受保护的void onPostExecute(JSONObject结果){
super.onPostExecute(结果);
JSONObject 1=新的JSONObject();
jsonObject1=结果;
}
}
}

我希望根据JsonObject1返回oncreate方法内部的视图,但得到nullpointer异常。我认为oncreate方法是在后台线程之前调用的。如何首先调用我的服务器调用,并根据它们的结果显示视图


任何帮助都将提前感谢….

首先显示空视图
 @Override
    protected void onPostExecute(JSONObject result) {
        if (result == null || result.length() == 0) {
            RelativeLayout one = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.fragment_home, null);
             //Here getView() is empty view which is returned in onCreateView
            if (getView() != null) {
                ((LinearLayout) getView()).addView(one);
            }
        } else {
            LinearLayout one = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.activity_login_facebook, null);
            if (getView() != null) {
                ((LinearLayout) getView()).addView(one);
            }
        }
    }
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.activity_notification_fragment,container,false); //first layout

    View view1=inflater.inflate(R.layout.activity_offline,container,false);             //second layout   

    //On back press for view....

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {

                mFragmentManager = getActivity().getSupportFragmentManager();
                mFragmentTransaction = mFragmentManager.beginTransaction();

                mFragmentTransaction.addToBackStack("home");
                mFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
                return true;
            }

            return false;
        }
    });

    //On back press for view1....

    view1.setFocusableInTouchMode(true);
    view1.requestFocus();
    view1.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {

                mFragmentManager = getActivity().getSupportFragmentManager();
                mFragmentTransaction = mFragmentManager.beginTransaction();

                mFragmentTransaction.addToBackStack("home");
                mFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
                return true;
            }

            return false;
        }
    });


    /* Depending on the condition....returning the views...*/
    if(notificationsList.size() == 0){
        return view1;
    }else{
        return view;
    }

}