I have a problem using Volley, I cant get data out from OnResponse mehod.
I need to use the List outside , for Fragment operations, but i couldn`t get it out from there. Maybe im doing something wrong, but i was unable to find a solution on other sites.
Can anyone help me find a solution please?
Here is my code:
public class MainActivity extends AppCompatActivity
{
private static final String JSON_URL = "http://Something/v1/Api.php?apicall=gettopics";
ListView listView;
List<Topic> topicList;
List<Topic> topicList2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listViewTopics);
topicList = new ArrayList<>();
loadTopics();
if(topicList.isEmpty())
{
TextView t = findViewById(R.id.text);
t.setText("Empty");
}
}
class TopicAdapter extends ArrayAdapter<Topic>
{
List<Topic> topicList;
public List<Topic> getTopicList() {
return topicList;
}
public TopicAdapter(List<Topic> topicList)
{
super(MainActivity.this, R.layout.layout_topic_list, topicList);
this.topicList = topicList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.layout_topic_list, null, true);
TextView textViewName = listViewItem.findViewById(R.id.textViewTitle);
final Topic topic = topicList.get(position);
textViewName.setText(topic.getTitle());
return listViewItem;
}
}
public void loadTopics() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray topicArray = obj.getJSONArray("topics");
for (int i = 0; i < topicArray.length(); i++) {
JSONObject topicObject = topicArray.getJSONObject(i);
Topic topic = new Topic(topicObject.getInt("id"),topicObject.getInt("ordering"),topicObject.getString("title"));
topicList.add(topic);
}
TopicAdapter adapter = new TopicAdapter(topicList);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Firstly in onCreate():
topicList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listViewTopics);
adapter = new TopicAdapter(topicList); //note:define 'adapter' as a class field as 'listView'
listView.setAdapter(adapter);
Then in onResponse():
topicList.clear();
try{
JSONObject obj = new JSONObject(response);
JSONArray topicArray = obj.getJSONArray("topics");
for (int i = 0; i < topicArray.length(); i++) {
JSONObject topicObject = topicArray.getJSONObject(i);
Topic topic = new Topic(topicObject.getInt("id"),topicObject.getInt("ordering"),topicObject.getString("title"));
topicList.add(topic);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
Related
I have created a Recycler view that is supposed to be created when the activity is created. Currently, when I click a button on my MainActivity, an intent launches the ListActivity which has my recyclerview but it doesn't load. I have used toast message to confirm that each method is getting called, and that I am getting the correct data from the API. If I reset the activity using the restart activity option in Android Studio the Recycler shows up and functions correctly. I don't know what I'm doing wrong.
Here is my ListActivity:
private RecyclerView myrecyclerview;
private RecyclerView.Adapter myadapter;
private RecyclerView.LayoutManager mylayoutmanager;
static RequestQueue listqueue;
static final private String url = "https://swapi.dev/api/people/";
static ArrayList<RecyclerItem> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().hide();
listqueue = Volley.newRequestQueue(this);
myrecyclerview = findViewById(R.id.characterlist);
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
parseJsonData();
}
public void parseJsonData(){
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonarray = response.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String height = jsonobject.getString("height");
String mass = jsonobject.getString("mass");
String eyecolor = jsonobject.getString("eye_color");
String birthyear = jsonobject.getString("birth_year");
//list.add(new RecyclerItem("darth vader", "200", "128", "1950", "red"));
list.add(new RecyclerItem(name, "Height: " + height, "Mass: " + mass, "Birth Year: " + birthyear, eyecolor));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
listqueue.add(request);
}
#Override
public void onCharacterClick(int position) {
String color = list.get(position).getEyecolor();
Toast.makeText(getApplicationContext(), color, Toast.LENGTH_SHORT).show();
}
} ```
Like I mentioned, once I reload the activity, it works correctly. But I want the recycler view to show when I navigate to the activity.
The problem is that the first time that the activity is create, list is empty and parseJsonData() is running on the background filling that list.
Once you reload the activiy, the list and adapter are filled therefore when you call
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
the recycler view is show. Try to do this on your parseJsonData(); after the loop ends, then create the adapter and show the rv
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
....
}
myadapter = new MyAdapter(list, this);
....
myrecyclerview.setLayoutManager(mylayoutmanager);
I hope it help for u
Creat a List
private List< TipsList > tipsLists = new ArrayList<>();
SET UP RECYCLERVIEW LIKE THIS
RecyclerView tipsRv = findViewById(R.id.tips_rv);
TipsAdapter adapter = new TipsAdapter(tipsLists, this);
tipsRv.setAdapter(adapter);
tipsRv.setHasFixedSize(true);
tipsRv.setLayoutManager(new LinearLayoutManager(this));
getDATA
public void getWallis() {
String myJSONStr = method.loadJSON();
try {
JSONObject ROOT_OBJ = new JSONObject(myJSONStr);
JSONArray MAIN_ARRAY = ROOT_OBJ.getJSONArray("ff_api");
JSONObject TIPS_OBJ = MAIN_ARRAY.getJSONObject(3);
JSONArray TIPS_ARRAY = TIPS_OBJ.getJSONArray("Tips");
for (int i = 0; i < TIPS_ARRAY.length(); i++) {
TipsList tipsList = new TipsList();
JSONObject jsonObject = TIPS_ARRAY.getJSONObject(i);
tipsList.setId(jsonObject.getInt("id"));
tipsList.setTipsTitle(jsonObject.getString("tipsTitle"));
tipsList.setTipsDec(jsonObject.getString("tipsDec"));
tipsLists.add(tipsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I have list data recycler view and I want to make it like a table layout and dynamical. Here is the example view of the table that I want to make:
https://ibb.co/q7zYM64
And this is my condition app :
https://ibb.co/JKXwthj
and this is my main_activity.java :
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "http://sipermata.bappedawaykanan.com/api/admin/jumlah_penduduk_kabupaten/list?year=2019";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("data");
//JSONArray array = new JSONArray(s);
for (int i = 0 ; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
//String tahun = o.getString("year");
JSONObject isitahun = o.getJSONObject("year");
Iterator<String>itr = isitahun.keys();
//for(int j = 0; j<=isitahun.length();j++){
while (itr.hasNext()){
String key = itr.next();
JSONObject a = isitahun.getJSONObject(key);
String tahun = a.getString("value");
ListItem item = new ListItem(
id, kec, avg, key, tahun
);
listItems.add(item);
}
}
adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
You can set layout as horizontal.
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManager);
I know this question has been asked so many times, but none of the solutions answered there seems to solve my problem.
Most of the solutions suggested attaching an adapter (setadapter()) and I have done that. But the problem still seems to persist.
I also checked if my listitems are empty and it isn't.
I have attached the adapter in a function loadUserAccounts().
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_accounts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Swipe to refresh
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.userSwipeRefresh);
//Recycler View
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//Function to load the users to the recycler view
loadUserAccounts();
/*
* Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user
* performs a swipe-to-refresh gesture.
*/
swipeRefresh.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("Swipe_log: ", "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
loadUserAccounts();
}
}
);
}
and this is my loadUserAccounts() function:
/**
* Function to load the user account
* into the recycler view from the log database
*/
public void loadUserAccounts(){
String tag_string_req = "req_user_acc";
clear();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_USER_ACCOUNTS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
listItems.add(item);
}
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error!=null && error.getMessage() !=null){
Log.e(TAG,"User Accounts Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_LONG).show();
}
}
});
//Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
if (swipeRefresh == null)
return;
else {
if (swipeRefresh.isRefreshing()) {
swipeRefresh.setRefreshing(false);
}
}
}
My adapter class RecyclerViewUserAdapter
public class RecyclerViewUserAdapter extends RecyclerView.Adapter<RecyclerViewUserAdapter.ViewHolder> {
private List<ListItem_RecyclerView_User> listItems;
private Context context;
public RecyclerViewUserAdapter(List<ListItem_RecyclerView_User> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_recycler_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewUserAdapter.ViewHolder holder, int position) {
ListItem_RecyclerView_User listItem = listItems.get(position);
holder.txtUserName.setText(listItem.getTxtUserName());
holder.txtUserCpf.setText(listItem.getTxtUserCpf());
holder.txtAccountType.setText(listItem.getTxtAccountType());
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
date = df.parse(listItem.getTxtCreatedDate());
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String loginTime = sdf.format(date);
holder.txtCreatedDate.setText(loginTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView txtUserName;
private TextView txtUserCpf;
private TextView txtAccountType;
private TextView txtCreatedDate;
public ViewHolder(View itemView) {
super(itemView);
txtUserName = (TextView) itemView.findViewById(R.id.txtUserName);
txtUserCpf = (TextView) itemView.findViewById(R.id.txtUserCpf);
txtAccountType = (TextView) itemView.findViewById(R.id.txtAccountType);
txtCreatedDate = (TextView) itemView.findViewById(R.id.txtCreatedDate);
}
}
}
Try this...
modify that getItemCount() to like this.
#Override
public int getItemCount() {
return listItems.size();
}
Try this
Create your adapter with empty list data
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
// your normal code
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
// create new adapter
recyclerViewUserAdapter = new RecyclerViewUserAdapter(new ArrayList<>(), userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//your normal code
}
In your response
#Override
public void onResponse(String response) {
try {
List<ListItem_RecyclerView_User> responseList = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
responseList.add(item);
}
/*recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);*/
// write method to update your data
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
In your adapter create method
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged():
}
How can i display this to Recyclerview? i already got the data of the id i want to display it on Recyclerview. i want to filter the data that depends on the current user.. btw i am using navigation drawer and it is on fragment.
this is the logcat.
i want to the data of the given id to recyclerview. but the problem is it wont display. please help.. thanks in advance here is my code.
this is the 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();
}
this is the php. i dont know if my json code format is wrong.
<?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));
}
}
?>
i think you need to filter the data in your recycler view. if thats the issue, there is inbuilt Filter method to filter the datas from inside recycler view adapter.
below is the code used to filter contacts using filter method...
#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();
}
};
}
just check above code and change according to your need, as i cannot correctly figure your issue.
Thank you. :)
I have php file when user post existing ticknumber the php will echo JSON code for one array of that was posted, I linked it with Activity that will do same job of php file but when I click on button nothing show up in Listview !!
<?php
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
require_once('config.php');
$con->set_charset('utf8');
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[5], 'subject' =>$get[4],'response' =>$get[6]));
}
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
SupportActivity.java
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aaa/getticket.php";
private RequestQueue requestQueue1;
int i ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("error")) {
Toast.makeText(supportActivity.this, "please check the number", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject ticket ;
JSONArray jsonArray = new JSONArray("responseticket");
ticket = jsonArray.getJSONObject(Integer.parseInt(response));
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
SupportAdapter.java
public class supportAdapter extends ArrayAdapter<supportContent> {
private Context context;
private List<supportContent> contents;
public supportAdapter(Context context, List<supportContent> con){
super(context, R.layout.supportcontent, con);
this.contents = con;
}
#Override
public int getCount(){
return contents.size();
}
public View getView(int position, View convertview, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(getContext());
View supcon = inflater.inflate(R.layout.supportcontent, null);
TextView ticketnumber = (TextView)supcon.findViewById(R.id.ticketnumber);
ticketnumber.setText(contents.get(position).getTicketnumber());
TextView supportsubject = (TextView)supcon.findViewById(R.id.supportsubject);
supportsubject.setText(contents.get(position).getSubject());
TextView response = (TextView)supcon.findViewById(R.id.response);
response.setText(contents.get(position).getResponse());
return supcon;
}
}
Parse your response as below -
JSONObject jObj = new JSONObject(response);
JSONArray jResponseTicketarray = jObj.getJSONArray("responseticket");
JSONObject jTicket = jResponseTicketarray.getJSONObject(0);
String Ticketnumber = jTicket.getString("ticketnumber");
String Subject = jTicket.getString("subject");
String Response = jTicket.getString("response");
response - returned Json response in onResponse() mth.
jResponseTicketarray.getJSONObject(0); - here '0' is first element in ResponseTicketArray. If der are multiple object u might wanna iterate thr loop and extract required fields.
Modify below code too -
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
to below -
supportContent support = new supportContent();
support.setTicketnumber(TicketNumber);
support.setSubject(Subject);
support.setResponse(Response);