Android Get XML from URL as string - android

I am very new to Android Development and Java,
I have C# experience
anyway
I am trying to get XML from a URL
I tried every possible thing but non is working.
Always get crash or no result.
I just want a simple XML result, I found some JSON and PHP code, that i do not want to connect to MySQL.
is there any simple function to retrieve the XML as string from a URL
this is one of my traials
`
lbl1 = (TextView) findViewById(R.id.lbl1);
try {
InputStream is = new URL("http://api.androidhive.info/pizza/?format=xml").openConnection().getInputStream();
String strxml = is.toString();
lbl1.setText(strxml);
}
catch (MalformedURLException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}`
any help will be much appreciated. Thanks

How would you do it in C#?
URL.toString() and (in c#) Request.Url.ToString() are alike. Both behave the same way: creating a string of the URL.
(Like in C#) you would need a HTTP client: http://android-developers.blogspot.de/2011/09/androids-http-clients.html

Related

How to call value from string folder in android?

How do i call a link that is stored under
R.strings.myLink , in the below line
URL url = new URL("https://www.myLink.com");
getString(R.string.myLink)
If above shows error, then use below:
context.getResources().getString(R.string.myLink)
use this code
try {
URL url = new URL(getResources().getString(R.string.urllink));
} catch (MalformedURLException e) {
e.printStackTrace();
}

Parsing an XML string into a kXML Element

I'm writing an Android app that connects to a SOAP webservice using kSOAP2, and I have a kXML element where I would like to inject a child based on an XML string I got from elsewhere (a REST API). I have the following code:
Element samlHeader = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
samlHeader.setPrefix("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
samlHeader.setPrefix("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
String samlTokenString = ...; //I got this from elsewhere
Element samlTokenElement = ...; //I don't know how to build this
samlHeader.addChild(Node.ELEMENT, samlTokenElement);
So I'm trying to figure out how to build my Element based on the XML string I'm getting from elsewhere.
This is the solution that we ended up implementing:
try {
KXmlParser parser = new KXmlParser();
parser.setInput(new StringReader(samlTokenString));
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
Document samlTokenDocument = new Document();
samlTokenDocument.parse(parser);
samlHeader.addChild(Node.ELEMENT, samlTokenDocument.getRootElement());
} catch (XmlPullParserException e) {
Log.e(TAG,"Could not parse SAML assertion", e);
} catch (IOException e) {
Log.e(TAG,"Could not parse SAML assertion", e);
}
We're still validating if it produces the right result but it seems to work.

Android OS - How to track Azure upload progress

I've been working with Azure on the Android OS and I managed to upload my video file (.mp4) to a Container I had already prepared for it.
I did this by getting a Shared Access Signature (SAS) first, which provided me with:
a temporary key
the name of the container to where I want to send the files
the server URI
Then, I started an AsyncTask to send the file to the container using the "upload".
I checked the container, and the file gets uploaded perfectly, no problems on that end.
My question is regarding the progress of the upload. Is it possible to track it? I would like to have an upload bar to give a better UX.
P.S - I'm using the Azure Mobile SDK
Here's my code:
private void uploadFile(String filename){
mFileTransferInProgress = true;
try {
Log.d("Funky Stuff", "Blob Azure Config");
final String gFilename = filename;
File file = new File(filename); // File path
String blobUri = blobServerURL + sharedAccessSignature.replaceAll("\"", "");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
//Container name here
CloudBlobContainer container = blobCLient.getContainerReference(blobContainer);
blob = container.getBlockBlobReference(file.getName());
//fileToByteConverter is a method to convert files to a byte[]
byte[] buffer = fileToByteConverter(file);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
if (blob != null) {
new UploadFileToAzure().execute(inputStream);
}
} catch (StorageException e) {
Log.d("Funky Stuff", "StorageException: " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("Funky Stuff", "IOException: " + e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.d("Funky Stuff", "Exception: " + e.toString());
e.printStackTrace();
}
mFileTransferInProgress = false;
//TODO: Missing ProgressChanged method from AWS
}
private class UploadFileToAzure extends
AsyncTask <ByteArrayInputStream, Void, Void>
{
#Override
protected Void doInBackground(ByteArrayInputStream... params) {
try {
Log.d("Funky Stuff", "Entered UploadFileToAzure Async" + uploadEvent.mFilename);
//Method to upload, takes an InputStream and a size
blob.upload(params[0], params[0].available());
params[0].close();
} catch (StorageException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Thanks!
You can split your file and send its part using Block, there is a good example of your case in this link but it used C# so you should find the corresponding function in the android library reference.
Basically instead of sending you file as one big file, you split it to multiple files (bytes) and send it to azure so you can track the progress on how many bytes that already sent to azure

Passing an image from webview to application (IOS and Android)

I'm building hybrid applications that rely on 2-way communication between javascript in a webview and the hosting application.
Attitudes differ somewhat as in IOS the JS can send a message to swift (using WKWebView), that listens through
userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
when implementing the WKScriptMessageHandler protocol,
whereas in Android the JS can actually call an Android method that has #JavascriptInterface annotation, after calling addJavascriptInterface().
Both approaches are OK for me, as I'm passing around data using JSON strings. Question is, what if I need to pass a media file, say an image or video, from the web page to the application? should I just pass a bitmap inside the json? Seems a little naive... recommendations?
edit: when passing an image from the application to the webpage I save the file to the file system and send the filename to the webview. Can it be done the other way around? Can javascript save to the hosting mobile device file system?
You have to host(in case of webapp) or store(in case of mobile app) the image and pass the image url, not exactly the image.
Almost all api that uses images bitmap also takes image url.
regards
Ashish
To answer your second question which is there are comments, use the following code.
Here the html content is your binary content:
FileWriter imageFileWriter = null;
BufferedWriter imageBufferedWriter = null;
ABOUtil.createDir(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
File imageFileDir = new File(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
String imageName = "/finalimage"+ filename + jpg
File mimageFile = new File(imageFileDir, imageName);
try {
imageFileWriter = new FileWriter(mimageFile, false);
imageBufferedWriter = new BufferedWriter(imageFileWriter);
StringBuilder sb = new StringBuilder();
sb.append(htmlContent);
sb.append(scriptInjectJavascript(lstimageNameValue));
imageBufferedWriter.write(sb.toString());
imageBufferedWriter.close();
return mimageFile;
}
catch (IOException e) {
MAFLogger.e("", "", e);
}
finally{
if(imageFileWriter!=null)
try {
imageFileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
if(imageBufferedWriter!=null)
try {
imageBufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
}

Weird JSON encoding issue on Android 4.1.2

I have an issue on Android 4.1.2 where a JSON object given to us by our REST API gets encoded weirdly when sending back.
This is the snippet of json I'm getting:
"cost":{
"amount": 0,
"currency": "GBP"
}
I'm wanting to pretty much just pass this particular snippet back the same way (modifying other parts of the json), but this is what I get on Android 4.1.2:
"cost":"{amount=0, currency=GBP}"
The function I believe is causing this weird encoding is here:
private StringEntity getEntityForRequest(final Payment payment, final PaymentDelegate delegate) {
JSONObject json = new JSONObject();
MyApplication.getContext().addApplicationInformationToJSONObject(json);
StringEntity entity = null;
try {
entity = new StringEntity(json.toString(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
payment.markAsFailed("Reservation failed, data returned not expected.");
save(payment);
if (delegate != null) {
delegate.onFailure(new MyError(MyError.DEFAULT_STATUS, MyError.DEFAULT_TYPE, "Payment error", "Error during reservation"));
}
}
return entity;
}
This is the addApplicationIformationToJSONObject function:
/**
* Adds system information to a JSON object.
*/
public void addApplicationInformationToJSONObject(JSONObject json) {
try {
try {
json.put("app_version", getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
json.put("app_version", "Unknown");
}
json.put("device", getDeviceName());
json.put("os_type", "android");
json.put("os_version", String.format("%d", Build.VERSION.SDK_INT));
json.put("device_id", Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID));
} catch (JSONException e) {
MyLog.e("MyApplication", "Error when adding system information to JSON");
}
}
What's causing this weird encoding?
How can I modify the code to avoid issues like this?
Found a solution. It seems older version interprets that cost snippet as a string rather than a JSONObject. Doing this seems to solve the issue:
ticketObject.remove("cost");
ticketObject.put("cost", new JSONObject(getCost()));

Categories

Resources