Android really long execution time of HTTP request - java

i have a problem in my app. At start i will describe how it works. It send request to the server (which wasn't created by me), and in the response i am getting JSON string ( it's not so big average 10 records in JSONarray) there in one parameter there is URL to the picture which i download and save as a bitmap for every JSON object. To summarize i download a JSON which looks like:
{
"id":"125",
"description":"desc",
"type":"type",
"state":"state",
"date":"2012-09-22 10:40:46.0",
"lat":"52.321911",
"lng":"19.464111",
"author":"user",
"photo":"GetImage?size=small&id=0",
"comments":[
]
}
x 10 for example, and then i download from URL "photo" image for every object. Problem lies in the time of execution, it is really really long which it should't it is not big data. Here it is how i do this: AsyncClass that download image:
private class HttpGetImage extends AsyncTask<Object, Integer, Integer>
{
public boolean ready = false;
public boolean success = false;
#Override
protected Integer doInBackground(Object... obj) {
DefaultHttpClient client = new MyHttpClient(ViewEdit.this);
HttpGet get = new HttpGet(url+photoUrl);
HttpResponse getResponse = null;
try {
getResponse = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
HttpEntity responseEntity = getResponse.getEntity();
BufferedHttpEntity httpEntity = null;
try {
httpEntity = new BufferedHttpEntity(responseEntity);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
ready=true; return null;
}
InputStream imageStream = null;
try {
imageStream = httpEntity.getContent();
m_orders.get((Integer)obj[1])
.setOrderBitmap(BitmapFactory.decodeStream(imageStream));
success = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} finally {
try {
imageStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
}
ready = true;
return null;
}
}
and AsyncClass for jsonString:
private class HttpGetNotifications extends AsyncTask<Double, Integer, Integer>
{
public boolean ready = false;
public boolean success = false;
#Override
protected Integer doInBackground(Double... params)
{
DefaultHttpClient client = new MyHttpClient(ViewEdit.this);
HttpGet get = new HttpGet(url + Double.toString(params[0]) + "&longitude=" + Double.toString(params[1]) + "&radius="+distance);
HttpResponse getResponse = null;
try {
getResponse = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
HttpEntity responseEntity = getResponse.getEntity();
String entityContents="";
try {
entityContents = EntityUtils.toString(responseEntity);
loadNotifications(entityContents);
success = true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
ready = true;
return null;
}
public void loadNotifications(String jsonstring) throws JSONException
{
JSONObject jsonResponse = new JSONObject(jsonstring);
JSONArray notifi = jsonResponse.getJSONArray("notifications");
for (int i =0, count = notifi.length(); i <count; i++){
//storage of data
}
}
}
Maybe you guys have an idea how can i optimize that code to reduce a time of execution?

Put in some profiling to find what's taking the time. In each of your AsyncTasks:
private long time0, time1;
#Override protected void onPreExecute() {
time0 = System.currentTimeMillis();
}
#Override protected void onPostExecute(HttpResponse response) {
time1 = System.currentTimeMillis();
long deltaT = (time1 - time0);
Log.d(TAG, "Execute took "+deltaT+"ms");
}
And then go from there.

Related

Java SocketException: Network is unreachable, but the URL works in the browser

I am trying to read some data via a GET request as
URL corpusDbUrl = null;
try {
corpusDbUrl = new URL("http://xxx.cc.ww.tt:1234/erwet/erherh/iouiiu");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URLConnection corpusDbConn = null;
try {
corpusDbConn = corpusDbUrl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(corpusDbConn.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String inputLine="";
try {
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
} catch (Exception e) { // TODO Auto-generated catch block
e.printStackTrace();
}
and i get
java.net.SocketException: Network is unreachable
but when i try the URL in browser, it works just fine. What am i doing wrong?

InvocationTargetException for ClassLoaders.callStaticFunction Java Eclipse

I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}

Jsoup can't open html page Status=-1

While connecting to a URL i'm getting Below is the logcat error i'm getting
and below that my code to connect to url.
When i try to connect to base url http://www.apkmania.co/ it connects successfully
but when try to connect to this url it throws me an error.
07-31 20:47:20.150: I/System.out(14295): IOException: org.jsoup.HttpStatusException: HTTP error fetching URL. Status=404, URL=http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html/
break;
Thread thread=new Thread(new Runnable(){
public void run(){
PrepareItem(webrss);
runOnUiThread(new Runnable(){
public void run() {
if(dialog.isShowing()){
try {
setDataToHandels();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("SET DATA TO HANDELS: " + e);
}
dialog.dismiss();
}
}
});
}
});
thread.start();
break;
private void PrepareItem(String url) {
System.out.println(url);
Document content= null;
try {
content = Jsoup.connect(url).userAgent("Mozilla").timeout(10*1000).get();
} catch (final IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException: " + e.toString());
}
int i=0;
try {
Elements html1 = content.getElementById("main-wrapper").getElementsByTag("div").get(16).children();
html1.select("img").first().remove();
String[] main_content= new String[html1.size()];
i=0;
for (Element element_src : html1.select("div")) {
if (element_src.attr("dir").equals("ltr")) {
main_content[i] = element_src.toString();
i++;
}
}
for (int j = 0; j < main_content.length-2; j++) {
all_text = all_text+main_content[j];
}
all_images_ems = html1.select("img");
all_images_src = new String[all_images_ems.size()];
i=0;
for (Element img_src : all_images_ems) {
all_images_src[i] = img_src.attr("src");
i++;
}
anchor_link_ems = html1.select("a");
all_links = new String[anchor_link_ems.size()];
i=0;
for (Element anchor_links : anchor_link_ems) {
all_links[i] = anchor_links.attr("href");
i++;
}
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Please help me in this regard.
There's a slash at the end of the url.
http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html/
If you remove the slash at the end, it should work.
http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html
Edit:
It's working for me like this.
String url = "http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html";
Document content = null;
try {
content = Jsoup.connect(url).userAgent("Mozilla").timeout(10*1000).get();
} catch (final IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException: " + e.toString());
}
System.out.println(content);
And I'm getting
<!DOCTYPE html PUBLIC "- ...
I solved the problem here is the code if anybody in future needs
String url = "http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html"
URL url1;
InputStream in = null;
try {
url1 = new URL(url);
URLConnection urlConnection = url1.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Document content= null;
try {
content = Jsoup.parse(in, "UTF-8", url);
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
e1.printStackTrace();
}

How do I convert a string to an iCalendar(ics) object?

I have been given the task of implementing a way to convert a string received through a JSON object to an iCalendar object(ics). I found the iCal4j library and have been attempting to use that as my parser. however it seems that the CalendarBuilder takes an InputStream.
How do I proceed ?
String response = jsonObj.getString("icalendar");
CalendarBuilder calBuiler = new CalendarBuilder();
Calendar calendar = calBuilder.build("???");
....
Edit : Would this work?
public Calendar convertStringtoCalendar(String arg)
{
CalendarBuilder calBuiler = new CalendarBuilder();
InputStream is;
try {
is = new ByteArrayInputStream(arg.getBytes("UTF-8"));
return calBuiler.build(is);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Solved the problem by doing the following.
public static Component getCalendarEvent(String myCalendarString)
{
try {
StringReader sin = new StringReader(myCalendarString);
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = builder.build(sin);
return (Component)calendar.getComponent("VEVENT");
} catch (Exception e) {e.printStackTrace();}
return null;
}
I suggest you try my new iCalendar API for Java called iCalendarFx. It can parse a string into any calendar element - VCALENDAR, VEVENT, etc.
You can check it out at http://jfxtras.org/
You can download it at https://github.com/JFXtras/jfxtras/tree/8.0/jfxtras-icalendarfx

Can't get Android 2.3 to handle GZIp

Having some issue with Android 2.3 not picking up the Content-Encoding header from our server.
See http://pastebin.com/v0Jvn0nD for a comparison with 2.2 and 2.3.
So, I am trying to get a workaround so Android can handle the GZIP, at the moment it just fails. Here is the connection logic:
Any help would be cool. Many thanks
URL test = null;
try {
test = new URL(url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection connection = null;
try {
connection = test.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = null;
try {
stream = connection.getInputStream();
Log.d("HttpHelper","getContentEncoding: " + connection.getContentEncoding()); // RETURNING NULL ON 2.3
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ("gzip".equals(connection.getContentEncoding())) { // NULL HERE ON 2.3
try {
stream = new GZIPInputStream(stream);
responseString = textHelper.getText(stream);
globallistener.onComplete(responseString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories

Resources