I am new to android development, just started with sqlite.
Working on location app that should retrieve locations from mongo server, and populate local SQLite db.
Listview, Search queries etc.. should use local db data.
I am using volley library for my networking.
Questions:
1- After getting volley response, how do i populate sqlite?
2- How do I send updated location data from server to device?
(I dont need to update server with device info.)
3- How do i ensure sqlite only gets updated, not overwriten from server everytime?
I have seen examples using asynctask, syncadapter etc... But at this
point in project i cannot change my code from volley.
My volley code below (currently parses json to object):
private void getResource() {
RequestQueue rq = Volley.newRequestQueue(this);
JsonArrayRequest jObjR = new JsonArrayRequest(url_all_points, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseJSON(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
rq.add(jObjR);
}
private void parseJSON(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObj = response.getJSONObject(i);
JSONObject coord = jsonObj.getJSONObject("coord");
MyLocation wj = new MyLocation();
wj.setTitle(jsonObj.optString("name"));
wj.setLat(coord.optDouble("latitude"));
wj.setLng(coord.optDouble("longitude"));
mLocations.add(wj);
LatLng location = new LatLng(wj.getmLat(), wj.getmLng());
mMap.addMarker(new MarkerOptions().position(location)
.title(wj.getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
}
}
Related
So i am a beginner in android programming. I have run into a problem . I am trying to get JSON data from a fake API . But due to some problem in my request i cant get the data in my response . I tried debugging with breakpoints but the loop (which adds the received data to the arraylist) is not getting executed . Can anyone pls tell me what the error in my code is ?
the API link is :- https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json
public class Repository {
RequestQueue queue;
ArrayList<Question> questionArrayList = new ArrayList<>();
String url = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public ArrayList<Question> getQuestions(final SyncInterface callback){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Question question = new Question(response.getJSONArray(i).get(0).toString(),
response.getJSONArray(i).getBoolean(1));
//Add questions to arraylist/list
questionArrayList.add(question);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (callback != null)
callback.isFinished(questionArrayList);
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Tag","error");
}
});
queue = AppController.getInstance().getRequestQueue();
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
}
The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive
I have to create an android application which shows some reports and images in Recycler view using json volley request it works when internet is available i also need to show the once loaded data in recycler view when internet is not available here is the code i used to select data when internet is available
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, Config.DATA_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String str = response.toString();
loading.hide();
JSONArray arr = response.getJSONArray("Stock_Report");
parseData(arr);
} catch (JSONException e) {
e.printStackTrace();
}
// now you have the array. in this array you have the jsonObjects
// iterate on this array using a for loop and parse like you did before
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
//Adding request to the queue
requestQueue.add(jsObjRequest);
}
please help me to find better solution to show this data when internet is not available also thanks in advance
I am currently using Volley to extract JSON contents using the following code.
JsonArrayRequest servicesStatus = new JsonArrayRequest(url1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
// Having obj to process further
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Now, I want one more JSON handler for the new URL and the dialog to be closed once it has successfully downloaded from both the URLs.
I tried to copy paste the above thing with url1 replaced by url2 and different jsonarrayrequest name. And added the hideDialog() in the second one. But the second one is not being called at all.
If you want make multiple request then you will have to add your Request to Queue. You can do it like this:
RequestQueue request = Volley.newRequestQueue(Context);
request.add(FirstRequest);
request.add(SecondRequest);
This should help you to add multiple request in Volley.
This is my JSON code. I want to cache JSON data from URL for the first time and second time it will be work without internet.How and where have to use the volley cache tool, and how to access the saved file??
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.URL_CONTACTS, new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
new Thread(new Runnable() {
#Override
public void run() {
try{
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has(Constants.TAG_EXAM)) {
JSONArray examArray = jsonObject.getJSONArray(Constants.TAG_EXAM);
for(int i = 0; i < examArray.length(); i++) {
// get all array from JSON object
JSONObject seat = examArray.getJSONObject(i);
}
}
handler.sendEmptyMessage(1);
} catch (JSONException e) {
handler.sendEmptyMessage(2);
e.printStackTrace();
} catch (NullPointerException e) {
handler.sendEmptyMessage(3);
e.printStackTrace();
}
}
}).start();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}``
})`
Volley doesn't provide such cache tools to cache json,you can create your own cache tool using map or LruCache to make it.because your json will be little and use little memory,you can use map to save it,it will be the easiest way to make it in my opinion.
You can cache the response of volley since it's a string using SharedPreferences.