如何在recyclerview上获取当前id的数据

时间:2018-01-09 08:17:54

标签: java android android-studio android-volley

如何向Recyclerview显示此信息?我已经获得了id的数据,我想在Recyclerview上显示它。我想过滤依赖于当前用户的数据..顺便说一句,我使用导航抽屉,它是片段。

this is the logcat

这是logcat。

我想将给定id的数据发送给recyclerview。但问题是它不会显示。请帮忙..在此先感谢这里是我的代码。

这是AdapterApartment

public class AdapterApartment extends RecyclerView.Adapter<AdapterApartment.ViewHolderApartment> {

private Context mCtx;
private ArrayList<Apartment> apartmentList = new ArrayList <>();

public AdapterApartment(Context mCtx, ArrayList <Apartment> apartmentList) {
    this.mCtx = mCtx;
    this.apartmentList = apartmentList;
}

@Override
public ViewHolderApartment onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.layout_houses, null);
    return new ViewHolderApartment(view);
}

@Override
public void onBindViewHolder(ViewHolderApartment holder, int position) {
    Apartment apartment = apartmentList.get(position);


    holder.category.setText(apartment.getCategory());
    holder.apartmentname.setText(apartment.getApartmentname());
    holder.price.setText(String.valueOf(apartment.getPrice()));

}

@Override
public int getItemCount() {
    return apartmentList.size();
}

class ViewHolderApartment extends RecyclerView.ViewHolder {

    TextView category, apartmentname, price;

    public ViewHolderApartment(View itemView) {
        super(itemView);

        category = itemView.findViewById(R.id.textViewCategory);
        apartmentname = itemView.findViewById(R.id.textName);
        price = itemView.findViewById(R.id.textViewPrice);
    }
}

}

private String url = Server.URL + "viewapartment.php";
private String url2 = Server.URL + "listapartment.php";


private ArrayList<Apartment> apartmentList = new ArrayList <>();
private AdapterApartment adapterApartment;
private RecyclerView recyclerView;

private String id;
private String username;
private int success;
TextView txt_id, txt_username;

private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

String tag_json_obj = "json_obj_req";

ProgressDialog pDialog;


public static LandlordAddApartment newInstance(String id, String username) {
    LandlordAddApartment fragment = new LandlordAddApartment();

    Bundle args = new Bundle();
    args.putString(TAG_ID, id);
    args.putString(TAG_USERNAME, username);
    fragment.setArguments(args);
    return fragment;
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);


    if (getArguments() != null) {
        id = getArguments().getString(TAG_ID);
        username = getArguments().getString(TAG_USERNAME);
    }

}



@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v =  inflater.inflate(R.layout.landlord_add_apartment, container, false);

    txt_id = (TextView) v.findViewById(R.id.add_txt_id);
    txt_id.setText(id);
    txt_username = (TextView)v.findViewById(R.id.add_txt_username);
    txt_username.setText(username);






    checkUseriD(id);
    recyclerView = (RecyclerView)v.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    adapterApartment= new AdapterApartment(getActivity(), apartmentList);
    loadApartment();
    recyclerView.setAdapter(adapterApartment);


    FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), AddApartment.class);
            intent.putExtra(TAG_ID, id);
            intent.putExtra(TAG_USERNAME, username);
            startActivity(intent);
        }
    });
    return v;

}


protected boolean isNetworkConnected() {
    try {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return (mNetworkInfo == null) ? false : true;


    }catch (NullPointerException e){
        return false;

    }
}

private void checkUseriD(final String id) {

    pDialog = new ProgressDialog(getActivity());
    pDialog.setCancelable(false);
    pDialog.setMessage("searching ...");
    showDialog();


    StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url, new Response.Listener <String>() {
        @Override
        public void onResponse(String response) {
            Log.e(TAG, "get id Response: " + response.toString());
            hideDialog();


            try {
                JSONObject jObj = new JSONObject(response);
                JSONArray array = new JSONArray(response);
                success = jObj.getInt(TAG_SUCCESS);
                // Check for error node in json
                if (success == 1) {

                    Log.e("Success", jObj.toString());


                    Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            hideDialog();

        }
    }) {

        @Override
        protected Map <String, String> getParams() {
            // Posting parameters to login url
            Map <String, String> params = new HashMap <String, String>();
            params.put("userID", id);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(stringRequest1, tag_json_obj);

}
private void loadApartment() {

    String url;

    /*
    * Creating a String Request
    * The request type is GET defined by first parameter
    * The URL is defined in the second parameter
    * Then we have a Response Listener and a Error Listener
    * In response listener we will get the JSON response as a String
    *
    * */

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url2, new Response.Listener <String>() {
        @Override
        public void onResponse(String response) {
            try {
                //converting the string to json array object
                JSONObject object = new JSONObject(response);

                //traversing through all the object
                for (int i = 0; i < array.length(); i++) {

                    //getting product object from json array
                    JSONObject apartment = array.getJSONObject(i);

                    apartmentList.add(new Apartment(
                            apartment.getInt("userID"),
                            apartment.getString("Category"),
                            apartment.getString("apartmentName"),
                            apartment.getString("price_month")));
                }
                //creating adapter object and setting it to recyclerview
                AdapterApartment adapter = new 
          AdapterApartment(getContext(), apartmentList);
          recyclerView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });


    Volley.newRequestQueue(getActivity()).add(stringRequest);
}



private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}
这是php。我不知道我的json代码格式是否错误。

<?php 



$server="localhost";
$user   = "root"; 
$password= ""; 
$database= "albayboardinghouse";

$connect = mysql_connect($server, $user, $password) or die ("connect failed!");
mysql_select_db($database) or die ("Error!");

$userID = $_POST['userID'];

class emp{}

if (empty($userID)) { 
    $response = new emp();
    $response->success = 0;
    $response->message = "Error data"; 
    die(json_encode($response));
} else {
    $query = mysql_query("SELECT userID, Category, apartmentName, price_month  FROM apartmentlocation WHERE userID = '".$userID."'");
    $row = mysql_fetch_array($query);



    if (!empty($row)) {
        $response = new emp();
        $response->success = 1;
        $response->userID = $row["userID"];
        $response->Category = $row['Category'];
        $response->apartmentName = $row['apartmentName'];
        $response->price_month = $row['price_month'];
        die(json_encode($response));

        } 
        else{ 
        $response = new emp();
        $response->success = 0;
        $response->message = "Error getting Data";
        die(json_encode($response)); 
    }

}
?>

1 个答案:

答案 0 :(得分:-1)

我认为您需要过滤回收站视图中的数据。如果这就是问题,那么内置的Filter方法可以从Recycler视图适配器内部过滤数据。

下面的

是使用过滤方法过滤联系人的代码...

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String charString = charSequence.toString();
            if (charString.isEmpty()) {
                contactListFiltered = contactList;
            } else {
                List<Contact> filteredList = new ArrayList<>();
                for (Contact row : contactList) {

                    // name match condition. this might differ depending on your requirement
                    // here we are looking for name or phone number match
                    if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getPhone().contains(charSequence)) {
                        filteredList.add(row);
                    }
                }

                contactListFiltered = filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = contactListFiltered;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            contactListFiltered = (ArrayList<Contact>) filterResults.values;

            // refresh the list with filtered data
            notifyDataSetChanged();
        }
    };
}

只需检查上面的代码并根据您的需要进行更改,因为我无法正确解决您的问题。 谢谢。 :)