【问题标题】:List view in fragment with Async Task带有异步任务的片段中的列表视图
【发布时间】:2017-09-19 09:33:38
【问题描述】:

my error log 我试图在我的片段中加载列表视图。但是我的应用程序在单击按钮以填充我的列表视图时崩溃。我不知道我犯了什么错误。任何帮助将不胜感激。我已经尝试了大部分关于此的东西..但没有什么效果很好。(我删除了一些代码以避免笨拙的外观)

这是我的片段代码:

public class Func extends Fragment {

    ArrayList<Flowers> flowersList = new ArrayList<Flowers>();

    String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";

    @Override
    public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
                                          Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab2, container, false);

        FlowerAdapter adapter=new FlowerAdapter(getActivity().getApplicationContext(),R.layout.flower_list_xml,flowersList);
        ListView listView=(ListView)rootView.findViewById(R.id.listView);
        listView.setAdapter(adapter);

        return rootView;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Button b = (Button)getView().findViewById(R.id.button);

        b.setOnClickListener( new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                new BackTask().execute(url);

            }

        });

    }

// 我的异步任务从这里开始

 public class BackTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String... strings) {
            String result = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                Log.d("testhtt2", "test");
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                Log.d("test44", sb.toString());
                return sb.toString();

            } catch (Exception e) {
                e.printStackTrace();
                return null;

            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;

                    }
                }

                return result;
            }
        }
  @Override
        protected void onPostExecute(String s){
            try {
                JSONArray ar =new JSONArray(s);
                for (int i = 0; i < ar.length(); i++){
                    JSONObject jsonObject=ar.getJSONObject(i);
                    Flowers flowers= new Flowers();
                    flowers.setName(jsonObject.getString("NAME"));
                    flowersList.add(flowers);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

【问题讨论】:

  • 也发布错误
  • 发布错误日志....
  • 没有什么好用的?所以没有人会帮助你。你应该更具体。
  • 是的,等等@Anonymous @ Ricky Patel
  • 对不起兄弟我会解释@Hetfieldan24

标签: java android json listview android-fragments


【解决方案1】:

您在 doInBackground 中返回 null,然后尝试在 OnPostExecute 中将其解析为 JSONArray。从你的 doInBackground 方法返回一个正确的字符串,看看是否有帮助。

【讨论】:

    【解决方案2】:

    在使用 getView() 之前做一个空检查

    if(getView()!=null){
    //Your code     
    }
    

    另外,最好使用 getview() 的 rootview 初始化 oncreate 视图中的按钮

    编辑

    您正在执行的网络调用必须移动到 doInBackground,因为它应该在后台线程中完成并获取结果。获取的结果应该添加到 onPostExecute 的列表中。希望这对您有所帮助

    public class SampleClass extends AsyncTask<String, Void, String> {
    
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(String... strings) {
        BufferedReader reader = null;
        String result=null;
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            Log.d("testhtt2", "test");
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            Log.d("test44", sb.toString());
            result= sb.toString();
    
        } catch (Exception e) {
            e.printStackTrace();
            result= null;
    
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    result= null;
    
                }
            }
            return result;
        }
    }
    
    @Override
    protected void onPostExecute(String s){
        try {
            JSONArray ar =new JSONArray(s);
            for (int i = 0; i < ar.length(); i++){
                JSONObject jsonObject=ar.getJSONObject(i);
                Flowers flowers= new Flowers();
                flowers.setName(jsonObject.getString("NAME"));
                flowersList.add(flowers);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      您可以尝试在 onViewCreated() 方法中使用 view 而不是 getView()。

        public class ListView extends Fragment {
      @Nullable
      @Override
      public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
          View rootView = inflater.inflate(R.layout.tab2, container, false);
          return rootView;
      }
      
      @Override
      public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
          super.onViewCreated(view, savedInstanceState);
          Button b = (Button) view.findViewById(R.id.button);
          b.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  new BackTask().execute("http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData");
              }
          });
      }
      
      private class BackTask extends AsyncTask<String, Void, String> {
          String result;
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
          }
          @Override
          protected String doInBackground(String... params) {
              try {
                  result = Utility.executeHttpGet(params[0]);
              } catch (Exception e) {
                  Log.e("ListView", e.getMessage(), e);
              }
              return result;
          }
          @Override
          protected void onPostExecute(String s) {
              try {
                  JSONArray ar = new JSONArray(s);
                  for (int i = 0; i < ar.length(); i++) {
                      JSONObject jsonObject = ar.getJSONObject(i);
                  }
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          }
      }
      

      }

      【讨论】:

        【解决方案4】:

        试试这个代码

        public class Listview extends Fragment {
        
        ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
        String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
        
        ListView listview;
        View rootView;
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            if (rootView!= null) {
                ViewGroup parent = (ViewGroup) view.getParent();
                if (parent != null)
                    parent.removeView(view);
            }
            try {
                rootView = inflater.inflate(R.layout.tab2, container, false);
            } catch (InflateException ignored) {
            }
        
            listView=(ListView)rootView.findViewById(R.id.listView);
            Button b = (Button)rootView.findViewById(R.id.button);
            b.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new BackTask().execute(url);
                }
        
            });
            return view;
        }
        private class BackTask extends AsyncTask<String,String,String>{
        
            @Override
            protected void onPreExecute(){
                super.onPreExecute();
            }
            @Override
            protected String doInBackground(String... strings) {
                return null;
            }
            @Override
            protected void onPostExecute(String s){
                 try {
                   JSONArray ar =new JSONArray(s);
                   for (int i = 0; i < ar.length(); i++){
                   JSONObject jsonObject=ar.getJSONObject(i);
                   Flowers flowers= new Flowers();
                   flowers.setName(jsonObject.getString("NAME"));
                   flowersList.add(flowers);
             }
            FlowerAdapter adapter=new FlowerAdapter(getActivity(),R.layout.flower_list_xml,flowersList);
            listView.setAdapter(adapter);
        
            } catch (JSONException e) {
            e.printStackTrace();
           }
            }
          }
        
        }
        }
        

        【讨论】:

        • 它运行得不好兄弟。我想你还没有发布完整的代码。它向我展示了很多危险信号
        猜你喜欢
        • 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
        相关资源
        最近更新 更多