Android - Wait for Volley response to complete and continue executing - android

I need execute a Volley request and wait for the response to parse it and return it, but have no idea on how to achieve this.
Can someone help?
here is my code :
public void getWord(){
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject lesMots = response.getJSONObject("lesMots");
Iterator<?> keys = lesMots.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (lesMots.get(key) instanceof JSONObject) {
JSONObject obj = (JSONObject) lesMots.get(key);
//Récupération des deux mots, anglais et français
String wordToFind = obj.getString("wordFrench").toUpperCase();
String wordEnglish = obj.getString("wordEnglish").toUpperCase();
//Mots mis dans un array respectif
listOfWordEnglish.add(wordEnglish);
listOfWordFrench.add(wordToFind);
container.removeAllViews();
}
numberOfWord++;
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error + "", Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
There is 7 word in each array but when i'm trying to get acess into my initGame function, it said they are empty, i guess it's because volley request is not this fast !
if someone can explain me how to do that
here is my initGame function
`public void initGame() {
win = false;
found = 0;
typed_word.setText("");
image.setBackgroundResource(R.drawable.first);
listOfLetters = new ArrayList<>();
listOfWordFrench = new ArrayList<>();
listOfWordEnglish = new ArrayList<>();
getWord();
for (int i = 0; i < listOfWordEnglish.size(); i++){
System.out.println(i);
String wordEnglish = listOfWordEnglish.get(i);
wordEnglishPendu.setText(wordEnglish);
word = listOfWordFrench.get(i);
for (int x = 0; x < word.length(); x++) {
TextView oneLetter = (TextView) getLayoutInflater().inflate(R.layout.textview, null);
container.addView(oneLetter);
}
}
}`

Since Volley is asynchronous, so the for loop below getWord() will be called before onResponse of your Volley request.
The solution for your issue is to move that for loop into onResponse, there you can place it after the while loop.
Hope it helps!

Related

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

How to externalise volley json parsing to a separate class file so the code will be loosely coupled?

I have got a class called Client.class. Within this, I have got a method as follows where Im invoking a volley to fire api requests.
public void dispatchLoginRequest() {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// Log.d(TAG, "ADS " + frameLoginJson().toString());
pDialog.setMessage("Logging in ...");
showDialog();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, "http://52.11.242.90:8082/api/login", frameLoginJson(), new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseLoginResponse(response);
// aparjithaDb.parseLoginResponse(response, this);
Parser.getInstance().parseLoginResponse(response,this,getApplicationContext());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "log" + frameLoginJson().toString());
error.printStackTrace();
pDialog.hide();
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().getRequestQueue().add(jsonArrayRequest);
}
I have the following method in other class called as Parse.class where im parsing the response and adding it to db.
public void parseLoginResponse(JSONArray response, ClientLogin clientLogin, ContextWrapper contextWrapper) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject value = response.getJSONObject(i);
JSONArray configuration = value.getJSONArray("configuration");
int group_id = value.getInt("group_id");
String group_name = value.getString("group_name");
JSONObject menu = value.getJSONObject("menu");
JSONObject menus = menu.getJSONObject("menus");
JSONArray master = menus.getJSONArray("Master");
JSONArray transaction = menus.getJSONArray("Transaction");
JSONArray report = menus.getJSONArray("Report");
boolean approvalExists = isApprovalExists(transaction, "Compliance Approval");
boolean taskExists = isTaskExists(transaction, "Compliance Task Details");
Toast.makeText(contextWrapper.getApplicationContext(), "COOL" + approvalExists, Toast.LENGTH_SHORT).show();
for (int j = 0; j < configuration.length(); j++) {
JSONObject jsonobject = configuration.getJSONObject(i);
int period_from = jsonobject.getInt("period_from");
int period_to = jsonobject.getInt("period_to");
int country_id = jsonobject.getInt("country_id");
int domain_id = jsonobject.getInt("domain_id");
Db.getInstance(contextWrapper).addClientConfig(new ClientConfig(j, String.valueOf(period_from), String.valueOf(country_id), String.valueOf(period_to), String.valueOf(domain_id), group_name, String.valueOf(group_id)));
}
Intent intent = new Intent(clientLogin, Client.class);
intent.putExtra("approvalExists", "" + approvalExists);
intent.putExtra("taskExists", "" + taskExists);
clientLogin.startActivity(intent);
// logClientDb();
} catch (Exception e) {
Toast.makeText(contextWrapper.getApplicationContext(), "Please Check your user credentials..." + e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
The problem is that im getting the following error
Error:(91, 37) error: method parseLoginResponse in class Parser cannot be applied to given types;
required: JSONArray,ClientLogin,ContextWrapper
found: JSONArray,<anonymous Listener<JSONArray>>,Context
reason: actual argument <anonymous Listener<JSONArray>> cannot be converted to ClientLogin by method invocation conversion
Im just trying to externalise the way that Im parsing the json and adding it to db while using volley. How can I do so?
For request modify it as follow-
JsonArrayRequest request=new JsonArrayRequest(url,requestSuccessListener(),requestErrorListener());
now write u r public void external function requestSuccessListener and requestErrorListener. it will work.

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

Android value of arraylist out of method

I have this code created with Volley and JSON:
public List<String> result = new ArrayList<String>();
public List<String> mostraDati(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, DatiNet.MostraDati, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
System.out.println("fin qui ci siamo");
JSONArray utenti = response.getJSONArray("utenti");
List<String> resTemp = new ArrayList<String>();
for (int i = 0; i < utenti.length(); i++) {
JSONObject student = utenti.getJSONObject(i);
String nome = student.getString("nome");
String cognome = student.getString("cognome");
String numero = student.getString("numero");
String email = student.getString("email");
resTemp.add(nome + " " + cognome + " " + email);
}
result = resTemp;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
System.out.println(result.toString());
return result;
}
It works well but the return is always null "[]". How to solve the problem?
I think the problem is to port the value out of the method of jsonObjectRequest.
You have to change your code to add one arrayList value to another arrayList.
Change
result = resTemp;
to
result.addAll(resTemp);

Categories

Resources