SAX parser getting error while parsing special character " : " - android

<media:group>
<media:content type="video/mp4"
url="http://cdn2.junctiontv.net/dmv/roku/ChiroDiniTumiJeAmar2997fps800kbpsForIPTV.mp4"
bitrate="800"
duration="8100"/>
</media:group>
<media:thumbnail
url="http://cdn2.junctiontv.net/dmv/images/ChiroDiniTumiJeAmar158x204.png"/>
I am trying to parse this xml using SAX Parser. But am getting error due to : in the tags. However if I replace remove : ie, change to its working fine. But problem is ,if I do this, am getting error in url as : is removed after http.
any solution?????????

Instead of using SAXparder, use
android.util.Xml.parse(InputStream,Xml.Encoding.ISO_8859_1, DefaultHandler);
to solve this problem...

This is an appropriate code. Adding this code to any SAX Parser code, xml containing http:// and https:// both can be parsed .
String text10=text9.replaceAll(":", ""); //text9 is any valid url with http:// or https:// or both
String text11="",text12="",text13="",text14="";
if(text10.contains("http//"))
{
text14=text10.replaceAll("http//", "http://");
}
if(text10.contains("https//"))
{
text14=text10.replaceAll("https//", "https://");
}
if(text10.contains("https//") && (text10.contains("http//")))
{
if(text10.contains("http//"))
{
text13=text10.replaceAll("http//", "http://");
}
if(text13.contains("https//"))
{
text14=text13.replaceAll("https//", "https://");
}
}
System.out.println("This is demo text " + text14);

Finally managed to do it.....in a round away process. It works fine if code contains only http://
String text2=text1.replaceAll(":", "");
String text3=text2.replaceAll("http", "http:");
Adding these two lines to my code,makes everything go fine.

Related

About JSON string (URL encoding) of android-webview

In the old version of Webview, the expected operation was achieved by the following processing.
internal fun openURL(json: String) {
try {
val jsonData = JSONObject(json)
WebView Ver:80.0.3987.99
I/chromium: [INFO:CONSOLE(205)] "WebviewToNative API executed:
{"methodname":"openInBrowser","params":{"url":"https:// ..(omitted)..
/init?registid=8og02vdtjmr38ap09hdurk6a2u","backurl":"/"}}", source:
https:// ..(omitted).. /resources/js/native.js?ver=0001
The following error will occur in the new version of Webview for the same string.
WebView Ver:94.0.4606.71
W/System.err: org.json.JSONException: Unterminated string at character
167 of {"url":"https:// ..(omitted)..
/init?registid=epqnn5m4ufveh25tfl25stgp1%22,%22backurl%22:%22/%22}
I have two questions.
What was the fix in Webview for the difference in behavior?
I have confirmed that the following correction code works as expected, but is there any problem?
internal fun openURL(json: String) {
try {
val encoding = "UTF-8"
val decodeJsonStr = URLDecoder.decode(json, encoding);
val jsonData = JSONObject(decodeJsonStr)
this looks like a new bug introduced in URLDecoder, as " character at the end of URL even after decode call is still partially HTML-URL-encoded (closing " is encoded as %22 in here: ...init?registid=...tgp1%22,%22backurl...)
I would recommend to try some lib for parsing JSON, they are mostly more efficient that built-in JSONObject. take a look at gson or Jackson

How to post data for WebView android

I need to post data to Webview.
I found from some of the links the below code:
WebView webview = new WebView(this);
setContentView(webview);
String url = "http://www.example.com";
String postData = username=my_username&password=my_password";
webview.postUrl(url",EncodingUtils.getBytes(postData, "BASE64"));
But in my android studio I see EncodingUtils as deprecated
Can anyone help me what is the alternative for EncodingUtils to post data to Android WebView?
Try like below...
Java:
WebView webview = new WebView(this);
setContentView(webview);
String url = "http://www.example.com";
String postData = "username=" + URLEncoder.encode(my_username, "UTF-8") + "&password=" + URLEncoder.encode(my_password, "UTF-8");
webview.postUrl(url,postData.getBytes());
Kotlin:
val webview = WebView(this)
setContentView(webview)
val url = "http://www.example.com"
val postData = "username=${URLEncoder.encode(my_username, "UTF-8")}" +
"&password=${URLEncoder.encode(my_password, "UTF-8")}"
webview.postUrl(url, postData.toByteArray())
This is a simple workaround.
String html = "<!DOCTYPE html>" +
"<html>" +
"<body onload='document.frm1.submit()'>" +
"<form action='http://www.yoursite.com/postreceiver' method='post' name='frm1'>" +
" <input type='hidden' name='foo' value='12345'><br>" +
" <input type='hidden' name='bar' value='23456'><br>" +
"</form>" +
"</body>" +
"</html>";
webview.loadData(html, "text/html", "UTF-8");
I know this is not the best method but this works.
I would like to add a few things to the answer as I had to work on same and found some info could help complete the answer to this question.
First thing is the need for such a scenario. My need was that I am
creating a payment gateway client for native applications in android.
Second thing is that the URL you are opening needs to perform some
operations right. Hence you must enable your webView to enable
such operations or else things might not work. For example if your
URL is executing some java script, than you must enable java script
for your webview. This can be done as shown below :
val set = webview.settings
set.javaScriptEnabled = true
Normally this will enable trivial things such as timers, returning results etc on your webview.
Third thing is a case when your webView needs to call methods of your android app. This can be done by adding some JavaScript Interface as shown below :
webview.addJavascriptInterface(WebAppInterface(), "Android")
Where WebAppInterface() is a simple class which atleast one method annotated with #JavascriptInterface as shown below :
class WebAppInterface() {
#JavascriptInterface
fun showToast(status: String) {
//show toast here or handle status
}
}
The name Android will be the one which will be injected into your URL as a variable and you can call the methods of your android WebAppInterace from that URL as shown below:
Android.showToast("From WebPage")
Last thing is your postURL method which is somewhat like :
webview.postUrl(actionUrl, params.toByteArray(Charsets.UTF_8))
This method has couple of things that it takes as default. First is that request type is taken as default POST as the name suggest.
Header content-type can be default taken as application/x-www-form-urlencoded and
most important params it takes as & separated key value pairs as shown :
val params = "MERCHANT_ADDR=" + addr + "&CHANNEL=android"
We must pass byteArray of this string which is shown in post URL callback.
Now after your API is hit and it in some cases loads a callback url, from that call back URL using the JavaScript Interface, you can return result to your application and close the webview.
I hope it helps people.
try this:
You need to URL-encode the parameter value before sending it.
String postData = "fileContents=" + URLEncoder.encode(fileCon, "UTF-8");
For those who came here by trying to put a html body as a postData and not working,
try to put your string body as something below:
val htmlCode = "https://ramdom.user.me"
val postData = "{\n" +
"\t\"token\": \"963966f649\"\n" + "}"
webview.postUrl(htmlCode, postData.toByteArray())
I hope to save someone`s life. :-)

About how to pass the ParseObject(Object) using Rest API(service) in Installation class in android?

I am sagar, i am trying to implement the Parse Push-Notification in android using REST API (Service), and i am almost got success in implement the Push-Notification in Xamarin-Android using REST API. But i got stuck with one part in sending the Data into REST service. I trying to pass the ParseObject in service, but the in parse table there is a need of Object,(). I have tried to pass the ParseObject as below:
JsonConvert.SerializeObject(ParseUser.CurrentUser)
It convert ParseObject into array and array is not accepted in table and ,i got failed to save it in table. because there i a need of object.
I need solution or suggestion from developer guys. Yours help will be appreciated. I am trying the below code to achieve the result.
public static void RegisterPush(string regristrationId)
{
if (regristrationId != null) {
string appID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string restID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string masterID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
var client = new RestClient ("https://api.parse.com");
var request = new RestRequest ("1/installations", RestSharp.Method.POST);
request.AddHeader ("Accept", "application/json");
request.AddHeader ("X-Parse-Application-Id", appID);
request.AddHeader ("X-Parse-REST-API-Key", restID);
request.Credentials = new NetworkCredential (appID, masterID);
request.Parameters.Clear ();
Console.Error.WriteLine ("ParseUser.CurrentUser-->"+ (ParseObject) ParseUser.CurrentUser);
//JsonConvert.SerializeObject(ParseUser.CurrentUser)
string strJSONContent = "{\"user\" :"+ JsonConvert.SerializeObject(ParseUser.CurrentUser)+",\"owner\":\"" + ParseUser.CurrentUser.ObjectId + "\",\"deviceType\":\"android\",\"GCMSenderId\":\"1234567890\",\"appName\":\"abcdefgh\",\"pushType\":\"gcm\",\"deviceToken\":\"" + regristrationId + "\"}";
Console.Error.WriteLine("json string-->"+ strJSONContent);
request.AddParameter ("application/json", strJSONContent, ParameterType.RequestBody);
client.ExecuteAsync (request, response => {
Console.Error.WriteLine ("response for android parse installation-->" + response.Content);
});
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
}
}`
Output:{"user" :[{"Key":"dealOffered","Value":4},{"Key":"dealRequested","Value":5},{"Key":"displayName","Value":"Cook"},{"Key":"email","Value":"lorenzo#gmail.com"},{"Key":"firstName","Value":"Lorenzo"},{"Key":"lastName","Value":"Cook"},{"Key":"mobileNumber","Value":9999999999.0},{"Key":"picture","Value":{"IsDirty":false,"Name":"tfss-afd25c29-6679-4843-842c-fe01f7fcf976-profile.jpg","MimeType":"image/jpeg","Url":"http://files.parsetfss.com/profile.jpg"}},{"Key":"provider","Value":"password"},{"Key":"userType","Value":"Merchant"},{"Key":"username","Value":"merchant#sailfish.com"},{"Key":"zipCode","Value":2342343}],"owner":"3cF1vHUXkW","deviceType":"android","GCMSenderId":"1234567890123","appName":"Sailfish","pushType":"gcm","deviceToken":"APA91bE3bsTIInQcoloOBE4kdLVVHVTRVtNyA1A788hYSC15wAVu8mUg-lwk7ZPk370rngrK7J6OoLmiM9HRr1CGPaBo6LCNrSUL7erBku4vepaFFkQzgqS6BcAemp"}
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
maven
I found the solution in , parse xamarin docs, in one query , the way is simple, but i little bit hard to found out.
The issue is with the data passing in json format in REST, to pass any pointer using REST API, use as below.
The solution is as below:
`{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"qYvzFzGAzc"
},
"owner":"qYvzFzGAzc",
"deviceType":"android",
"GCMSenderId":"123456789",
"appName":"NiceApp",
"pushType":"gcm",
"deviceToken":"APA91bFeM10jdrCS6fHqGGSkON17UjEJEfvJEmGpRM-d6hq3hQgDxKHbyrqAIxMnEGgbLEZf0E9AllHxiQQQCdEFiNMF1_A8q0n9tGpBE5NKhvS2ZGJ9PZ7585puWqz_1Z1EjSjOvgZ1LQo708DeL2KzA7EFJmdPAA"
}`
It looks like your column user is set up wrong. It should show as a Pointer<_User> not Pointer
If you load this class in your Data Browser, is the "user" key defined as a string, or a Pointer <_User>
This error seems to indicate that this is a string column, which is why the Parse.User object is not being accepted as a valid value. You might have tried setting a string on this key before, which in turn type-locked the "user" key as a string column.
Found it on the examples given on this page - https://www.parse.com/docs/rest
Have you check your REST API connection while passing ParseObject?
Because your error says:
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
Here "code":111This error code comes when server refuse for connection

Get JSON from a div in html

I have a hidden div which by JavaScript gets filled with json text. I need to find this div and read the json text from it. How can this be done?
<html>
<div id="hiddenJSON">
{
"id":"1234",
"Name":"Jonas",
"Address":"Test Road 5",
"Phone":"1234-1234-1234"
}
</div>
</html>
try below code :-
Pattern p = Pattern.compile(Pattern.quote("<div id=\"hiddenJSON\">") + "(.*?)" + Pattern.quote("</div>"));
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group(1));
}
But better solution is you have to receive data without html tag so talk with back end person.
It would be best to use a library for this such as JSoup. Check out this question about parsing html code
Here is how i solved this:
result is the response from #JavascriptInterface
WebView Fragment
WebView wv = ...
wv.addJavascriptInterface( this, "android" );
wv.loadUrl( "javascript:android.showHTML(document.getElementById('hiddenJSON').innerHTML);" );
Interface in my WebView Fragment
#JavascriptInterface
public void showHTML( String result ) {
// handle JSON (result)
}
Problem:
I had to get the result from my WebView in order to get the JavaScript to run (filling this hidden div with JSON).

Using image URL which has dashes in it

I'm trying to download images from a website and my code is working fine in most cases, but I can't download from this URL http://www.liveandlocal.org.uk/images/ShowPics/Steiny’s%20Blues%20-%20Such%20Sweet%20Thunder.jpg
The difference between this and the other URLs is that this one has a dash. I'm fairly certain this is the problem. Is there a way around this?
My error is java.io.filenotfoundexception
My initial code was:
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/" + Show + ".jpg";
imgLink = imgLink.replace(" ", "%20");
This gave me links like: http://www.liveandlocal.org.uk/images/ShowPics/The%20Atlantics.jpg
which works, but this didn't work for the link I posted at the top.
So now I've tried:
try {
Show = URLEncoder.encode(Show, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/" + Show + ".jpg";
Which doesnt work for any of my links, such as http://www.liveandlocal.org.uk/images/ShowPics/The+Atlantics.jpg
If you copy and paste the link at the start of this post into your browser it will work, so it is just not working on Android.
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/Steiny%E2%80%99s%20Blues%20-%20Such%20Sweet%20Thunder.jpg"
working fine for me, tested it, replace the characters thus accordingly and '.
- is fine.
Your url contains letters which are not suited for urls (' in this case).
You can encode your url as the following:
String encodedUrl = URLEncoder.encode(normalUrl, "UTF-8");
URLEncoder

Categories

Resources