Please help me to fix this code , i"m a new programmer and start learn java at android studio. here the code . i have fixed it but not complate . so many problem
private void request()
{
Log.d("VOLLE------","MAUKKKK");
JsonArrayRequest requestItem = new JsonArrayRequest(Request.Method.POST, url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject data = response.getJSONObject(i);
OurData item = new OurData();
item.setId(data.getString("idperawatan"));
item.setmText1(data.getString("nama"));
item.setmText2(data.getString("alamat"));
item.setmImageResource(data.getString("image"));
mList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(requestItem);
}
Looks like it's complaining about mismatched arguments in JsonArrayRequest(). Try removing the POST method and JSONArray arguments and pass the url String as the first parameter:
private void request() {
Log.d("VOLLE------","MAUKKKK");
JsonArrayRequest requestItem = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject data = response.getJSONObject(i);
OurData item = new OurData();
item.setId(data.getString("idperawatan"));
item.setmText1(data.getString("nama"));
item.setmText2(data.getString("alamat"));
item.setmImageResource(data.getString("image"));
mList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(requestItem);
}
Related
I know this is common to ask but I've already trying clear() the items since before initiate the function, but it seems it always duplicate the items, This date is comes from my MySql database but I've check my SQL but it does not duplicate names and I think the problems is in code in java which rendered ArratList but I've tried countryList.clear(); but nothings happens,need help. I have two Spinner/dropdown the second spinner depends on the first spinner list
//First Dropdown Country
public void CountryListDropdown(){
countryList.clear();
String url = "http://192.168.254.103/csu_clinic/populate_country.php";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("countries");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String countryName = jsonObject.optString("country_name");
countryList.add(countryName);
countryAdapter = new ArrayAdapter<>(SignUp.this,
android.R.layout.simple_spinner_item, countryList);
// countryAdapter.clear();
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(countryAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
spinnerCountry.setOnItemSelectedListener(this);
}
//Second Dropdown that depends on dropdown 1 populate list depends from dropdown one
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(adapterView.getId() == R.id.spinnerCountry){
cityList.clear();
String selectedCountry = adapterView.getSelectedItem().toString();
String url = "http://10.0.2.2/android/populate_city.php?country_name="+selectedCountry;
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("cities");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String cityName = jsonObject.optString("city_name");
cityList.add(cityName);
cityAdapter = new ArrayAdapter<>(SignUp.this,
android.R.layout.simple_spinner_item, cityList);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCity.setAdapter(cityAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
Try changing your code like this.
public void CountryListDropdown() {
String url = "http://192.168.254.103/csu_clinic/populate_country.php";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("countries");
countryList.clear();
for(int i=0; i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String countryName = jsonObject.optString("country_name");
countryList.add(countryName);
}
countryAdapter = new ArrayAdapter<>(SignUp.this,android.R.layout.simple_spinner_item, countryList);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(countryAdapter);
spinnerCountry.setOnItemSelectedListener(this);
} catch (JSONException e) {
e.printStackTrace();
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {}
});
requestQueue.add(jsonObjectRequest);
}
I built a login system that checks the input of the user and checks with the data if he can log in.
The server side of the application is working fine but I'm not able to stop the main thread of the application and wait for the response to arrive.
basically I'm using Volley library to communicate with my server. first of all, is send the username to check if such one even exists in the database, secondly, I check the combination of the password and username. and if these checks are fine I receive the user unique id which the user needs for the rest of the app.
This is the code that handles the java login process:
public void toMainLobby(View view)
{
if(LoginIsValid()) //check if the user can log in
{
getUserID();
}
}
/**
* the function checks if the login details are correct
* #return boolean whether the login details are correct
*/
private boolean LoginIsValid()
{
pop_up_message.setText("");
//check if the fields are empty
if(username.getText().toString().equals("") || password.getText().toString().equals(""))
{
pop_up_message.setText("Please fill all fields");
return false;
}
resetBooleans();
Log.d("FinalDebug","send the request");
thread = new Thread(new Runnable() {
#Override
public void run() {
checkIfUsernameIsTaken(new VolleyCallBack() {
#Override
public void onSuccess() {
Log.d("FinalDebug","on success");
}
});
}
});
thread.start();
waitForResponse();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(!flag)
{
pop_up_message.setText("Username doesn't exist");
return false;
}
resetBooleans();
checkLogin(new VolleyCallBack() {
#Override
public void onSuccess() {
hasChanged = true;
}
});
waitForResponse();
if(!flag)
{
pop_up_message.setText("Password incorrect");
return false;
}
return true;
}
public void getUserID()
{
StringRequest getuserid = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("ID"))
{
String value = jsonObject.getString("ID");
String newvalue = value.substring(2,value.length() - 2);
if(!newvalue.equals("0"))
{
id = Integer.parseInt(newvalue);
Toast.makeText(getApplicationContext(),newvalue,Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),iJam_Main_Lobby.class);
intent.putExtra("username",username.getText().toString());
intent.putExtra("id", id);
startActivity(intent);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("type_of_request","GET_USER_ID");
hashMap.put("username",username.getText().toString());
return hashMap;
}
};
MySingelton.getInstance(this).addToRequestQueue(getuserid);
}
//private methods
private void checkLogin(final VolleyCallBack volleyCallBack)
{
StringRequest checkLog = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("isValid"))
{
String ans = jsonObject.getString("isValid"); //extracts the isValid value
//checks the response
String newString = ans.substring(1,ans.length() - 1);
Toast.makeText(getApplicationContext(),"login response: " + newString,Toast.LENGTH_LONG).show();
Log.d("result from server",newString);
if(!newString.equals("true"))
{
flag = false;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
volleyCallBack.onSuccess();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("type_of_request","LOGIN");
hashMap.put("username",username.getText().toString());
hashMap.put("password",password.getText().toString());
return hashMap;
}
};
MySingelton.getInstance(this).addToRequestQueue(checkLog);
}
private void resetBooleans()
{
flag = false;
hasChanged = false;
}
private void checkIfUsernameIsTaken(final VolleyCallBack volleyCallBack)
{
StringRequest checkUsername = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("isValid"))
{
String ans = jsonObject.getString("isValid"); //extracts the isValid value
//checks the response
String newString = ans.substring(1,ans.length() - 1);
Toast.makeText(getApplicationContext(),"Response about username existence: " + newString,Toast.LENGTH_LONG).show();
Log.d("result from server",newString);
if(newString.equals("true"))
{
flag = true;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
hasChanged = true;
volleyCallBack.onSuccess();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("type_of_request","CHECK_USERNAME_EXISTENCE");
hashMap.put("username",username.getText().toString());
return hashMap;
}
};
MySingelton.getInstance(this).addToRequestQueue(checkUsername);
}
private void waitForResponse()
{
for(int i = 0; i < 10; i++)
{
if (!hasChanged)
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
{
return;
}
}
return;
}
}
*disclaimer - the toasts and the log.d lines are for debugging purposes.
This app is to fetch data from api.github.com/users and reflect on spinner
I am getting data in logs on Splash.java but unable to reflect data on Home.java
MyAppDatabase.java
#Database(entities = {Users.class}, version = 1, exportSchema = false)
public abstract class MyAppDatabase extends RoomDatabase {
public abstract MyDao myDao();
}
MyDao.java
#Dao
public interface MyDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void addUsers(Users users);
#Query("SELECT * FROM Users")
List<Users> getUsers();
#Query("SELECT node_id FROM Users")
List<String> getNodeId();
}
getData() on Splash.java
public class Splash extends AppCompatActivity {
MyAppDatabase myAppDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class, "MyDao").allowMainThreadQueries().build();
//get data from webservice and store locally
getData();
}
}, 500);
}
private void getData() {
//Creating a string request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
response.length();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonArrayRequest);
}
}
putData() on Home.java
public class Home extends AppCompatActivity {
MyAppDatabase myAppDatabase;
//To add into spinner
private ArrayList<String> userType;
//List of users from Db
List<Users> users;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userType = new ArrayList<>();
spinner = findViewById(R.id.sp_user_type);
myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class,"UsersDb").allowMainThreadQueries().build();
//get data from Db and put into arrayList for spinner
putData();
}
private void putData() {
users =myAppDatabase.myDao().getUsers();
userType.add("Select UserType"); //Dummy addition
for(int i = 0; i < users.size(); i++){
userType.add(users.get(i).getType());
Log.e("DistNames",users.get(i).getType());
}
users.size();
spinner.setAdapter(new ArrayAdapter<>(Home.this, android.R.layout.simple_spinner_dropdown_item, userType));
}
}
Because you are starting activity in the loop itself, which should be actually outside the loop.
Actually, the mistake that you are doing is it will launch Home activity in the first iteration itself and so you are not getting all the data from the API response. To solve this, let the loop iterates through each entry and add into the database, and start the activity when it completes and so outside the loop.
Wrong:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
Correct:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});
I am trying to pull a list of Geofence names from the database using JSON and for loop, but it does not add anything on the RecycleView.
However if i manually add a string such as the example comment mTextNames.add("HARRY POTTER")and it shows up just fine.
private void initGeofenceNames(){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, HttpUrl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
Log.d(TAG, "GeofenceManageListActivity: jsonObject called");
mGeofenceNames.add(jsonObject.getString("geof_name"));
for (String s : mGeofenceNames){
mTextNames.add(s.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "GeofenceManageListActivity: " + error.toString());
}
});
requestQueue.add(jsonArrayRequest);
//mTextNames.add("HARRY POTTER");
initRecyclerView();
}
EDIT:
private void initRecyclerView(){
RecyclerView recyclerView = findViewById(R.id.geofenceManagementListRecyclerView);
GeofenceManagementListRecyclerViewAdapter adapter = new GeofenceManagementListRecyclerViewAdapter(mTextNames, this );
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
Use as your method
private void initGeofenceNames(){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, HttpUrl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
Log.d(TAG, "GeofenceManageListActivity: jsonObject called");
mGeofenceNames.add(jsonObject.getString("geof_name"));
for (String s : mGeofenceNames){
mTextNames.add(s.toString());
}
initRecyclerView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "GeofenceManageListActivity: " + error.toString());
}
});
requestQueue.add(jsonArrayRequest);
//mTextNames.add("HARRY POTTER");
}
Second Option
create class level adapter veriable
as
private GeofenceManagementListRecyclerViewAdapter adapter;
private void initRecyclerView(){
RecyclerView recyclerView = findViewById(R.id.geofenceManagementListRecyclerView);
adapter = new GeofenceManagementListRecyclerViewAdapter(mTextNames, this );
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
private void initGeofenceNames(){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, HttpUrl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
Log.d(TAG, "GeofenceManageListActivity: jsonObject called");
mGeofenceNames.add(jsonObject.getString("geof_name"));
for (String s : mGeofenceNames){
mTextNames.add(s.toString());
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "GeofenceManageListActivity: " + error.toString());
}
});
requestQueue.add(jsonArrayRequest);
//mTextNames.add("HARRY POTTER");
initRecyclerView();
}
try to put "initRecyclerView()" inside onResponse
try {
JSONObject jsonObject = response.getJSONObject(i);
Log.d(TAG, "GeofenceManageListActivity: jsonObject called");
mGeofenceNames.add(jsonObject.getString("geof_name"));
for (String s : mGeofenceNames){
mTextNames.add(s.toString());
}
initRecyclerView();
} catch (JSONException e) {
e.printStackTrace();
add adapter.notifyDataSetChanged(); like below
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
Log.d(TAG, "GeofenceManageListActivity: jsonObject called");
mGeofenceNames.add(jsonObject.getString("geof_name"));
for (String s : mGeofenceNames){
mTextNames.add(s.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged(); //change here
}
},