i am fetching 104 variables from MySQL through php in android and trying to show in list view but its taking almost 1 - 2 minutes to load values how to speed up the data fetching.
i am using json for fetching data, any other library's for fast fetching.
please explain with complete example.
Try the Android Asynchronous Http Client library
Features
Using upstream HttpClient of version 4.3.6 instead of Android provided DefaultHttpClient
Compatible with Android API 23 and higher
Make asynchronous HTTP requests, handle responses in anonymous callbacks
HTTP requests happen outside the UI thread
Requests use a threadpool to cap concurrent resource usage
GET/POST params builder (RequestParams)
Multipart file uploads with no additional third party libraries
Streamed JSON uploads with no additional libraries
Handling circular and relative redirects
Tiny size overhead to your application, only 90kb for everything
Automatic smart request retries optimized for spotty mobile connections
Automatic gzip response decoding support for super-fast requests
Binary protocol communication with BinaryHttpResponseHandler
Built-in response parsing into JSON with JsonHttpResponseHandler
Saving response directly into file with FileAsyncHttpResponseHandler
Persistent cookie store, saves cookies into your app’s SharedPreferences
Integration with Jackson JSON, Gson or other JSON (de)serializing libraries with BaseJsonHttpResponseHandler
Support for SAX parser with SaxAsyncHttpResponseHandler
Support for languages and content encodings, not just UTF-8
For more details please visit these link :
http://loopj.com/android-async-http/
Here's an example of using it :
pdialog.setMessage("Veuillez patienter!");
pdialog.show();
RequestParams params = new RequestParams();
params.put("user_login", username);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://yourUrl.com", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
loading = true;
AdapterPrincipal adapterPrincipal;
String s = "";
try {
s = new String(responseBody, "UTF-8");
Log.d("Error", s.toString());
JSONObject arrg = new JSONObject(s);
JSONArray query = arrg.getJSONArray("query");
Log.i("result from query ", "" + query);
for (int i = 0; i < query.length(); i++) {
try {
pdialog.dismiss();
JSONObject object = query.getJSONObject(i);
String dateinsertannonce = object.getString("date_insert_annonce");
Log.i("date", dateinsertannonce);
String datevente = object.getString("vendu");
String marque = object.getString("marque");
String Clomn_Model = object.getString("model");
String Clomn_Prix = object.getString("prix");
String Clomn_Kilometrage = object.getString("kilometrage");
String Clomn_BoiteVitesse = object.getString("boite_vitesse");
String Clomn_Energie = object.getString("energie");
String Clomn_Source = object.getString("source");
String Clomn_Url = object.getString("url");
String Clomn_PHOTO = object.getString("images_noms");
String Maj = object.getString("derniere_maj");
int id = object.getInt("id");
voitureList = databaseHelper.getAllVoiture(username, currentLength);
listView.setAdapter(new AdapterLogin(getActivity(), voitureList, username, currentLength));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
});
}
Related
I am using StringEntity with AndroidAsyncHttp but it is deprecated. Is there another way to get this to work while sending my json string in the way I am to my web service?
public void getPropertyImagesAsync(final String[] params) {
JsonStructure jsonStructure = new JsonStructure();
jsonStructure.methodName = "getPropertyWorkorders";
jsonStructure.serviceName = "mobileapi";
jsonStructure.parameters = params;
String jsonString = new Gson().toJson(jsonStructure);
StringEntity entity = null;
try {
entity = new StringEntity(jsonString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post(visnetawrap, BASE_URL + "/amf/gateway/?contentType=application/json", entity, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
AppUtils.outputJsonString(s);
}
#Override
public void onSuccess(int i, Header[] headers, String s) {
AppUtils.outputJsonString(s);
}
});
}
Keep an eye on the situation, but you can probably get away with continuing to use StringEntity for now.
StringEntity is actually part of Apache HTTP, not android-async-http. Google deprecated the entire Apache HTTP API in SDK 22, and removed it from the stub library in SDK 23 (M preview). It reportedly still runs on M devices, but you can't compile it.
Unfortunately, android-async-http was designed around Apache HTTP. Worse, it exposes its use of that API, so it can't be changed without causing breakage. The developers have announced plans to ensure continued support, possibly by introducing a dependency on the standalone Apache HTTP.
I recommend you to use a library for your network operations. You can use Retrofit. It's a powerful library and easy to use.
http://square.github.io/retrofit/
I'm an experienced developer with android and currently i am developing android application that has Django as its server side on heroku cloud.
I'm pretty new to django and django rest framework so i dont really get how to use it except for the guide on their website.
What i was trying to do recently was using Volley/AsyncHttpClient/Apache Http to contact with my django server.
With each of these libraries i got Http 500 error on django in his console output.
What i tried to do on each of them is adding data to the body or parameters.
On Volley - i overrided the getParams and added them to hash
on AsyncHttpClient - i made RequestParams
on HttpClient(apache) - i used a list of NameValuePair and added them as entity of UrlEncodedForm to the http post request.
i also tried on volley and asynchttpclient to add data to the body of the request and it didn't worked also.
I even thought of changing my server side because of all the trouble Django is causing me , so please if anyone have the answer please give it :)
This is my Server Side(Django):
class User(APIView):
queryset = AppUser.objects.all()
def get(self,request,format=None):
users = AppUser.objects.all()
serialized_users = UserSerializer(users, many=True)
return HttpResponse(serialized_users.data)
def post(self,request):
user_serializer = UserSerializer(data=request.DATA)
if user_serializer.is_valid():
user_serializer.save()
return HttpResponse(status.HTTP_201_CREATED)
return HttpResponse(status=status.HTTP_406_NOT_ACCEPTABLE)
**There's no point to show the urls/models/serializer because it all works on the google chrome with the GET method.
Android(apache http client):
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
paramsList.add(new BasicNameValuePair("user",userJson));
post.setEntity(new UrlEncodedFormEntity(paramsList));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
}
Android (AsyncHttpClient):
try {
RequestParams params = new RequestParams();
params.put("user",userJson);
mClient.post(msg.getText().toString(),params,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 201) Toast.makeText(MainActivity.this,"Success" , Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
} catch (Exception e) {
}
I'm really clueless what to do next because i think i covered all my options contacting my server...
Thanks
If I am not wrong, the message in console just says Http 500 Server error without the cause right?
To debug it more, add following to your settings(base.py)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'ERROR',
'class': 'logging.StreamHandler',
'stream': sys.stderr
},
},
'loggers': {
'django.request': {
'handlers': ['console'],
'propogate': True,
'level': 'ERROR',
}
}
}
This few lines in your settings will print the cause of 500 error in the console, you might get clue to what you are doing wrong.
I have the following json formatted string that is returned from the web service:
{"Success":false,"Message":"This version is not supported"}
I am using the following code to invoke the web service:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://mywebsite/check/getcompatibilityinfo", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
The response contains the json string now I need to access the Success and the Message property. Is there any simple way to do it without using complicated third party libraries?
The JSONObject class is already available in your Android codebase (no 3rd party dependencies). Since your example uses normal (simple) JSON, you can use:
try {
JSONObject responseJSON = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
boolean success = responseJSON.getBoolean("Success");
String message = responseJSON.getString("Message");
I want to send an image from the android client to the Django server using Http Post. The image is chosen from the gallery. At present, I am using list value name Pairs to send the necessary data to the server and receiving responses from Django in JSON. Can the same approach be used for images (with urls for images embedded in JSON responses)?
Also, which is a better method: accessing images remotely without downloading them from the server or downloading and storing them in a Bitmap array and using them locally? The images are few in number (<10) and small in size (50*50 dip).
Any tutorial to tackle these problems would be much appreciated.
Edit: The images chosen from the gallery are sent to the server after scaling it to required size.
I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your NameValuePair using image as the key-name.
Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your project and add them to your Java build path.
You will need to add the following imports to your class.
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
Version 4.3.5 Updated Code
httpclient-4.3.5.jar
httpcore-4.3.2.jar
httpmime-4.3.5.jar
Since MultipartEntity has been deprecated. Please see the code below.
String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
if (career != null)
builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());
post.setEntity(builder.build());
try {
responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
// System.out.println("Response from Server ==> " + responseBody);
JSONObject object = new JSONObject(responseBody);
Boolean success = object.optBoolean("success");
String message = object.optString("error");
if (!success) {
responseBody = message;
} else {
responseBody = "success";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
The loopj library can be used straight-forward for this purpose:
SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("text", "some string");
params.put("image", new File(imagePath));
client.post("http://example.com", params, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
// error handling
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
// success
}
});
http://loopj.com/
I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.
I usually do this in the thread handling the json response:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.
I want to send an image from the android client to the Django server using Http Post. The image is chosen from the gallery. At present, I am using list value name Pairs to send the necessary data to the server and receiving responses from Django in JSON. Can the same approach be used for images (with urls for images embedded in JSON responses)?
Also, which is a better method: accessing images remotely without downloading them from the server or downloading and storing them in a Bitmap array and using them locally? The images are few in number (<10) and small in size (50*50 dip).
Any tutorial to tackle these problems would be much appreciated.
Edit: The images chosen from the gallery are sent to the server after scaling it to required size.
I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your NameValuePair using image as the key-name.
Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your project and add them to your Java build path.
You will need to add the following imports to your class.
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
Version 4.3.5 Updated Code
httpclient-4.3.5.jar
httpcore-4.3.2.jar
httpmime-4.3.5.jar
Since MultipartEntity has been deprecated. Please see the code below.
String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
if (career != null)
builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());
post.setEntity(builder.build());
try {
responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
// System.out.println("Response from Server ==> " + responseBody);
JSONObject object = new JSONObject(responseBody);
Boolean success = object.optBoolean("success");
String message = object.optString("error");
if (!success) {
responseBody = message;
} else {
responseBody = "success";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
The loopj library can be used straight-forward for this purpose:
SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("text", "some string");
params.put("image", new File(imagePath));
client.post("http://example.com", params, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
// error handling
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
// success
}
});
http://loopj.com/
I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.
I usually do this in the thread handling the json response:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.