代码之家  ›  专栏  ›  技术社区  ›  Pratik Verma

AsyncTask未使用BaseApter创建GridView

  •  0
  • Pratik Verma  · 技术社区  · 7 年前

    我是安卓开发新手,对此我有非常基本的了解。到目前为止,我通过这个网站或youtube视频实现了这一点。我被困在AsyncTask中(之前我在Create View上使用了。get(),它工作得很好,但UI被阻止,直到任务完成。为了避免UI阻塞,我被建议删除。从OnCreateView()函数中获取()函数。删除此函数后,即时消息无法从AsyncTask中获取任何数据。我这么做了,但现在我无法创建视图。我做了很多研究,但无法获得这样的优势

    这是我的代码。请帮助我如何从中创建视图

    OnCreateView():-

        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View GView = inflater.inflate(R.layout.fragment_dashboard, container, false);
        progressBarHolder = (FrameLayout) GView.findViewById(R.id.progressBarHolder);
        GridView gridView = (GridView) GView.findViewById(R.id.gridView);
        //Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
        String finalResult = null;
        try{
            finalResult = String.valueOf(new JSONTask().execute("https://www.example.in/android_api/dashboard_data",JsonData()));
            Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
            JSONObject parentObject = null;
            parentObject = new JSONObject(finalResult);
            if(((String) parentObject.names().get(0)).matches("error")){
                JSONObject jObj = parentObject.getJSONObject("error");
                errorThrow(jObj.getString("Description"));
            } else if(((String) parentObject.names().get(0)).matches("success")){
                JSONObject jObj = parentObject.getJSONObject("success");
                JSONArray arrajson = jObj.getJSONArray("data");
                String arrayCount = Integer.toString(arrajson.length());
                String[] type = new String[arrajson.length()];
                Integer[] count = new Integer[arrajson.length()];
                for (int i=0; i<arrajson.length();i++){
                    JSONObject jsonObject = arrajson.getJSONObject(i);
                    type[i] = jsonObject.getString("type");
                    count[i] = jsonObject.getInt("count");
                }
                CustomAdpter customAdpter = new CustomAdpter(DashboardFragment.this,type,count);
                gridView.setAdapter(customAdpter);
                return GView;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return GView;
    }
    

    基本适配器代码:-

        class CustomAdpter extends BaseAdapter {
    
        String[] type;
        Integer[] count;
        public CustomAdpter(DashboardFragment dashboardFragment, String[] type, Integer[] count){
            this.count = count;
            this.type = type;
        }
        @Override
        public int getCount() {
            return type.length;
        }
    
        @Override
        public Object getItem(int i) {
            return null;
        }
    
        @Override
        public long getItemId(int i) {
            return 0;
        }
    
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.grid_single_itme,null);
            TextView textView = (TextView) view.findViewById(R.id.TextView1);
            TextView textView1 = (TextView) view.findViewById(R.id.textView2);
            textView.setText(String.valueOf(count[i]));
            textView1.setText(type[i]);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getActivity(),"Booking Item Clicked",Toast.LENGTH_LONG).show();
                }
            });
            return view;
        }
    }
    

    异步任务代码:-

        public class JSONTask extends AsyncTask<String,String,String> {
        private ProgressDialog mProgressDialog;
    
        int progress;
        public JSONTask(){
            mProgressDialog = new ProgressDialog(getContext());
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(0);
        }
    
        @Override
        protected void onPreExecute(){
            mProgressDialog = ProgressDialog.show(getContext(),"Loading","Loading Data...",true,false);
            super.onPreExecute();
        }
    
        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            final String finalJson = params[1];
            String json = finalJson;
            try{
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                connection.setRequestProperty("A-APK-API", "******");
                connection.setRequestProperty("Authorization", "Basic **:**");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.connect();
    
                OutputStream stream = connection.getOutputStream();
                OutputStreamWriter streams =  new OutputStreamWriter(stream, "UTF-8");
                stream.write(json.getBytes("UTF-8"));
                stream.close();
    
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
    
                StringBuffer buffer = new StringBuffer();
    
                String line = "";
                while((line = reader.readLine()) != null){
                    buffer.append(line);
                }
                return buffer.toString();
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(connection != null){
                    connection.disconnect();
                }
                try {
                    if(reader != null) {
                        reader.close();
                    }
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
            return null;
        }
        protected void onPostExecute(String result){
            super.onPostExecute(result);
            Json_String = result;
            Toast.makeText(getContext(),result,Toast.LENGTH_LONG).show();
            mProgressDialog.dismiss();
        }
    }
    

    请帮帮我

    2 回复  |  直到 7 年前
        1
  •  1
  •   greenapps    7 年前

    如果不使用,则无法从asynctask获得结果。get()。

    所以,改变这一说法。仅启动asynctask。

    然后将所有代码放在AsyncTask的onPostExecute()中该行之后。

    仅此而已。

        2
  •  0
  •   himel    7 年前

    您应该更改创建适配器和连接的方式 你应该这样做

    1、首先通过 AsyncTask , doInBackGround

    1. 然后在 onPostExecute 方法检索数据并创建适配器并将其附加到视图
    2. 在获取数据时,您可以显示一些 ProgressDialog .
    3. 如果你的 异步任务 在另一个单独的类中,然后使用接口从 班 看看这个 https://stackoverflow.com/a/47373959/8197737