I'm having a problem with Volley and the RecyclerView.
In the onCreate Method of my Activity, I call a Volley Request to get data from my server. I then pass it to my Adapter as a List.
The thing is that everything is happening so fast when the onCreate method has finished my Volley Request hasn't finished yet, so nothing is displayed on the screen, how can I avoid this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__services__worker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Servicios");
final List services = new ArrayList();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Method.GET, AppConfig.URL_GET_SERVICES_REQUIRED, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag_servicio = jsonObject.getString("contratista");
String servicio = jsonObject.getString("descipcion_del_problema");
String zona = jsonObject.getString("zona");
String money = jsonObject.getString("precio_min");
//Toast.makeText(Activity_Services_Worker.this, tag_servicio+servicio+zona+money, Toast.LENGTH_SHORT).show();
services.add(new Servicios_worker(tag_servicio, servicio, zona, money));
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse (VolleyError error){
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(Activity_Services_Worker.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
recycler = (RecyclerView) findViewById(R.id.servicesAsked_RecyclerView);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new Adapter_services_required(services);
recycler.setAdapter(adapter);
}
In the add method, which I think is adding an element to the array of elements of the adapter, you should do notifyDatasetChanged() or you can do this:
...
final List services = new ArrayList();
;; CHANGED
recycler = (RecyclerView) findViewById(R.id.servicesAsked_RecyclerView);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new Adapter_services_required(services);
recycler.setAdapter(adapter);
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Method.GET, AppConfig.URL_GET_SERVICES_REQUIRED, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag_servicio = jsonObject.getString("contratista");
String servicio = jsonObject.getString("descipcion_del_problema");
String zona = jsonObject.getString("zona");
String money = jsonObject.getString("precio_min");
//Toast.makeText(Activity_Services_Worker.this, tag_servicio+servicio+zona+money, Toast.LENGTH_SHORT).show();
services.add(new Servicios_worker(tag_servicio, servicio, zona, money));
;; CHANGED
adapter.notifyDatasetChanged();
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse (VolleyError error){
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(Activity_Services_Worker.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
Related
I was working on parsing the nested JSON objects using Volley and I got the answer from the stackoverflow itself.
Parsing Nested JSON Objects using Volley
But I think the code can be optimized without the if else and also I have to display a text "No Data" if the volley request is null or no data received. I tried to check using adapter.isEmpty, adapter.getCount()
None of it worked.
This is my code
datalist=false;
progressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
schemeslist=false;
progressBar.setVisibility(View.INVISIBLE);
try {
JSONObject obj = new JSONObject(response);
JSONObject one = obj.getJSONObject("getProjectDetailsResult");
JSONObject two = one.getJSONObject("NewDataSet");
if(two.get("Rec") instanceof JSONArray) {
datalist=true;
JSONArray heroArray = two.getJSONArray("Rec");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
} else {
datalist=true;
JSONObject heroObject = two.getJSONObject("Rec");
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
// Toast.makeText(getApplicationContext(), " " + listView.getAdapter().getCount(),Toast.LENGTH_SHORT).show();
if(!datalist){
txtNoData.setVisibility(View.VISIBLE);
}
} 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();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
Can anyone tell me where should I put the if condition to work?
I checked with a toast for getting item count, but if there is no data, it is displaying blank and not 0. So I am not able to check
You can check size() of data list(heroList), size() is zero means you have no data.
try this
if(heroList.size() == 0){
txtNoData.setVisibility(View.VISIBLE);
}
I am trying to get a JSON request from an API using volley but it didn't seem to work. I did try another dummy API and it works but not for this one. The one I am currently using has headers with key and value. Also, on checking the API on postman, I saw that the JSON format begins with '[' so I am not sure what to put for the JSONObject. Also, I am not sure if I added the header right. I am very new to android and would definitely appreciate it if someone could help me out.
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://apidev.travelhouse.world/api/v1/packages";
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject hit = response.getJSONObject(i);
String creatorName = hit.getString("holiday_name");
String imageUrl = hit.getString("primary_image");
String likeCount = hit.getString("package_price");
mExampleList.add(new ExampleItem(imageUrl, creatorName, likeCount));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(MainActivity.this, "Failed to connect", Toast.LENGTH_LONG).show();
}
}) {
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX#123");
return headers;
}
};
mRequestQueue.add(request);
}
Replace your JsonObjectRequest with:
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {....}
}
}
I'm doing an app that gets the nearby locations using JSON and displays them in a recyclerview. My problem is that, I'm really not sure what am I doing wrong here cause everything looks pretty well.
This is my code for reading JSON:
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data ...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLDATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject o = jsonArray.getJSONObject(i);
List_Item item = new List_Item(o.getString("name"), o.getString("reference"));
listItems.add(item);
System.out.println("My List Item: " + listItems);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
and this is my JSON structure:
This is my stackTrace:
You should set layout manager.
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
reycyclerview.setLayoutManager(layoutManager);
I want to send the Id_student variable to MySQL but face to the following exception:
org.json.JSONException: Value 0 of type java.lang.Integer cannot be
converted to JSONArray
I have attached my code as following:
int id_student=123;
String GET_JSON_DATA_HTTP_URL ="http://pharamjo.96.lt/Select/ImageJsonData.php?";
String JSON_IMAGE_TITLE_NAME = "Id_student";
String JSON_IMAGE_URL = "Url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
//show = (TextView)findViewById(R.id.show);
/*Intent intent = getIntent();
id_student = intent.getStringExtra("student");
//show.setText(id_student);*/
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL + id_student ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Select", "onResponse");
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("********Select********",error.getMessage());
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Would you please guide me to solve my problem?
I'm trying to get url links of images from json response, save it to string[] using ArrayList and then display the images in gridview as shown in this site. My json looks like this:
I fetched the links using volley but I'm not getting the links properly. I checked the content of ArrayList using Toast and it shows the images inside [[]] like this:
That's why the images are not getting downloaded. I get 6 blank views in list.
MainActivity:
public class MainActivity extends AppCompatActivity {
String[] IMGS={};
ArrayList<String> sal = new ArrayList<String>();
ListView listView;
public static final String KEY_USERID = "user_id";
private static final String REGISTER_URL = "http://example.com/Services.php?action=fetchUserLog";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerUser();
listView = (ListView)findViewById(R.id.list);
}
///////////////////////////////////////// Volley Method Starts //////////////////////////////////////////////////////////////////
private void registerUser(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
try {
JSONObject jObj = new JSONObject(response);
String status = jObj.getString("status");
Toast.makeText(MainActivity.this, status, Toast.LENGTH_LONG).show();
// Now check status value
if (status.equals("0")) {
Toast.makeText(MainActivity.this, "There was some error! Please try again.", Toast.LENGTH_LONG).show();
}else if(status.equals("1")){
// Toast.makeText(getActivity(), "Information saved successfully", Toast.LENGTH_LONG).show();
JSONArray result = jObj.getJSONArray("results");
for(int i = 0 ; i < result.length() ; i++){
JSONObject json_data = result.getJSONObject(i);
sal.add(json_data.getString("images"));
//Toast.makeText(MainActivity.this, sal+"", Toast.LENGTH_LONG).show();
IMGS = sal.toArray(new String[sal.size()]);
listView.setAdapter(new ImageListAdapter(MainActivity.this, IMGS));
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(MainActivity.this, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERID, "21");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
///////////////////////////////////////// Volley Method Ends ////////////////////////////////////////////////////////////////////
}