android- Intentional '%' in string throws IllegalArgumentException - android

I am making a http call to an api for a string response.
The result contains intentional % signs in a sentence like:
"This land is 95% fertail and 5% contaminated"
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
EDIT: StackTrace:
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:818)
Caused by: java.lang.IllegalArgumentException: Invalid % sequence at 1756: [{"address":{"addressComponen...
My httpGet method:
public String makeHttpGetRequestUtf8(String urlStr) throws IOException {
String result = "";
try {
URL url = new URL(urlStr);
BufferedReader brIn = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String line = "";
while ((line = brIn.readLine()) != null)
result += line;
}catch (Exception e){
Log.e("HTT_GET", "Failed to make httpGetRequestUtf8: " + e);
}
String afterDecode = URLDecoder.decode(result, "UTF-8");
return afterDecode;
}
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
Server writes this data with this metod and so I believe the encoding should be fine?
File file = new File(path/filename.txt);
String content = writeMeToFile;
Writer out;
try{
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "UTF8"));
if(!file.exists()){
file.createNewFile();
}else{
FileUtils.copyFile(file, dest);
out.write(content);
out.close();
}
} catch (IOException e) {
Logger.getLogger(UpdateAds.class.getName()).log(Level.SEVERE, null, e);
}
Side question/note: Somehow characters like 'ä', 'ö', 'ü', 'õ' are fine in the browser but show up as � in android.
I don't understand at which side am I encoding the string wrong. Since the text is fine in the browser I am thinking it's android, but the httpGet method is done by the book.
Thanks!

Related

Can't read from buffered reader in android

I am trying to get data by using API. I get data in bufferedreader which contains multiple lines. But I am not able to extract that in a String. I do know that bufferedreader has data, i have checked by displaying it using multiple .readLine(); but the loop doesn't work.
protected String[][] doInBackground(Cursor[] cursors)
{
String list[][] = new String[cursors[0].getCount()][2];
//while(cursors[0].moveToNext())
{
String DATA="",temp;
String baseAddress="http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY";
String apiKey="J63P";
Uri Url = Uri.parse(baseAddress)
.buildUpon()
.appendQueryParameter("symbol","SBIN")
.appendQueryParameter("interval","1min")
.appendQueryParameter("apikey",apiKey)
.build();
Log.d("built URL",Url.toString());
try
{
url= new URL(Url.toString());
urlconnection= (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
urlconnection.connect();
InputStream inputStream = urlconnection.getInputStream();
if (inputStream==null)
{
Log.d("inputstream","empty");
return null;
}
BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream));
while((temp = reader.readLine())!=null)
{
DATA.concat(temp);
}
Log.d("unedited",DATA);
}
catch(IOException e)
{
Log.e("createList", "Error in url ", e);
return null;
}
try {
String List = "Time Series (1min)";
JSONObject full = new JSONObject(DATA);
JSONArray permin = full.getJSONArray(List);
for (int i=0;i<permin.length();i++)
{
String open,high,low,close;
JSONObject current = permin.getJSONObject(i);
open = current.getString("1. open");
high = current.getString("2. high");
low = current.getString("3. low");
close = current.getString("4. close");
Log.d("Extracted ",open + " " + high + " " + low + " " + close +"\n");
}
}
catch (JSONException e)
{
Log.e("createList","Error in json",e);
}
}
return list;
}
and Log is:
04-24 14:34:52.009 3574-3619/lcukerd.com.stocknotifier D/built URL: http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=SBIN&interval=1min&apikey=J63P
04-24 14:34:53.723 3574-3619/lcukerd.com.stocknotifier E/createList: Error in json
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at lcukerd.com.stocknotifier.MainActivity$createList$override.doInBackground(MainActivity.java:123)
at lcukerd.com.stocknotifier.MainActivity$createList$override.access$dispatch(MainActivity.java)
at lcukerd.com.stocknotifier.MainActivity$createList.doInBackground(MainActivity.java:0)
at lcukerd.com.stocknotifier.MainActivity$createList.doInBackground(MainActivity.java:69)
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:818)
Also, note that "Log" statement after inner while loop is also not working.
Pls, Help me Solve it.
You got exception in the Json data, it is very clear from the log, it says:
04-24 14:34:53.723 3574-3619/lcukerd.com.stocknotifier E/createList:
Error in json
Oh yeah:
Change this line:
DATA.concat(temp);
To
data = DATA.concat(temp);
Also in java it's better to write it this way:
data += temp;

AsyncTask DoInBackground downloading Google Spreadsheets Data Returning Null?

Here is the code:
#Override
public String doInBackground(String... params)
{
try
{
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //Cast HttpUrlConnection because URL does not contain methods available to url, creates object
httpURLConnection.setRequestMethod("GET"); //Request data from source
httpURLConnection.setDoInput(true);
httpURLConnection.connect(); //Object actually connects, connect() invoked by getInputStream() etc.
//Reads data from network stream
InputStream inputStream = httpURLConnection.getInputStream();
//Rather than read one character at a time from the network or disk, BufferedReader reads a larger block at a time
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Used to create mutable string e.g. append()
StringBuilder stringBuilder = new StringBuilder();
String line = "";
//Change stream data to StringBuilder data
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
I'm basically downloading the JSON data from Google Spreadsheets, but the result returned from the doInBackground function continues to return some sort of a null object reference. What does this mean?...
EDIT*
Here is my logcat:
07-28 12:41:30.289 3796-3891/com.example.steven.app E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.steven.app, PID: 3796
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.AlertDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:95)
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
Picture of what is actually being stored inside String result...
My problem was:
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
I found out that by reading here:
URLConnection Doesn't Follow Redirect
the setFollowRedirect and setInstanceFollowRedirects only work automatically when the redirected protocol is same . ie from http to http and https to https. (Shalvika)
I changed the statement to:
URL url = new URL("https://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
Your code looks fine, the problem is that you are not allowed to get data from that URL.
On hitting this URL "http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH"
I am getting following response, so i guess you are getting access denied from server.
google.visualization.Query.setResponse (
{
"version": "0.6",
"status": "error",
"errors": [
{
"reason": "access_denied",
"message": "Access denied",
"detailed_message": "Access denied"
}]
}
)

File upload using MultipartEntityBuilder gives an Error

In my android app I'm using AsyncTask to upload a file to the backend. In there I use MultipartEntityBuilder in my doInBackground method. my doInBackground part is as follows,
#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 builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
StringBody stringBody = new StringBody("data", ContentType.MULTIPART_FORM_DATA);
builder.addPart("file", fileBody);
builder.addPart("name", stringBody);
httpPost.setEntity(builder.build());
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;
}
}
This show me no syntax errors. but when I run the code an exception throws and the app stops. the error log is as below.
Process: com.x.x, PID: 6271
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.NoSuchFieldError: org.apache.http.message.BasicHeaderValueFormatter.INSTANCE
at org.apache.http.entity.ContentType.toString(ContentType.java:153)
at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:56)
at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
at org.apache.http.entity.mime.MultipartEntityBuilder.build(MultipartEntityBuilder.java:240)
at com.x.x.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddCropMonitors.java:1905)
at com.x.x.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddCropMonitors.java:1875)
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)
 
it tells NoSuchFieldError exception raises, but I go through several tutorials and it's seems to me the code is ok according to them. the line number points to where the error occurs is points to
httpPost.setEntity(builder.build());
line. so whats the problem with this code segment and how can I fix this. thanks and regards!
I think this is due to library which you are using in your build.gradle file.
Please check with below code once
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
add this in your build.gradle file.
implementation 'org.apache.httpcomponents:httpmime:4.5.10'

Unknown error while calling Web API from Android

i am trying to send a JSONObject as input parameter for a C# Web API with the following code
protected String doInBackground(JSONObject... companyInfo) {
try {
URL url;
URLConnection urlConn;
url = new URL(HOST_NAME + WEB_API_METHOD);
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Host", HOST_NAME);
urlConn.connect();
PrintWriter out = new PrintWriter(urlConn.getOutputStream());
out.print(companyInfo[0]);
out.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
Log.i("companyInfo > ", stringBuilder.toString());
}
catch (Exception ex)
{
Log.e("Exception", ex.getLocalizedMessage());
}
return null;
}
When this is called, the method doesn't execute and when i try to catch the error, i don't get a meaningful message. it shows the URL name and thats it.
I am unable to find the issue and any help would be appreciated.
this is the error i got
java.io.FileNotFoundException: http://MY_FULL_URL
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at com.fourtyninetons.NewCompanyActivity$saveCompanyProfile.doInBackground(NewCompanyActivity.java:103)
at com.fourtyninetons.NewCompanyActivity$saveCompanyProfile.doInBackground(NewCompanyActivity.java:70)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Lakshman.
As mentioned in the solution of this question, the problem is with the web api method and the backend database. Fiddler helped me solve the issue and the above code is working fine.
Useful Tip: When anyone gets this FileNotFoundExceptionuser POSTMAN or FIDDLER to execute the method and find for the errors.
Thank you everyone who attempted to solve this.

NullPointerException with StringBuilder

I get a very common crash below from the code below.
I thought my try, catches will have handled that.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
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 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:1102)
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:65)
at java.io.InputStreamReader.<init>(InputStreamReader.java:65)
at com.test.test.FinderMain.grabPlaneRoute(FinderMain.java:759)
at com.test.test.FinderMain.access$7(FinderMain.java:729)
at com.test.test.FinderMain$GetRouteTask.doInBackground(FinderMain.java:684)
at com.test.test.FinderMain$GetRouteTask.doInBackground(FinderMain.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
Line 759 is within grabPlaneRoute and is the line containing the "StringBuilder total = new StringBuilder();"
Can someone help with this, it is driving me crazy! :-)
private void grabPlaneRoute(String adshex) {
List<GeoPoint> localList = new ArrayList<GeoPoint>();
HttpURLConnection con = null;
URL url;
InputStream is=null;
try {
url = new URL("http://www.testurl.com&test=" + adshex);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(20000 /* milliseconds */);
con.setConnectTimeout(60000 /* milliseconds */);
con.setRequestMethod("GET");
con.setDoInput(true);
// Start the query
con.connect();
is = con.getInputStream();
}catch (IOException e) {
//handle the exception !
e.printStackTrace();
return;
}
//localList = decodePoly(convertStreamToString(is));
//Log.i("HTTP DUMP", convertStreamToString(is));
BufferedReader r = new BufferedReader(new InputStreamReader(is),8024);
StringBuilder total = new StringBuilder();
String line;
try {
while ((line = r.readLine()) != null) {
String[] separated = line.split(",");
GeoPoint p = getPoint(Double.valueOf(separated[0]),Double.valueOf(separated[1]));
localList.add(p);
}
}catch (IOException e) {
//handle the exception !
e.printStackTrace();
}
drawPlaneRoute(localList);
}
Line 759 is actually the line that begins with BufferedReader r = new ....
The variable is is null.
What happens when con.GetInputStream returns a null, and doesn't throw an exception? You're not handling that case, and that's likely what's happening here.
In addition, I don't see a need for the either try/catch block at all. Just let the exception percolate up the call stack. You're hiding the IOException now, preventing anyone calling grabPlaneRoute from discovering that an error occurred.
It's fairly impossible for StringBuilder total = new StringBuilder(); to cause a NullPointerException. On the other hand, the nearest cause of the Exception is in the logtrace:
at java.io.Reader.<init>(Reader.java:65)
at java.io.InputStreamReader.<init>(InputStreamReader.java:65)
Which makes me think that it's caused by:
BufferedReader r = new BufferedReader(new InputStreamReader(is),8024);
In that case, the only thing that could be null is is.

Categories

Resources