【问题标题】:How to show json data in sliding menu fragments?如何在滑动菜单片段中显示 json 数据?
【发布时间】:2016-08-04 11:27:20
【问题描述】:

我想在滑动菜单片段中显示 json 数据,但是当我进入片段应用程序意外关闭时,我有 34 个片段,我需要在每个片段中显示不同的 Json 数据。感谢您的帮助,希望您能理解问题。

LOGCAT

DahiliyeFragment

    public class DahiliyeFragment extends Fragment {


    public DahiliyeFragment() {
    // Required empty public constructor
    }
    private ListView lvPersonel;

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


        new JSONTask().execute("https://api.myjson.com/bins/4hopr");

        DisplayImageOptions defaultOptions = new              DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(      getActivity()).defaultDisplayImageOptions(defaultOptions)
        .build();
        ImageLoader.getInstance().init(config); // Do it on Application start

        lvPersonel = (ListView) getView().findViewById(R.id.lvPersonel);


        return inflater.inflate(R.layout.fragment_dahiliye, container, false);
    }



    public class JSONTask extends  AsyncTask<String,String,List<PersonelModel>>
    {

    @Override
    protected List<PersonelModel> doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader=null;
        InputStream stream;
        StringBuffer buffer;
    try {
        URL url = new URL(params[0]); //bağlantı
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream)); 
        buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            buffer.append(line);

        }

        String finalJson = buffer.toString();
        JSONObject parentObject = new JSONObject(finalJson);

        JSONArray parentArray = parentObject.getJSONArray("personeller"); 

        List<PersonelModel> personelModelList = new ArrayList<>(); 

        for(int i=0; i<parentArray.length(); i++)

        {
            JSONObject finalobject = parentArray.getJSONObject(i); 


            PersonelModel personelModel = new PersonelModel();
            personelModel.setUnvan(finalobject.getString("unvan"));
            personelModel.setAd(finalobject.getString("ad"));
            personelModel.setSoyad(finalobject.getString("soyad"));
            personelModel.setOda(finalobject.getString("oda"));
            personelModel.setResim(finalobject.getString("resim"));




            personelModelList.add(personelModel);



            }


            return personelModelList;


            } catch (MalformedURLException e) {
            e.printStackTrace();
            } catch (IOException e) {
            e.printStackTrace();
            } catch (JSONException e) {
            e.printStackTrace();
            } finally {
            if(connection != null)
            {connection.disconnect();}
            try {
            if(reader != null){
                reader.close();}
            } catch (IOException e) {
            e.printStackTrace();
            }
            }

            return null;
            }



            @Override
            protected void onPostExecute(List<PersonelModel> result) {
                super.onPostExecute(result);

                PersonelAdapter adapter = new                         PersonelAdapter(getActivity(),R.layout.row, result);
                lvPersonel.setAdapter(adapter);

            }
            }



            public class PersonelAdapter extends ArrayAdapter{

                private List<PersonelModel> personelModelList;
                private int resource;
                private LayoutInflater inflater;

            public PersonelAdapter(Context context, int resource,  List<PersonelModel> objects) {
                super(context, resource, objects);
                personelModelList = objects;
                this.resource = resource;
                inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            }

            @Override
            public View getView(int position, View convertView, ViewGroup  parent) {

                ViewHolder holder = null;
                if(convertView == null)
                {
                holder = new ViewHolder();
                convertView = inflater.inflate(resource, null);
                holder.ivResim =     (ImageView)convertView.findViewById(R.id.ivResim); 
                holder.tvAd = (TextView)convertView.findViewById(R.id.tvAd);
                holder.tvSoyad = (TextView)convertView.findViewById(R.id.tvSoyad);
                holder.tvOda = (TextView)convertView.findViewById(R.id.tvOda);
                holder.tvUnvan = (TextView)convertView.findViewById(R.id.tvUnvan);

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




               final ProgressBar progressBar =     (ProgressBar)convertView.findViewById(R.id.progressBar);
                         ImageLoader.getInstance().displayImage("http://i.hizliresim.com/go7bpQ.jpg",   holder.ivResim, new ImageLoadingListener() {
           @Override
           public void onLoadingStarted(String s, View view) {
           progressBar.setVisibility(View.VISIBLE);
           }

          @Override
          public void onLoadingFailed(String s, View view, FailReason failReason)   {
              progressBar.setVisibility(View.GONE);
          }

          @Override
          public void onLoadingComplete(String s, View view, Bitmap bitmap)   {
              progressBar.setVisibility(View.GONE);
          }

          @Override
          public void onLoadingCancelled(String s, View view) {
              progressBar.setVisibility(View.GONE);
          }
          });



              holder.tvUnvan.setText("Unvan:   " +                  personelModelList.get(position).getUnvan());
              holder.tvAd.setText("Ad:  " + personelModelList.get(position).getAd());
              holder.tvSoyad.setText("Soyad:   " + personelModelList.get(position).getSoyad());
              holder.tvOda.setText("Oda:    " + personelModelList.get(position).getOda());




              return convertView;
          }
          }


    class ViewHolder

    {

        private ImageView ivResim;
        private TextView tvAd;
        private TextView tvSoyad;
        private TextView tvOda;
        private TextView tvUnvan;

    }

    }

【问题讨论】:

    标签: android json android-fragments


    【解决方案1】:

    根据您的 logcat 结果, 您可以参考 DahiliyeFragment 类的第 63 行, 它提到了调用 findViewById(..) 函数的变量的空指针异常

    根据你的代码,你有

    lvPersonel = (ListView) getView().findViewById(R.id.lvPersonel);
    

    由此可见,由于 getView() 没有启动,因为您处于 onCreateView(..) 状态,这意味着 getView() 将是一个空对象,这就是返回空指针异常的原因。

    要解决这个问题,你可以申请

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
       View v = inflater.inflate(R.layout.fragment_dahiliye, container, false);
    
        new JSONTask().execute("https://api.myjson.com/bins/4hopr");
    
        DisplayImageOptions defaultOptions = new              DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(      getActivity()).defaultDisplayImageOptions(defaultOptions)
        .build();
        ImageLoader.getInstance().init(config); // Do it on Application start
    
        lvPersonel = (ListView) v.findViewById(R.id.lvPersonel);
    
    
        return v;
    }
    

    【讨论】:

    • 是的,这个片段可以工作,谢谢,但其他片段有一个错误“没有找到 id 的视图”?我不知道什么是错误的,因为两者都有相同的代码
    • 首先,请确保您的资源文件中有 R.layout.fragment_dahiliye 和 R.id.lvPersonel 然后,请确保您没有在有该错误的类中导入 android.R
    【解决方案2】:

    你必须像这样使用onCreateView,因为你在你的logcat的第63行得到NullPointerException,因为你的getView()方法返回null;因为你在膨胀根布局之前使用getView()

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View rootView = inflater.inflate(R.layout.fragment_dahiliye, container, false);
       //then use findViewById like that because you getting nullpointerexception
       lvPersonel = (ListView) rootView.findViewById(R.id.lvPersonel);
       return rootView;
    }   
    

    【讨论】:

      【解决方案3】:

      在你的onCreateView方法中,先给视图充气,充气后找到你的ListView lvPersonel。例如,

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
      
          View view = inflater.inflate(R.layout.fragment_dahiliye, container, false);
          new JSONTask().execute("https://api.myjson.com/bins/4hopr");
      
          DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
          ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity()).defaultDisplayImageOptions(defaultOptions)
          .build();
          ImageLoader.getInstance().init(config); // Do it on Application start
      
          lvPersonel = (ListView) getView().findViewById(R.id.lvPersonel);
      
      
          return view;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多