Send a big string to a server in Android - android

I want to send 15 images to a server and I use json objects to convert these images in a String, but when i want to send it, is some devices there are Out of memory exception because there is a big string.
My images has 320x400 more and less and i do this:
First I create a jsonarray with one object to each image:
for (int i = 0; i < images.size(); i++) {
Mat aux = images.get(i);
int cols = aux.cols();
int rows = aux.rows();
int elemSize = (int) aux.elemSize();
byte[] data = new byte[cols * rows * elemSize];
aux.get(0, 0, data);
String dataString = new String(Base64.encode(data, Base64.DEFAULT));
JSONObject obj = new JSONObject();
try {
obj.put("ROWS", aux.rows());
obj.put("COLS", aux.cols());
obj.put("TYPE", aux.type());
obj.put("DATA", dataString);
} catch (JSONException e) {
e.printStackTrace();
}
arrayjson.put(obj);
}
And the i create a json object with contains this array and another params:
final JSONObject jsontoSend = new JSONObject();
try {
jsontoSend.put("USERNAME", user.username);
jsontoSend.put("DATE", getCurrentDateandTime());
jsontoSend.put("IMAGES", arrayjson);
jsontoSend.put("TOTALIMAGES", images.size());
} catch (JSONException e) {
e.printStackTrace();
}
Finally, i try to send this object:
StringEntity send = null;
try {
send = new StringEntity(jsontoSend.toString());
httpPost.setEntity(send);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
return -2;
}
How can i do to send this big string??
Thanks
SOLUTION:
I solved this adding in my Manifest file android:largeHeap="true"with this, android increase my app memory and runs fine

Related

How to get JSONObject without JSONArray

I have such a JSON: https://paste.ubuntu.com/p/HkTK9xTzNx/
How do I get a "imdb_id" String (line 14). There is no array which contains that value,it's not in square branches,so I don't know how to get it.
Solution as per your need:
try {
imdbLink = response.getString("imdb_id");
} catch (JSONException e) {
e.printStackTrace();
}
A standard solution:
String json = "{\"imdb_id\":\"str12345\"}"; // your json response from network call/local file
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
String id = jsonObject.getString("imdb_id");
} catch (Exception e) {
e.printStackTrace();
}

why is a JSON file not getting read by my app?

I am new to Stackoverflow and this is my first question.
I am developing an application where I am reading data from a json file from assets folder and storing the values in array list.
here is my code
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(String.valueOf(jsonObject));
}
} catch (JSONException e) {
e.printStackTrace();
}
// Inflate the layout for this fragment
return rootview;
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And this is my json data structure
"root" : {
"child" : [ "data1","data2","data3",.......]},
I want the data1,data2 values inside a list
Try this
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
list.add(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(jsonObject.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}

How to access volley response like this

How to access volley response {"data":"success"} like this.
i am already try this
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
You're trying to access a JSONArray from a JSONObject while it's just a string. So just replace getJSONArray with getString and try this
String data = new JSONObject(response).getString("data");
Or in your code
try {
JSONObject j = new JSONObject(response);
result = j.getString("data");
}
catch (JSONException e) {
e.printStackTrace();
}
Access Like This
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getString("data");
} catch (JSONException e) {
e.printStackTrace();
}
You can check this, before retrieving check if that tag (i.e. "data" for your case) is exists on that json object.
JSONObject j = null;
try {
j = new JSONObject(response);
if(j.has("data") {
result = j.getString("data");
}
} catch (JSONException e) {
e.printStackTrace();
}
As the value of data is string and to get string value you have to use JSONObject.getString("data")
Use:
result = j.getString("data");
Instead of:
result = j.getJSONArray("data");

Extracting data from server takes too much time- android

I have a android application, where i extract data from the multiple urls and save then as arraylist of string. It works fine, but for fetching data from 13 urls, it takes close to 15-20 sec. Where as fetching the data from same set of urls take 3-4 sec in same app built using phonegap. Here is the code below.
#Override
protected String doInBackground(String... params) {
client = new DefaultHttpClient();
for(int i=0;i<url.size();i++)
{
get = new HttpGet(url.get(i));
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entity = response.getEntity();
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
String str = buffer.toString();
param.add(str);
}
return null;
}
Could anyone please suggest how i can speed this execution and reduce the extraction time.
You could try starting a separate thread for each iteration from the for loop.
Smth like this :
for(int i = 0; i < url.size(); i++){
//start thread that gets data from url and adds it to the list
}

Doctype returned from Server instead of String?

I'm using BitNami to test my django project. I'm creating a connection from android, passing to it a url to fetch some data from the database. The data is in this form:
{"apps": ["False", "Hello from notepade++", "My App", "Test"]}
here's how I'm fetching and receiving the data in android
public static ArrayList<String> getApps(){
HttpClient httpclient = new DefaultHttpClient();
HttpResponse responseCategories;
int categoriesStatusCode =0;
String responseCategoriesString = "";
ArrayList<String> out = new ArrayList<String>();
HttpGet httpgetCategories = new HttpGet("http://safwany/sampleproject/applications/fetch_apps");
try {
responseCategories = httpclient.execute(httpgetCategories);
categoriesStatusCode = responseCategories.getStatusLine().getStatusCode();
try {
responseCategoriesString = EntityUtils.toString(responseCategories.getEntity());
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
if(categoriesStatusCode==200){
JSONObject object;
try {
System.out.println(responseCategoriesString);
object = new JSONObject(responseCategoriesString);
JSONArray Jarray = object.getJSONArray("apps");
for(int i = 0; i < Jarray.length(); i++)
{
String s = (String) Jarray.get(i);
out.add(s);
//categoriesMap.put(s, 0);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return out;
}
When I try to print responseCategoriesString, I get the following:
04-01 22:55:56.335: I/System.out(9325): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="refresh" content="0;url=http://search.tedata.net/main?InterceptSource=0&ClientLocation=eg&ParticipantID=esrkzqp9pwh62lmydaf4wsy3i92taus2&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0"/><script type="text/javascript">url="http://search.tedata.net/main?InterceptSource=0&ClientLocation=eg&ParticipantID=esrkzqp9pwh62lmydaf4wsy3i92taus2&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0";if(top.location!=location){var w=window,d=document,e=d.documentElement,b=d.body,x=w.innerWidth||e.clientWidth||b.clientWidth,y=w.innerHeight||e.clientHeight||b.clientHeight;url+="&w="+x+"&h="+y;}window.location.replace(url);</script></head><body></body></html>
04-01 22:55:56.335: W/System.err(9325): org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
When I look at the response data you get I think you have trouble with some firewall or similar:
http://search.tedata.net/main?InterceptSource=0&ClientLocation=eg&ParticipantID=esrkzqp9pwh62lmydaf4wsy3i92taus2&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0
Contains your requested url:
FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps
But FailedURI sounds like a company firefall/gateway with filter... you should check if your emulator/device can really access the safwany "domain". Maybe you should try an IP instead of safwany?

Categories

Resources