Retreiving data from MySQL database using Android Volley library is too slow - android

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.

Related

how to stay connected to the server

I'm trying to stay connected with a url but I don't know how.
I'm working on a quiz app so I need to refresh the question every time that user lose or win.
but it takes long time to connect to the url every time.
so I just want to connected once and then just get new questions from that url.
I'm using volley library to connect to a url.
And This is my code.
public static void getQuestionsData(Activity activity,
OnDoneLintenter onDoneListener) {
String url = "https://opentdb.com/api.php?amount=15&type=multiple";
RequestQueue queue = VolleySingleton.getInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(ColumnStructure.GET, url, null,
jsonObject -> {
try {
JSONArray array
= jsonObject.getJSONArray(ColumnStructure.COL_RESULTS);
for (int i = 0; i < array.length(); i++) {
setColumnStructureFields(array, i);
}
onDoneListener.onDone();
} catch (JSONException e) {
Log.e("Log", "there is not result : " + e.getMessage());
}
},
volleyError -> {
Log.e("Log", "volley error : " + volleyError.getMessage());
});
queue.add(jsonObjectRequest);
}
I use this code at the beginning and every time user lose or win.So is there any way to stay connected with the url or at least get the json faster.

I cannot identify what is causing this unexpected upload error on my app

I am relatively new to android development and I have been squeezing my brain juice for hours on probably a very simple error. Look, the app's been working fine yesterday and after I made some changes on some XML files and ran the app on my emulator, I experience this error:
2019-09-10 14:13:19.533 6388-
6516/ E/Volley: [301]
BasicNetwork.performRequest: Unexpected response code 406 for
http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
2019-09-10 14:13:21.573 1633-1656/system_process E/memtrack: Couldn't load
memtrack module
I have already tried numerous solutions on the web and it seems not to fix my problem. This is my code:
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_ADD_VEHICLE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String Success = jsonObject.getString("success");
if (Success.equals("1")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added
Successfully",Toast.LENGTH_SHORT).show();
}else if (Success.equals("0")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle
Already Exist",Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
e.printStackTrace();
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added
Error"+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(Addvehicle.this,"Vehicle Added
Error"+error.toString(),Toast.LENGTH_SHORT).show();
hideLoader();
}
})
I am receiving a blank response from this URL and I need guidance on how to fix this:
http://*********.php
For whatever reasons, this page on my app stopped working because of this error. Any help would be appreciated. Again, I'm basically new in android development so please understand that a simple error like this bleeds my nose.
Here are my server php codes:
<?php
require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$plate_number=$_POST['plate_number'];
$vin=$_POST['vin'];
$car_make=$_POST['car_make'];
$car_model=$_POST['car_model'];
$car_year=$_POST['car_year'];
$displacement=$_POST['displacement'];
$fuel_type=$_POST['fuel_type'];
$transmission=$_POST['transmission'];
$mileage=$_POST['mileage'];
$owner_name=$_POST['owner_name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email_adress=$_POST['email_adress'];
$facebook=$_POST['facebook'];
$adddate = date("d/m/Y");
$photo = $_POST['photo'];
$id=uniqid();
$path = "vehicle_upload/$id.jpeg";
$finalpath = "*********.$path;
$sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
PlateNumber='$plate_number'");
if (mysqli_num_rows($sql1) > 0) {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
}else{
$sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");
if ($sql) {
if (file_put_contents($path, base64_decode($photo))) {
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
//mysqli_close($connect);
}
}
}
}
?>
In POST request you need to send parameters like an empty Hashmap i.e
{"":""} or you need to try https instead of http.

Display large amount of data(mostly text) in android app

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!

Android volley - Unexpected response code 500

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.

Android Volley request weird "1 second" delay between multiple fast clicks

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.

Categories

Resources