自定义适配器不显示数据

时间:2018-09-29 07:31:28

标签: java android adapter

我试图创建一个自定义适配器,并向其传递一个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数组已正确传递到适配器。

1 个答案:

答案 0 :(得分:0)

您的问题似乎不清楚。您所说的“什么都没有显示。”是什么意思。请提供您的JSON文件,以及该文件也可能出错的地方。