Data retrive from server too slow - android

I am getting data on splash. I have almost 7k data that I am getting from the server. While getting data from the server I am saving it in the local database but the problem is the process is too slow. It almost takes 5 minutes. I want to resolve the problem. Please help.
Code to get data from server and save it into database:
private void productsDetailsApi() {
String tag_json_obj = "json_obj_req";
String url = Constants.PRODUCTS_DETAILS_URL;
pBar.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("product_response", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.close();
ArrayList<ModelProductDetail> modelProductCodeList = dbHelper.getProductsArticleCode();
Log.e("TAG", "ModelProductDetail:art " + modelProductCodeList.size());
shopDetailsApi();
} catch (Exception e) {
e.printStackTrace();
}
//pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
// pBar.setVisibility(View.GONE);
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Databse Insert Query
//add products data
public void addProductsDetails(ModelProductDetail modelProductDetail) {
SQLiteDatabase productsDb = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PRODUCT_ID, modelProductDetail.getProduct_id());
values.put(KEY_PRODUCT_NAME_FR, modelProductDetail.getProduct_name_fr());
values.put(KEY_PRODUCT_NAME_NL, modelProductDetail.getProduct_name_nl());
values.put(KEY_PRODUCT_DESC, modelProductDetail.getProduct_desc());
values.put(KEY_PRODUCT_ART, modelProductDetail.getArticle_code());
values.put(KEY_PRODUCT_EAN, modelProductDetail.getEan_code());
values.put(KEY_PRODUCT_MBH, modelProductDetail.getProduct_mbh());
values.put(KEY_PRODUCT_MSRP, modelProductDetail.getProduct_msrp());
values.put(KEY_PRODUCT_SOURCE, modelProductDetail.getProduct_source());
values.put(KEY_COMPANY_ID, modelProductDetail.getCompany_id());
values.put(KEY_COMPANY_NAME, modelProductDetail.getCompany_name());
values.put(KEY_FRANCO_TRADING, modelProductDetail.getFranco_trading_value());
values.put(KEY_FRANCO_PRODUCT, modelProductDetail.getFranco_product_value());
productsDb.insert(TABLE_PRODUCT_DETAILS, null, values);
productsDb.close();
}

You could try wrapping all the inserts inside a transaction e.g. :-
JSONArray jsonArray = response.getJSONArray("data");
dbHelper.getWritableDatabase.beginTransaction(); //<<<<<<<<<< ADDED
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.getWritableDatabase.setTransactionSuccessful(); //<<<<<<<<<< ADDED
dbHelper.getWritableDatabase.endTransaction(); //<<<<<<<<<< ADDED
dbHelper.close();
To use the above you would also have to remove the line
productsDb.close();
From the Insert Query

Related

Volley Multiple Request :How to call more than 1 request in one Activity

Questions Description:
I Have four methode to get all the data of related things from server:
BankList();
BranchList();
StateDetails();
DistrictDetails();
In that I am fetching data From Server related with Bank Details one by one using Volley .and Storing into SQLite.
Quetions:
Please Check below Code
What is Correct way to call volley String Request one by one.
How to call volley String request one by One on Priority or automatically.
Code is Working Fine and its storing value into SQLite Also.
But Loader Progress Dialog not working Properly . its freezing the app its not working properly .it gives me output but application freeze for few second if network speed is slow like 3G then it took more time and then my application will freeze for more time . so please help me how to avoid that
My Question is My way is correct or wrong. how to call methods one after another . on priority basis or automatically one by one
Please Check below Code
public class LoginPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
BankList();
BranchList();
StateDetails();
DistrictDetails();
}
public void BankList() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("BankList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BankID = jsonObject.getInt("BankID");
String BankName = jsonObject.getString("BankName");
Log.e("Bank ID", String.valueOf(BankID));
Log.e("Bank Name", BankName);
ContentValues cv = new ContentValues();
cv.put("BankID", BankID);
cv.put("BankName", BankName);
db.insert("BankList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BankID = jsonObject.getInt("BankID");
String BankName = jsonObject.getString("BankName");
Log.e("Bank ID", String.valueOf(BankID));
Log.e("Bank Name", BankName);
so.BankList(BankID, BankName);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "BankList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().
addToRequestQueue(stringRequest);
}
public void StateDetails() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("StateList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int StateID = jsonObject.getInt("StateID");
String StateName = jsonObject.getString("StateName");
int Bank_id = jsonObject.getInt("Bank_id");
ContentValues cv = new ContentValues();
cv.put("StateID", StateID);
cv.put("StateName", StateName);
cv.put("Bank_id", Bank_id);
db.insert("StateList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int stateId = jsonObject.getInt("StateID");
String stateName = jsonObject.getString("StateName");
int bankID = jsonObject.getInt("Bank_id");
so.StateList(stateId, stateName, bankID);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "StateList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().
addToRequestQueue(stringRequest);
}
public void DistrictDetails() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("DistrictList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int DistrictId = jsonObject.getInt("DistrictId");
String DistrictName = jsonObject.getString("DistrictName");
int StateID = jsonObject.getInt("StateID");
ContentValues cv = new ContentValues();
cv.put("DistrictId", DistrictId);
cv.put("DistrictName", DistrictName);
cv.put("StateID", StateID);
db.insert("DistrictList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int DistrictId = jsonObject.getInt("DistrictId");
String DistrictName = jsonObject.getString("DistrictName");
int StateID = jsonObject.getInt("StateID");
so.DistrictList(DistrictId, DistrictName, StateID);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "DistrictList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().
addToRequestQueue(stringRequest);
}
public void BranchList() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("BranchList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BranchID = jsonObject.getInt("BranchID");
String BranchName = jsonObject.getString("BranchName");
String IFSC_code = jsonObject.getString("IFSC_code");
int District_id = jsonObject.getInt("District_id");
ContentValues cv = new ContentValues();
cv.put("BranchID", BranchID);
cv.put("BranchName", BranchName);
cv.put("IFSC_code", IFSC_code);
cv.put("District_id", District_id);
db.insert("BranchList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BranchID = jsonObject.getInt("BranchID");
String BranchName = jsonObject.getString("BranchName");
String IFSC_code = jsonObject.getString("IFSC_code");
int District_id = jsonObject.getInt("District_id");
so.BranchList(BranchID, BranchName, IFSC_code, District_id);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "BranchList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().addToRequestQueue(stringRequest);
}
}
There is problem with your code. The volley onResponse() and onErrorResponse() methods are always invoked in the main UI thread. In your code you place the SQLite database write operation inside the volley onResponse() method. The database write operation may be a long running process depending on the size of the data.
In your code the main UI thread sleep and wait for the database write operation to finish, and this is why your application user interface freeze. Place the database write operation on a separate background thread will solve your problem.
Use AsyncTask for the write operation.

Error 404 while senting data to server

This code is supposed to be sending my JSON value to the server. When I click the button, I get an error - Unexpected reponse code 404.
Could someone explain what the problem is and how I can solve it?
Is this a server side error?
This is my code...
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
getResults();
StringRequest request=new StringRequest(Request.Method.POST,server_url,new Response.Listener<String>() {
#Override
public void onResponse(String response){
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
protected Map<String,String>getParams() throws AuthFailureError{
Map<String,String> parameters = new HashMap<String, String>();
getResults().put(parameters);
return parameters;
}
};
requestQueue.add(request);
}
});
}
private JSONArray getResults() {
String myPath = "/data/data/com.example.sebastian.patientdetails/databases/" + "MyDBName.db";
String myTable = "patients";
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
JSONArray jsonArray = null;
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
jsonArray = new JSONArray();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
JSONObject object = new JSONObject();
try {
if (cursor.getString(i) != null) {
Log.d("TAG_NAME", cursor.getString(i));
object.put(cursor.getColumnName(i), cursor.getString(i));
} else {
object.put(cursor.getColumnName(i), "");
}
jsonArray.put(object);
}
catch (Exception e) {
Log.d("TAG_NAME", e.getMessage());
}
}
}
jsonArray.put(rowObject);
resultSet.put(rowObject);
cursor.moveToNext();
}
return resultSet;
}
}
404 means not found, server_url points to a not existent URL or the page you are requesting is redirecting you to 404.
If you open a browser and send a POST request in AJAX to the same URL and the same parameters, then you should experience the same behavior.

Unexpected response code 500 Android

This is my code...
b2 = (Button) findViewById(R.id.button3);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getResults();
StringRequest request= new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
protected Map<String,String>getParams() throws AuthFailureError{
Map<String,String> parameters = new HashMap<String, String>();
getResults().put(parameters);
return parameters;
}
};
requestQueue.add(request);
}
});
}
private JSONArray getResults() {
String myPath = "/data/data/com.example.sebastian.patientdetails/databases/" + "MyDBName.db";
String myTable = "patients";
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
JSONArray jsonArray = null;
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
//new jsonarray
jsonArray = new JSONArray();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
//new jsonarray of items jsonObject
JSONObject object = new JSONObject();
try {
if (cursor.getString(i) != null) {
Log.d("TAG_NAME", cursor.getString(i));
object.put(cursor.getColumnName(i), cursor.getString(i));
} else {
object.put(cursor.getColumnName(i), "");
}
//put jsonarray
jsonArray.put(object);
} catch (Exception e) {
Log.d("TAG_NAME", e.getMessage());
}
}
}
//put request jsonobject
jsonArray.put(rowObject);
resultSet.put(rowObject);
cursor.moveToNext();
}
return jsonArray;
}
}
When i click the button to sent my json object to server i got this error ' Unexpected response code 500 ' . Whats the reason. How can i fix this issue. Is there any issue in converting my sqlite to json object.?
The Web server (running the Web Site) encountered an unexpected condition that prevented it from fulfilling the request by the client (e.g. your Web browser or our CheckUpDown robot) for access to the requested URL.
This is a 'catch-all' error generated by the Web server. Basically something has gone wrong, but the server can not be more specific about the error condition in its response to the client. In addition to the 500 error notified back to the client, the Web server should generate some kind of internal error log which gives more details of what went wrong. It is up to the operators of the Web server site to locate and analyse these logs.
reference: http://www.checkupdown.com/status/E500.html

I/Choreographer: Skipped 33 frames! The application may be doing too much work on its main thread?

I believe that this error has something to do with the fact that I am not running my JSON in a thread. Here is my code below how can I fix this? Do I need to put this into a runnable, if so how do I do that? I am relativitly new to the idea of threads so please help me out?
private void JsonRequestMethod() {
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs.clear(); // here you clear the old data
listblogs=parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String studentId = currentQuestions.getString("studentId");
String DateCreated=currentQuestions.getString("created");
long time=Long.parseLong(DateCreated.trim());
data.append(text + "\n" + points + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
//The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
blogs.setDateCreated(getTimeAgo(time));
System.out.println(time+"time");
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
You are doing JSON parsing in the UI thread. Use Gson to convert it to ArrayListnew Gson.fromJson(yourObject, class); convert your response to POJO www.jsonschema2pojo.org/

Volley Object request Returning 0

I Have a Remote Database that contains 6 rows.
Here's my code, I put it in List so that i can get the size,
But it's always returning 0.
public List<Comments> getComments() {
final List<Comments> commentsData = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
return commentsData;
}
I need the size for some use.
Why is it always returning zero?
I even tried adding a counter++ inside for loop.
But when i get the value of the counter its still zero.
JsonObjectRequest run on a background thread. That's why you getting the list size 0. you must work into the public void onResponse(JSONObject response) {} function .
Exmp.
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
// **you may call function and pass the list value to update your ui component. you will get the real size of list here.**
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories

Resources