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);
}
Related
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);
}
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
}
},
This is my request:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<String> empresas = new ArrayList<String>();
for (Iterator<String> it = response.keys(); it.hasNext(); ) {
String key = it.next();
try {
String empresa = (String) response.get(key);
empresas.add(empresa);
empresasMap.put(key, empresa);
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(EmpresasFetch.this.localContext,
R.layout.list_mobile, empresas);
EmpresasActivity.empresasList.setAdapter(adapter);
EmpresasActivity.empresasList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(EmpresasFetch.this.localContext,
parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
/*Intent intent = new Intent(view.getContext(), EmpresasActivity.class);
intent.putExtra("segmento", (String) parent.getItemAtPosition(position));
localContext.startActivity(intent);*/
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.err.println("It wasn't possible to fetch the server's data.");
System.err.println(error);
System.err.println(error.networkResponse);
}
});
The System.err.println(error.networkResponse); returns null:
W/System.err: It wasn't possible to fetch the server's data.
com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
W/System.err: null
I can't access the Android Profiler because the target version is lower than 21. How can I see that String that is returned from the webserver??
Hey i'm creating Android application which connect with my database MySQL. I created an ArrayList with categories and added it to Adapter and then to Spinner. I see Spinner items but after onClick nothing happens and when I try to check what is in my ArrayList I see that it is empty.Data downloaded.
After click in Spinner nothing change
Here is my code:
public class InsertProductActivity extends AppCompatActivity {
Spinner categories;
String categoriesURL = "myURL";
ArrayList<String> downloadedCategories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_product);
categories = findViewById(R.id.categories);
getCategories();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
}
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
for(int i=0;i<jsonArray.length();i++){
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
try this one.
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
downloadedCategories = new ArrayList<>(); // try to add your instantiation of your arrayList here.
for(int i=0;i<jsonArray.length();i++) {
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//this block of code will prompt after your downloadedCategories finish storing your objects to your arrayList because if you put this in onCreate this wil call before your getCategories process not finish yet. So much better its much safer here.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
requestQueue.add(jsonObjectRequest);
}