StringIndexOutOfBoundsException in android - android

I am getting the following error:
java.lang.StringIndexOutOfBoundsException: length=13243; regionStart=32; regionLength=-39
at java.lang.String.startEndAndLength(String.java:593)
at java.lang.String.substring(String.java:1474)
at com.dict.XMLParser.getResultFromXML(XMLParser.java:63)
at com.dict.InternetDictProvider.searchWord(InternetDictProvider.java:29)
at com.dict.SearchDict$SearchOnline.doInBackground(SearchDict.java:130)
at com.dict.SearchDict$SearchOnline.doInBackground(SearchDict.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
in the following code which typically gets results after parsing the XML page given as HttpResponse to a HttpGet :
retry:
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://oxforddictionaries.com/definition/"+query+"?q="+query);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String meanings=parser.getResultFromXML(StringUtils.inputStreamToString(httpEntity.getContent()));
if(meanings==null && firstRetry)
{
firstRetry=false;
query = query.substring(0, 1).toUpperCase() + query.substring(1);
break retry;
}
else if(meanings==null && !firstRetry)
return query;
result = query + ":" + meanings;
}

query = query.substring(0, 1).toUpperCase() + query.substring(1);
i think this statement create exeption so use if(null!=query&&query.length()!=0){query=...}
and if you substring your string length more than 1 in your case

Related

Error in adding file to MultipartEntityBuilder in android

In my Android project I'm using MultipartEntityBuilder in uploading files to backend using an AsyncTask. I'm using httpmime-4.5.2 in my project.my doInBackground method in uploading AsyncTask is as below.
#Override
protected String doInBackground(String... params) {
try {
String serverLoaction = params[0];
String filePath = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(serverLoaction);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
entity.addPart("file", fileBody);
HttpEntity entity_ = entity.build();
httpPost.setEntity(entity_);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
but when the AsyncTask is executing it gives me following error.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1912)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1884)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841)
 
so whats wrong with this code. how can I fix this. Thanks and regards.
Finally I figured out the reason. I've imported httpmime library in to the project. But in my case it need another library to be executed together with httpmime. I import httpcore library and build the project. it solve the problem. :D I just add below line to build.gradle and re build the project.
compile 'org.apache.httpcomponents:httpcore:4.4.4'

MultipartEntityBuilder on API 22

I want to upload an image to server but i need to send 2 more things in order to connect with the server any HELP cause im really stuck on this one.
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// MultipartEntity entity = new MultipartEntity();
try {
File file = new File(path);
// Adding file data to http body
builder.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
builder.addTextBody("confid", name);
builder.addTextBody("udid", id);
entity = builder.build();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
Here are the errors from android Studio logcat
0-08 12:06:01.216 8616-8787/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.mime.MultipartEntityBuilder
at com.example.oleg.myapplication.MainActivity$1.uploadFile(MainActivity.java:305)
at com.example.oleg.myapplication.MainActivity$1.doInBackground(MainActivity.java:285) at com.example.oleg.myapplication.MainActivity$1.doInBackground(MainActivity.java:279) at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)

Httpget with cookie android

I am trying to get a json string from a webservice. I have successfully login and saved a cookie in my sharepreference. the cookie is then passed to the getMyAdverts method with a url/path to retrieve the json data. Here is my method.
public static String getMyAdverts( String path, String cookie) throws ClientProtocolException, IOException, JSONException{
String link =path;
System.out.println(link);
String responseBody = null;
HttpGet httpget = new HttpGet(path);
System.out.println("cookie "+cookie);
httpget.addHeader("Cookie", cookie);
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget);
System.out.println("response: "+response);
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
}
My problem is i don't get any response. Have i passed the cookie correctly or did i miss a step. Here is my log.
11-14 11:15:05.246: W/System.err(24636): java.lang.NullPointerException
11-14 11:15:05.246: W/System.err(24636): at application.util.Utils.getMyAdverts(Utils.java:352)
11-14 11:15:05.246: W/System.err(24636): at application.app.applicationMenu$loadingTask.doInBackground(applicationMenu.java:478)
11-14 11:15:05.253: W/System.err(24636): at application.app.applicationMenu$loadingTask.doInBackground(applicationMenu.java:1)
11-14 11:15:05.253: W/System.err(24636): at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-14 11:15:05.253: V/SlidingMenu(24636): changing layerType. hardware? true
11-14 11:15:05.253: W/System.err(24636): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-14 11:15:05.253: W/System.err(24636): at java.lang.Thread.run(Thread.java:856)
UPDATE: METHOD 2 : THE COOKIE IS EXPIRED BUT THE COOKIE SHOULD EXPIRE ON SATURDAY 16 NOVEMBER HOW COME
public static void cookieSession(String url, String cookie) throws ClientProtocolException, IOException{
String responseBody = null;
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie stdCookie = new BasicClientCookie("Cookie",cookie);
cookieStore.addCookie(stdCookie);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,
cookieStore);
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Cookie", cookie);
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
}
}

Force Close asynctask (Illegal Character)

I am getting this error, which is odd because it works from another activity calling the same async task. I can not figure out what the illegal character is in my query:
09-06 17:42:29.098 32101-32497/com.beerportfolio.beerportfoliopro E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 50: http://beerportfolio.com/app_getTopTaste.php?t=Rum
at java.net.URI.create(URI.java:727)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.readJSONFeed(GetTopTasteBeersJSON.java:139)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.doInBackground(GetTopTasteBeersJSON.java:49)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.doInBackground(GetTopTasteBeersJSON.java:34)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 5 more
Illegal character in query at index 50: http://beerportfolio.com/app_getTopTaste.php?t=Rum
It's the character at index 50, which is right after "Rum". It's probably some sort of whitespace character. You'll have to post your code for how you get/generate that URL if you want more details, but you might need to add some code to strip whitespace somewhere.
try to trim the string. It removes unwanted whitespace at the end of the string.
String url = " http://beerportfolio.com/app_getTopTaste.php?t=Rum";
HttpGet request = new HttpGet(url.trim());
Try the below
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = " http://beerportfolio.com/app_getTopTaste.php?t=Rum";
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
Log.i(".......",_response);
I just tried your url and i do get the response
09-06 22:05:04.547: I/.......(1460): [{"beer":"Rum Cask","rate":"5","id":"dkRDyR","breweryID":"jC0TAa"}]
As kabuko stated character 50 is after Rum. I think kabuko is right.
I guess you have space at the end of url. It is better to encode the url as below.
String query = URLEncoder.encode("Rum ", "utf-8");
String url = "http://beerportfolio.com/app_getTopTaste.php?t=" + query;
HttpGet request = new HttpGet(url);
URL encoding in Android

Sending JSON from Android to .NET WCF with international characters. How?

I'm getting exceptions when I'm trying to POST and my JSON has some international characters.
This is code that I use:
HttpPost request = new HttpPost(serviceURL + url);
request.addHeader("Authorization", "Basic " + Preferences.getAuthorizationTicket(mContext));
request.addHeader("DeviceSerialNumber", Utility.getDeviceSerialNumber(mContext));
request.addHeader("OSVersion", "Android v" + Build.VERSION.RELEASE);
StringEntity entity = new StringEntity(requestData);
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setEntity(entity);
ResponseHandler<String> handler = new BasicResponseHandler();
response.Body = mHttpClient.execute(request, handler);
response.Code = HttpURLConnection.HTTP_OK;
response.Message = "OK";
And this is error I'm getting:
org.apache.http.client.HttpResponseException:
Bad Request at
org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
at
org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
at
com.idatt.common.AsyncProcessor.processPOST(AsyncProcessor.java:550)
at
com.idatt.common.AsyncProcessor.PostMail(AsyncProcessor.java:367)
at
com.idatt.common.AsyncProcessor.doInBackground(AsyncProcessor.java:120)
at
com.idatt.common.AsyncProcessor.doInBackground(AsyncProcessor.java:28)
at
android.os.AsyncTask$2.call(AsyncTask.java:185)
at
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at
java.util.concurrent.FutureTask.run(FutureTask.java:137)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at
java.lang.Thread.run(Thread.java:1096)
When requestData doesn't have any international (russian, polish, etc) letters than it works fine. What do I miss? Or better yet how do I get traffic from emulator captured in Fiddler or something?
I believe you should specify UTF-8 charset when you create StringEntity:
StringEntity entity = new StringEntity(requestData,"utf-8");
http://developer.android.com/reference/org/apache/http/entity/StringEntity.html#StringEntity(java.lang.String, java.lang.String)

Categories

Resources