簡體   English   中英

自定義適配器不顯示數據

[英]Custom adapter doesn't show the data

我正在嘗試創建一個自定義適配器並向它傳遞一個 JSONArray,但它沒有顯示任何內容。 適配器是這樣的:

public class MasonryAdapter extends RecyclerView.Adapter<MasonryAdapter.MasonryView> {

    int[] imgList = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher,
            R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher,
            R.mipmap.ic_launcher, R.mipmap.ic_launcher};
    JSONArray arrayofresults;
    private Context context;

    public MasonryAdapter(Context context, String results) throws JSONException {
        this.context = context;
        arrayofresults = new JSONArray(results);
        Toast.makeText(context, "length" + arrayofresults.length(), Toast.LENGTH_LONG).show();
    }

    @Override
    public MasonryView onCreateViewHolder(ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
        MasonryView masonryView = new MasonryView(layoutView);
        return masonryView;
    }

    @Override
    public void onBindViewHolder(MasonryView holder, int position) {
        try {
            JSONObject tmpObj = arrayofresults.getJSONObject(position);
            holder.imageView.setImageResource(imgList[position]);
            Toast.makeText(context, "username" + tmpObj.getString("username"), Toast.LENGTH_LONG).show();
            holder.textView.setText(tmpObj.getString("username"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return arrayofresults.length();
    }

    class MasonryView extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;

        public MasonryView(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.img);
            textView = (TextView) itemView.findViewById(R.id.img_name);
        }
    }
}

我這樣設置: mRecyclerView.setAdapter(adapter); 但仍然沒有顯示任何內容。 我試圖在一個片段中展示它。 這是片段的代碼:

public class UserListFragment extends Fragment {
    TextView usernameView;
    RecyclerView mRecyclerView;
    Context context;
    MasonryAdapter adapter;
    private View view;

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

        view = inflater.inflate(R.layout.home_fragment, container, false);
        try {
            init();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return view;
    }

    private void init() throws JSONException {
        context = this.getActivity();
        usernameView = (TextView) view.findViewById(R.id.user);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.masonry_grid);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        new LoginRunner().execute("http://velvet.kavalinis.eu/getUsers.php");
    }

    public void showResult(String serverResponse) throws JSONException {
        if (serverResponse == null || serverResponse.isEmpty()) {
            final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
            TextView title = new TextView(context);
            title.setText(context.getResources().getString(R.string.login_fail_title));
            title.setPadding(10, 10, 10, 10);   // Set Position
            title.setGravity(Gravity.CENTER);
            title.setTextColor(Color.BLACK);
            title.setTextSize(20);
            alertDialog.setCustomTitle(title);
            TextView msg = new TextView(context);
            msg.setText(context.getResources().getString(R.string.login_fail));
            msg.setGravity(Gravity.CENTER_HORIZONTAL);
            msg.setTextColor(Color.BLACK);
            alertDialog.setView(msg);
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, context.getResources().getString(R.string.try_again_btn), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    alertDialog.cancel();
                }
            });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, context.getResources().getString(R.string.register_btn), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            new Dialog(context.getApplicationContext());
            alertDialog.show();
        } else {
            adapter = new MasonryAdapter(this.getActivity(), serverResponse);
            mRecyclerView.setAdapter(adapter);
            SpacesItemDecoration decoration = new SpacesItemDecoration(16);
            mRecyclerView.addItemDecoration(decoration);
        }
    }

    private class LoginRunner extends AsyncTask<String, String, String> {
        //private String resp;
        ProgressDialog progressDialog;

        @Override
        protected String doInBackground(String... params) {
            String responseStr = null;
            try {
                // HttpClient
                HttpClient httpClient = new DefaultHttpClient();
                // post header
                HttpPost httpPost = new HttpPost("https://velvet.gr);
                // add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("username", "test"));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // execute HTTP post request
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    responseStr = EntityUtils.toString(resEntity).trim();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return responseStr;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                showResult(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onPreExecute() {
            Toast.makeText(context, "Loading...", Toast.LENGTH_SHORT).show();
        }
    }

}

JSON 數組已正確傳遞給適配器。

好像你的問題不清楚。“它沒有顯示任何東西......”是什么意思。 請提供您的 JSON 文件,因為那里也可能出錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM