I'm creating an android app and i have a relatively large amount of data (mostly in text form and as key->string pairs) that i want to display in my app.
The problem is i don't want to enter the data in my app's code,meaning feel each TextView manually with the associated data.i don't feel that to be right!
I want my app to read this data from a file(maybe a JSON?) and then associate each key-> string pair with the related TexView.
To be more clear, i need to read from a prepared text file and use that text inside my app, AND i want to do this offline,i dont want to use any webservic
How should i accomplish this? should i use a database or room?Then how should i feel the database manually without using insert codes inside the app?
Use Volley for JSON Parsing
private static final String url ="your url";
Create a method
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait, while we load the data");
progressDialog.show();
*make a String or JSON request*
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
newurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("response", response.toString());
Log.i("updated Url",newurl);
progressDialog.dismiss();
*then move into the json and create JSON object or JSON Array to get their String values*
try {
JSONObject data = response.getJSONObject("data");
JSONArray onwardflights = data.getJSONArray("data_key");
for (int i = 0; i < onwardflights.length(); i++) {
JSONObject onwardFlightsChild = onwardflights.getJSONObject(i);
String arrival,deparutre,duration,flightno,grossamount,image,direct;
JSONObject object = onwardFlightsChild.getJSONObject("data_key");
Onwardflights onwardflights1 = new Onwardflights(
arrival = onwardFlightsChild.getString("data_key"),
deparutre = onwardFlightsChild.getString("data_key"),
duration = onwardFlightsChild.getString("data_key"),
flightno = onwardFlightsChild.getString("data_key"),
direct = onwardFlightsChild.getString("data_key"),
origin = onwardFlightsChild.getString("data_key"));
Log.i("Origin",origin);
Fare fare = new Fare(
grossamount = object.getString("data_key")
);
onwardflights1.setFare(fare);
suggestionmodel.add(onwardflights1);
}
*Create an instance of adapter and pass the parameters*
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(suggestionmodel,getApplicationContext());
recyclerView.setAdapter(recyclerAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("THIS", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(jsonObjReq);
}
You could simply use a JSON file. Now, the question is: How do you ship a JSON file with your app so that it's available at Runtime? You can use any of these methods:
Put it in the directory res/raw/ and read it using the Resources class (it has a openRawResource() method)
Put it in the assets/ directory and read it in using the AssetManager class (it has a open() method that returns an InputStream)
I hope this helps... Merry coding!
Related
I have two global variables currentTemp and currentHum that are set when Volley's onResponse method is called. My code looks like this:
// Request a string response from the provided URL.
private JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, WEATHER_URL, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONObject main = new JSONObject(response.getString("main"));
currentTemp = main.getString("temp");
currentHum = main.getString("humidity");
Log.i("RES", "Temp: " + main.getString("temp") + " Hum: " + main.getString("humidity"));
} catch (JSONException e) {
e.printStackTrace();
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(appContext, "An error occurred while retrieving weather info", Toast.LENGTH_LONG).show();
Log.e("ERR", "ERROR RET WEATHER DATA");
}
});
// Call the OpenWeatherMap API and get data such as temperature and humidity
private String getWeatherInfo(String key) {
// Add the request to the RequestQueue to invoke the API
queue.add(jsonObjectRequest);
// Access variables set by Volley's onResponse here.
switch (key) {
case "temp":
return String.valueOf(Float.parseFloat(currentTemp) - 273.15);
case "hum":
return currentHum;
default:
return " ";
}
}
I want to be able to access the values of the global variables set by the onResponse method in the getWeatherInfo method that invoked it. Then pass the values to a switch statement for processing. How do I do it without getting empty values for currentTemp and currentHum?
This work is meant to be done with use of an interface. If you don't know about an interface callbacks then please go through this answer. Which will help you understand interface, and plus point that this will guide you for handling volley response.
Also this is not recommended to take global variables to set any response, rather you can pass your whole JsonObject from volley class. and parse it where you make a call. You can use Gson for parsing the response to your Model or ArrayList.
i have generated an app over e-commerce site (magento 2) while i am trying to startup my app it processing very slowly because of many products in my server is there any possible way to speed up my usage of Async task while using JSON feeds.. Please let me for any possible ways
My one of the AsyncTask coding:
private class GetProduct extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
dialog_pro = new ProgressDialog(Healthy_Cat.this);
dialog_pro.setMessage("Please wait...");
dialog_pro.setCancelable(false);
dialog_pro.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONArray items = new JSONArray(jsonStr);
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
pro_name = c.getString("name");
String price = c.getString("price");
JSONArray array = c.getJSONArray("custom_attributes");
for (int k = 0; k < array.length(); k++) {
JSONObject jb = array.getJSONObject(k);
String attr = jb.getString("attribute_code");
if (attr.equalsIgnoreCase("special_price")) {
splprice = jb.getString("value");
}
}
String sku = c.getString("sku");
JSONArray media = c.getJSONArray("media_gallery_entries");
for(int k = 0; k < media.length(); k++) {
JSONObject jb = media.getJSONObject(k);
String imageURL = BaseURL_Helper.MediaBase +jb.getString("file");
media_image = imageURL;
// tmp hash map for single contact
Beanclass dataSet = new Beanclass();
dataSet.setTitle(pro_name);
dataSet.setImage(imageURL);
dataSet.setPrice(price);
dataSet.setSPLPrice(splprice);
dataSet.setSku(sku);
list.add(dataSet);
BeanclassList data = new BeanclassList();
data.setTitle(pro_name);
data.setImage(imageURL);
data.setSku(sku);
data.setSPLPrice(splprice);
data.setPrice(price);
listbean.add(data);
}
}
}catch (final JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
no_list.setVisibility(View.VISIBLE);
}
});
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"May be Network error!!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
if (dialog_pro.isShowing())
dialog_pro.dismiss();
mAdapter = new GridviewAdapter(Healthy_Cat.this,list);
gridlist.setAdapter(mAdapter);
Listadapter = new ListviewAdapter(Healthy_Cat.this,listbean);
listview_pro.setAdapter(Listadapter);
}
}
Thank u in advance..
There are few things you need to update in your code
API Calling lib: I'm using Retrofit for api calling very fast & simple to use. Support Header & Response caching too.
JSON Parsing: You are parsing JSON manually which is a time-consuming process. I'm using Google's JSON parsing Lib Gson. really very fast.
Pagination: If you having lots of data on the server then try to fetch data in small no of pieces. For example in case of "Item Listing API" try to fetch data from the server for 10-15 item at a time rather all the item at a once.
Asyntask performance speed is too low compare to Retrofit.
So For e-commerce app, You must use Retrofit.
There are a few things you can do. For starters, you don't have to parse the whole json, before updating view.
But really you yourself state the issue, which is you have too much data. This is not only a programming issue, it is also a user experience issue, too much data is confusing, especially on a mobile device.
What I suggest is breaking down your data into categories or the like. When app starts, download just a list of categories to display. Upon user choosing a category, then you download the data for that category.
When you download data, do it in chunks, so that you can start displaying right away.
There are many similar ideas that you can implement, for a better user experience.
I tried to retrieve a list of form data stored in database in my Android application. Each row of database contains some personal information of a person in string format and also an image of that person. I have stored the images in database in MEDIUMBLOB format.
Whenever I try to retrieve data from my server using JSONObjectrequest of Volley Library in my Android app, the response is usually very slow. Sometimes it takes more than 1 minute to view only 10 to 12 rows retrieved from the database.
This is my logcat:
D/Volley: [337] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://helpclick.ahsanaasim.me/v1/tasksall/johny 0xa3e020c1 NORMAL 1> [lifetime=14740],
I tried to search for a perfect solution but I couldn't find anything satisfactory. Here is my Java code:
mRequestStartTime = System.currentTimeMillis();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
showUrl2, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
System.out.println(totalRequestTime);
System.out.println(response.toString());
try { c1++;
System.out.println(c1);
JSONArray incidents = response.getJSONArray("incidents");
for (int i = 0; i < incidents.length(); i++) {
e=0;
JSONObject incident = incidents.getJSONObject(i);
c1++;
id= incident.getString("id");
age = incident.getString("age");
gender = incident.getString("gender");
location = incident.getString("location");
//det= incident.getString("det");
String image=new String();
image = incident.getString("bigimage");
if(image.length()!=0) {
myBitmap = ConvertToImage(image);
Bitmap bitmap= Bitmap.createScaledBitmap(myBitmap,500,500,true);
imgs.add(bitmap);
ages.add(age);
genders.add(gender);
locations.add(location);
ids.add(id);
}
}
if(c1>0) {
System.out.println(ages.size());
Intent intent1 = new Intent(search_buttons_page.this, All_Incidents.class);
startActivity(intent1);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
20000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
It would be really helpful if someone can tell me the reason of this slow performance and how to solve it by making minimum modifications in my source code.
Don't keep the images in the db. Keep them in files, and keep the URL of the files in the db. Download the images separately as needed via URL. Then you aren't killing your database access times with what should be file IO.
I am trying to edit an already registered addresses on my application, but I'm getting this error when I try to do that.
private void callServiceToEditAddress(String flatNo, String apartmentName, String landmark, String pincode) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", addressID);
hashMap.put("flat_no", flatNo);
hashMap.put("apartment_name", apartmentName);
hashMap.put("lanmark", landmark);
hashMap.put("pincode", pincode);
hashMap.put("state", selectedState);
hashMap.put("city", ID_city);
hashMap.put("location", ID_locality);
hashMap.put("country", "2");
new VolleyHelper(getActivity()).post("editAddress/", hashMap, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
mAddresshasbeenAdded.newAddressHasbeenAdded();
CroutonUtil.showCroutonMessage(getActivity(), success, CroutonUtil.CROUTON_STYLE_CONFIRM);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
}
My Log cat:
E/Volley: [365] BasicNetwork.performRequest: Unexpected response code 500 for link I'm using
i solved this by changing the permission for included files in my server side
I was actually able to solve my problem eventually. What happened is that this web service that I am using "editAddress" also needed another field that I was not providing inside hashMap. I made the changes and it worked fine.
I just change my url from
http
to
https
Then it works fine for me.
The parameters put into Hashmap and get in server side was misspelled, When I have corrected the words of both side with same spelling , The problem was gone, Alhamdulillah.
Sorry for my bad english, but i have problem and can't figure it out..
I have custom listview in my fragment for getting products from JSON array. And I have 3 ImageButtons in every listview row;
Plus Button(+), Minus Button(-) and Remove Button(X)..
So when i click each button, its calling JSON request for update product's piece number, getting new datas from response and repopulate array list.
Everything ok but, when I click that buttons faster, it seems there is 1 sec delay between multiple requests even first volley request has already done before.
Here is my JSON method in TableAdapter.java
public void JSON(final int position, final int process) {
if (inProgress==false) {
dialog = new ProgressDialog(myContext);
dialog.setMessage("Updating.....");
dialog.show();
inProgress = true;
System.out.println("**** Now request is beginning............");
final int rowID = tableModelList.get(position).getID();
final int treeID = tableModelList.get(position).getAna_dal();
final float price = tableModelList.get(position).getBFiyat();
final int quantity = tableModelList.get(position).getAdet();
final int print = tableModelList.get(position).getYazdimi();
final String insertUrl = "http://"+getServer+"/t6mobilservice/order-piece.php";
Map<String, String> parameters = new HashMap<>();
parameters.put("tableID", "" + getTableId);
parameters.put("rowID", "" + rowID);
parameters.put("treeID", ""+treeID);
parameters.put("process",""+process);
parameters.put("quantity",""+quantity);
parameters.put("price",""+price);
parameters.put("print",""+print);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, insertUrl, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray getOrders = response.getJSONArray("order");
Gson gson = new Gson();
tableModelList.clear();
for (int i = 0; i < getOrders.length(); i++) {
JSONObject order = getOrders.getJSONObject(i);
TableModel tableModel = gson.fromJson(order.toString(), TableModel.class);
tableModelList.add(tableModel);
}
mAdapter.notifyDataSetChanged();
System.out.println("**** onResponse: Request is done............");
System.out.println("**** JSON: "+response.toString());
dialog.cancel();
inProgress = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError response) {
Log.d("Response: ", response.toString());
inProgress = false;
}
});
requestQueue.add(jsObjRequest);
}
}
Dialog is showing when request beginning and canceling when request is done. But as I said, when I click faster, there is a delay between multiple requests even first request has already done. I'm saying 1 sec, because 2nd request is beginning after 1 sec exactly, no matter how I clicking fast. I can't figure it out..
I tested fast clicks to showing toasts with random numbers and it's working fine. But when I testing with JSON method, there is a weird delay.
I have SwipeRefreshLayout and ScrollView in my fragment.
I'm using Volley with singleton.
EDIT 1. : Here's a video link to showing what my problem is..
EDIT 2. : Here's a LogCat output video for every click
Every fast click has returning success json output, but nothing change instantly..
Thanks for your help.