I just wanted to know how to parse the following response of the server. I just wanted to get out the json from the xml. Because I know How to parse the json response So , some one please guide me how can I get this.
I have watched this link for xml parsing but I do not know how to specifically parse this (the underlying given response). the Response is as follows
<string xmlns="http://tempuri.org/">
[{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_3#2x.png","ImageID":"3"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_4#2x.png","ImageID":"4"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_5#2x.png","ImageID":"5"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_6#2x.png","ImageID":"6"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_7#2x.png","ImageID":"7"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_8#2x.png","ImageID":"8"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_9#2x.png","ImageID":"9"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_10#2x.png","ImageID":"10"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_11#2x.png","ImageID":"11"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_12#2x.png","ImageID":"12"}]
</string>
You can see that its in the
<string xmlns="http://tempuri.org/">
I just wanted to know how to parse this type of respne the rest of the response whcih is Json I can do parsing of json by my self. please just help me how to do it
This should work I haven't tested it yet
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
public class StringXmlParser {
// your xml doesn't have any name spacing so make it null.
private static final String ns = null;
public String parse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in,null);
parser.nextTag();
return readString(parser);
} finally {
in.close();
}
}
private String readString(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "string");
String jsonString = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "string");
return jsonString;
}
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
}
And this is how you use it
StringXmlParser xmlParser = new StringXmlParser();
String jsonString;
try {
// You need to get the input stream for the xml.
jsonString = xmlParser.parse(inputStream);
} finally {
if(inputStream != null) {
inputStream.close();
}
}
Related
In my application I want to display RSS feed of a particular website. But I do not want it to display full Rss feed, I want only some particular tags to be searched and display and only its related links should display on screen.
here is my code of the Parser Class:-
package com.example.sara.rssfeed;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
import com.example.sara.rssfeed.RssItem;
public class PcWorldRssParser {
// We don't use namespaces
private final String ns = null;
public List<RssItem> parse(InputStream inputStream) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(inputStream, null);
parser.nextTag();
return readFeed(parser);
} finally {
inputStream.close();
}
}
private List<RssItem> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, null, "rss");
String title = null;
String link = null;
List<RssItem> items = new ArrayList<RssItem>();
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("title")) {
title = readTitle(parser);}
else if (name.equals("link")) {
link = readLink(parser);}
if (title=="Top Stories - Google News" && link=="http://news.google.com/news?hl=en&ned=us") {
RssItem item = new RssItem(title, link);
items.add(item);
title = null;
link = null;
}
}
return items;
}
private String readLink(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "link");
String link = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "link");
return link;
}
private String readTitle(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
return title;
}
// For the tags title and link, extract their text values.
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
}
Error:
on line if (title=="Top Stories - Google News" &&
link=="http://news.google.com/news?hl=en&ned=us")if I put
tittle!=nullandlink!=null`
it displays full rss feed. but If i give it particular link and title tag to search it displays nothing, only a blank screen.
Please help what am I doing wrong.
Thanks in Advance.
I'm following the android xml parsing tutorial (http://developer.android.com/training/basics/network-ops/xml.html#analyze), however when stepping through it, it seems to fail at:
parser.require(XmlPullParser.START_TAG, ns, "rss");
and then ends up dropping to the finally clause. Just wondering if anyone could spot what the issue could be as I've played around with it for hours without much success.
The feed I am trying to read is: http://feeds.bbci.co.uk/news/rss.xml
Any help is greatly appreciated, please find the code below:
package com.proxama.news_bbc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.provider.DocumentsContract.Document;
public class MainActivity extends ActionBarActivity {
private static final String ns = null;
/*
* Only interested in the content of the following XML tags for each news
* item:
*
* item/media:thumbnail item/pubDate item/link item/description item/title
*/
private void skip(XmlPullParser parser) throws XmlPullParserException,
IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
public static class Entry {
public final String title;
public final String link;
public final String summary;
private Entry(String title, String summary, String link) {
this.title = title;
this.summary = summary;
this.link = link;
}
}
// Parses the contents of an entry. If it encounters a title, summary, or
// link tag, hands them off
// to their respective "read" methods for processing. Otherwise, skips the
// tag.
// Processes title tags in the feed.
private String readTitle(XmlPullParser parser) throws IOException,
XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
return title;
}
// Processes link tags in the feed.
private String readLink(XmlPullParser parser) throws IOException,
XmlPullParserException {
String link = "";
parser.require(XmlPullParser.START_TAG, ns, "link");
String tag = parser.getName();
String relType = parser.getAttributeValue(null, "rel");
if (tag.equals("link")) {
if (relType.equals("alternate")) {
link = parser.getAttributeValue(null, "href");
parser.nextTag();
}
}
parser.require(XmlPullParser.END_TAG, ns, "link");
return link;
}
// Processes summary tags in the feed.
private String readSummary(XmlPullParser parser) throws IOException,
XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "summary");
String summary = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "summary");
return summary;
}
// For the tags title and summary, extracts their text values.
private String readText(XmlPullParser parser) throws IOException,
XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
private Entry readEntry(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "item");
String title = null;
String summary = null;
String link = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("title")) {
title = readTitle(parser);
} else if (name.equals("summary")) {
summary = readSummary(parser);
} else if (name.equals("link")) {
link = readLink(parser);
} else {
skip(parser);
}
}
return new Entry(title, summary, link);
}
private List readFeed(XmlPullParser parser) throws XmlPullParserException,
IOException {
List entries = new ArrayList();
String xmlContents = parser.toString();
parser.require(XmlPullParser.START_TAG, ns, "rss");
Log.d("className", "Up to here ");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
// Starts by looking for the news item tag
if (name.equals("item")) {
entries.add(readEntry(parser));
} else {
skip(parser);
}
}
return entries;
}
private List parseXml(InputStream in) throws XmlPullParserException,
IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
return readFeed(parser);
} finally {
in.close();
}
}
private String downloadUrl(String myurl) throws IOException {
// TODO allow for internal storage if external is unavailable or full
File root = android.os.Environment.getExternalStorageDirectory();
String Directory = root.getAbsolutePath() + "/xmls";
String xmlFileName = "bbc_news_rss.xml";
String fullXmlPath = Directory + "/" + xmlFileName;
File dir = new File(Directory);
if (dir.exists() == false) {
dir.mkdirs();
}
/*URL url = new URL(myurl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(fullXmlPath);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();*/
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream in = conn.getInputStream();
Log.d("className", "Saved XML file to: " + fullXmlPath);
Log.d("className", "Starting to parse XML file: " + fullXmlPath);
//InputStream in = new FileInputStream(fullXmlPath);
try {
parseXml(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fullXmlPath;
}
// Uses AsyncTask to create a task away from the main UI thread. This task
// takes a
// URL string and uses it to create an HttpUrlConnection. Once the
// connection
// has been established, the AsyncTask downloads the contents of the webpage
// as
// an InputStream. Finally, the InputStream is converted into a string,
// which is
// displayed in the UI by the AsyncTask's onPostExecute method.
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... stringUrl) {
try {
Log.d("className", "Downloading url: " + stringUrl[0]);
return downloadUrl(stringUrl[0]);
} catch (IOException e) {
return "Unable to retrieve file.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Log.d("className",
"In onpostexecute and result of downloadUrl is: " + result);
// If the file has been saved correctly, parse it.
if (result != "Unable to retrieve file.") {
Log.d("className", "Creating list view");
createList();
}
}
}
/** Pull in the XML from http://feeds.bbci.co.uk/news/rss.xml */
public void pull_xml(View view) {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// can connect so fetch XML file
Log.d("className", "Successfully connected to network!");
new DownloadWebpageTask()
.execute("http://feeds.bbci.co.uk/news/rss.xml");
} else {
// display error
Log.d("className",
"Unable to connect to network, trying to use a previously saved local xml file");
}
}
public void createList() {
setContentView(R.layout.activity_main);
// Get ListView object from XML
ListView listView = (ListView) findViewById(R.id.listView1);
// Defined Array values to show in ListView
String[] values = new String[] { "Ukraine begins 'anti-terror' action" };
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
// Original classes and methods that came by default with new android
// projects.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// retrieve the XML and create list view
pull_xml(null);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Your code has several mistakes:
DownloadWebpageTask.onPostExecute: here you are trying to compare Strings with != operator. It's wrong, you'll always get false. The correct way is to use equals method:
if ("Unable to retrieve file.".equals(result)) {
Log.d("className", "Creating list view");
createList();
}
createList() method: what's the purpose of calling setContentView(R.layout.activity_main); here if you already did it at the onCreate?
pull_xml(View view) method: what's the purpose of view argument? You are not using it at this method.
parseXml method: please add parser.nextTag()
I am new to android development and am trying to work with json data. I followed the web page "
http://hmkcode.com/android-parsing-json-data/" to make a simple app to get and display json. It works fine with the tutorial json web site. But when I change the url to point to my website I get an exception error on the line "JSONObject json = new JSONObject(result);"
03-15 08:56:10.518: W/System.err(1330): org.json.JSONException: Value <?xml of type
java.lang.String cannot be converted to JSONObject
03-15 08:56:10.528: W/System.err(1330): at org.json.JSON.typeMismatch(JSON.java:111)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:159)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:172)
When I display the string I get it looks like this (almost, I had trouble formatting, the mgmtresponse line is all one line, I also blocked out the ip address):
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<mgmtResponse
responseType="operation"requestUrl="https://128.205.x.xxx/webacs/api/v1/op/info/version"
rootUrl="https://128.205.x.xx/webacs/api/v1/op">
-<versionInfoDTO>
<result>2.0.0.0.294</result>
</versionInfoDTO>
</mgmtResponse>
Here is the main section of code. As you can see I tried a bunch of things and commented out a bunch of things to get down to the problem. I am stuck at the point where I can not take my input and convert it to a json object. I think I need to format the response some how but I just can not figure out what is wrong.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText etResponse;
TextView tvIsConnected;
static TextView response_code;
static String httpcode;
static String version;
#Override
// oncreate is called when activity is created
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
response_code = (TextView) findViewById(R.id.response_code);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("network is connected");
}
else{
tvIsConnected.setText("network is NOT connected");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("https://128.205.x.xx/webacs/api/v1/op/info/version");
// new HttpAsyncTask().execute("https://hmkcode.appspot.com/rest/controller/get.json");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new MyHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(request);
final int StatusCode = httpResponse.getStatusLine().getStatusCode();
String st=String.valueOf(StatusCode);
httpcode = st;
//HttpResponse httpResponse = HttpClient.execute(new HttpGet(url));
// receive response as inputStream
//HttpEntity entity = httpResponse.getEntity();
//result = EntityUtils.toString(entity);
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader
(inputStream,"iso-8859-1"),8);
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line+"\n";
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService
(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
// displays results to Edittext and displays recieved to toast
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
response_code.setText(httpcode);
try {
//etResponse.setText(result);
JSONObject json = new JSONObject(result);
//etResponse.setText(json.toString(1));
//JSONObject mgmtResponse =
// new JSONObject(json.getString("mgmtResponse"));
//JSONObject versionInfoDTO =
// new JSONObject(mgmtResponse.getString("versionInfoDTO"));
version = "NCS-Version";
//
//JSONArray articles = json.getJSONArray("articleList"); //get articles array
//str += "articles length = "+json.getJSONArray("articleList").length();
//str += "\n--------\n";
//str += "names: "+articles.getJSONObject(0).names(); //get first articles keys
//str += "\n--------\n";
//str += "url: "+articles.getJSONObject(0).getString("url"); //return an article url
//String str = "NCS Version";
//version += versionInfoDTO.getJSONObject("result");
etResponse.setText(version);
// not - etResponse.setText(json.toString(1));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//etResponse.setText(version);
}
}
}
As Rashmi points out, you are receiving data in XML-format, and attempting to parse it as JSON-format, which is giving you an error. The format of the data can usually be specified in the request URL.
EDIT
Your are using the URL https://128.205.x.xx/webacs/api/v1/op/info/version and I don't know what that is, if it's your own server or not, but usually, APIs provide both XML and JSON formats, which could look something like this:
https://example.com:2087/xml-api/functionname
for XML and
https://example.com:2087/json-api/functionname
for JSON
Some webservices will allow/require you to specify "application/json" as the accept header, so in addition to this:
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
Say what you want back:
request.setHeader("Accept", "application/json");
And, if required, what you are supplying:
request.setHeader("Content-type", "application/json");
Please don't mark it as duplicate as I am fighting for many days and have already tried lots of examples but not able to solve and getting confuse.I am new to WCF and android also
So I have created a WCF service with some get and post method like below
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "RegisterUser",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat= WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
ResultSet RegisterUser(string EmailID, string Name,Stream profilepic, string Mobile, long IMEI);
I am calling this service method by android client as below
MainActivity.java
public void doneOnClick(View v) throws FileNotFoundException,
InterruptedException, JSONException {
// Toast toast = new Toast(this);
// gets IMEI of device ID
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = tm.getDeviceId();
bMap = BitmapFactory.decodeFile(selectedImagePath);
path = SaveImage.writeFileToInternalStorage(getApplicationContext(),
bMap, "UserImage.png");
name = nameV.getText().toString();
mobile = mobileV.getText().toString();
emailID = emailV.getText().toString();
if (name.length() != 0 && mobile.length() != 0 && emailID.length() != 0
&& path.length() != 0) {
SharedPreferences shared = getSharedPreferences(PREFS, 0);
Editor editor = shared.edit();
editor.putString("UserPicPath", path);
editor.putString("UserName", name);
editor.putString("UserMobile1", mobile);
editor.putString("UserEmail", emailID);
editor.putString("IMEI", imei);
editor.commit();
}
JSONArray jsonarr = new JSONArray();
JSONObject jsonObj = new JSONObject();
jsonObj.put("emailID", emailID);
jsonObj.put("name", name);
jsonObj.put("mobile", mobile);
jsonObj.put("imei", imei);
jsonarr.put(jsonObj);
servicemethodname = "RegisterUser";
DownloadWebPageTask bcktask = new DownloadWebPageTask();
bcktask.execute(servicemethodname, jsonarr);
}
and calling backgroundtask as
package com.example.wcfconsumer;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
public class DownloadWebPageTask extends AsyncTask<Object, Integer, String> {
private final static String SERVICE_URI = "http://192.168.0.100:80/Service1.svc/";
protected void onPostExecute(String result) {
MainActivity.emailV.setText(result);
}
#Override
protected String doInBackground(Object... params) {
JSONArray jsonparams = (JSONArray) params[1];
String methodname = params[0].toString();
InputStream is;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVICE_URI + methodname);
StringEntity se = new StringEntity(jsonparams.toString(), "UTF-8");
se.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(se);
Log.e("Gerhard", jsonparams.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
InputStreamReader i = new InputStreamReader(is);
BufferedReader str = new BufferedReader(i);
String msg = str.readLine();
Log.e("Gerhard", msg);
return msg;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String convertToString(Bitmap image) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String mediaString = Base64.encodeToString(data, Base64.URL_SAFE);
return mediaString;
}
}
My question contains multiple part :
1. How to send Image file along with other datatypes to RegisterUser method and get reponse in json format?
2. Does same will work for video file as for the Image file?
3. I want to return customdatatype from service(in this case ResultSet), is there something special I need to do for it?
Please don't mark it as duplicate as I have already tried lots of examples but not able to solve and getting confuse.
Please help me!!! Many Many Many Thanks In Advance.
Regards,
Sourabh
To send a media file (or any arbitrary file, for that matter) to WCF, you need to have an operation where the only parameter in the request body is of type Stream. That means that you can have other parameters to the operation, but they need to be passed via the URI (using the UriTemplate property of the [WebInvoke] attribute) - see more information in the post at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx.
In your example, you'd have something like the code below:
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "RegisterUser?emailId={EmailID}&name={Name}&mobile={Mobile}&IMEI={IMEI}",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat= WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
ResultSet RegisterUser(string EmailID, string Name,Stream profilepic, string Mobile, long IMEI);
And in the client you'd not use JSON, but pass the non-file parameters in the request URI, and the file contents in the request body.
And for your other questions: yes, it would also work for video files (for any arbitrary data, for that matter); and no, you don't need to do anything special for the return type - it should just work.
I am new in android. I want to create a application to read the XML file from an URL and show the image in a grid view using ImageUrl of image.
Thanks for the answer but I am able to read xml file from url but I need if in xml imageUrl is there so show in grid view.
This is my xml file
<?xml version="1.0" encoding="UTF-8"?>
<channels>
<channel>
<name>ndtv</name>
<logo>http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png</logo>
<description>this is a news Channel</description>
<rssfeed>ndtv.com</rssfeed>
</channel>
<channel>
<name>star news</name>
<logo>http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png</logo>
<description>this is a news Channel</description>
<rssfeed>starnews.com</rssfeed>
</channel>
</channels>
Check the following URl to kow about XML parsers
http://www.totheriver.com/learn/xml/xmltutorial.html#6.2
First get the data from url. store in in file. use the folowing code to parse the XML using SAXParser
SAX Parser to parse an XML
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserExample extends DefaultHandler{
List myEmpls;
private String tempVal;
//to maintain context
private Employee tempEmp;
public SAXParserExample(){
myEmpls = new ArrayList();
}
public void runExample() {
parseDocument();
printData();
}
private void parseDocument() {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
sp.parse("employees.xml", this);
}catch(SAXException se) {
se.printStackTrace();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch (IOException ie) {
ie.printStackTrace();
}
}
/**
* Iterate through the list and print
* the contents
*/
private void printData(){
System.out.println("No of Employees '" + myEmpls.size() + "'.");
Iterator it = myEmpls.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
//Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//reset
tempVal = "";
if(qName.equalsIgnoreCase("Employee")) {
//create a new instance of employee
tempEmp = new Employee();
tempEmp.setType(attributes.getValue("type"));
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch,start,length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("Employee")) {
//add it to the list
myEmpls.add(tempEmp);
}else if (qName.equalsIgnoreCase("Name")) {
tempEmp.setName(tempVal);
}else if (qName.equalsIgnoreCase("Id")) {
tempEmp.setId(Integer.parseInt(tempVal));
}else if (qName.equalsIgnoreCase("Age")) {
tempEmp.setAge(Integer.parseInt(tempVal));
}
}
public static void main(String[] args){
SAXParserExample spe = new SAXParserExample();
spe.runExample();
}
}
Working with XML on Android
Grid View example