JSONObject and for loop not working in RecycleView - java

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
}
},

Related

Array List duplicate items in Android Studio

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);
}

getParams() with JsonArrayRequest

I am trying to get the response from the server based on the data I send it, I am able to get a response from the server, but the server doesn't seem to be receiving the values in the getParams().
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Toast.makeText(getContext(), selectedUniversityItem.getmUniversityValue(), Toast.LENGTH_SHORT).show();
params.put("schoolUniversity", selectedUniversityItem.getmUniversityValue());
params.put("key", key);
return params;
}
};
queue.add(jsonRequest);
The method I would suggest in this case is to pass the parameters in the URL of your code and remove the getParams() method.
So, your modified code looks like;
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url+"?schoolUniversity="+selectedUniversityItem.getmUniversityValue()+"&key="+key,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
};
queue.add(jsonRequest);
Hopefully, this will work. Good Luck :)

Cannot fetch data from room database to Spinner

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());
}
});

JSON Array request cannot be applied error about constructor

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);
}

How to create a single volley webservice class to use across the android app?

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
}
});

Categories

Resources