I'm trying to make an api rest call as following:
InputSource is = new InputSource("http://api.eventful.com/rest/events/search?app_key=5mnzXGn4S4WsNxKS&keywords=books&location=paris&date=Future");
is.setEncoding("ISO-8859-1");
ParseurEvent parseur = new ParseurEvent(is);
my event parser:
List<Event> eventList;
InputSource bookXmlFileName;
String tmpValue;
Event eventTmp;
//SimpleDateFormat sdf= new SimpleDateFormat("yy-MM-dd");
//Constructor
public ParseurEvent(InputSource bookXmlFileName) {
this.bookXmlFileName = bookXmlFileName;
eventList = new ArrayList<Event>();
parseDocument();
printDatas();
}
private void parseDocument() {
// parse
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
parser.parse(bookXmlFileName, this);
} catch (ParserConfigurationException e) {
Log.e("myParserConfigurationException", "ParserConfig error");
} catch (SAXException e) {
Log.e("mySAXException", "SAXException : xml not well formed");
} catch (IOException e) {
Log.e("myIOException", e.getMessage());
}
}
public List<Event> printDatas() {
for (Event event : eventList) {
Log.i("Event", event.getTitle());
}
return eventList;
}
#Override
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
if (elementName.equalsIgnoreCase("event")) {
eventTmp = new Event();
eventTmp.setId(attributes.getValue("id"));
}
}
#Override
public void endElement(String s, String s1, String element) throws SAXException {
// if end of book element add to list
if (element.equals("event")) {
eventList.add(eventTmp);
}
if (element.equalsIgnoreCase("title")) {
eventTmp.setTitle(tmpValue);
}
if (element.equalsIgnoreCase("url")) {
eventTmp.setUrl(tmpValue);
}
if (element.equalsIgnoreCase("description")) {
eventTmp.setDescription(tmpValue);
}
if(element.equalsIgnoreCase("start_time")){
eventTmp.setStart_time(tmpValue);
}
}
#Override
public void characters(char[] ac, int i, int j) throws SAXException {
tmpValue = new String(ac, i, j);
}
}
I get this exception:
Couldn't open http://api.eventful.com/rest/events/search?app_key=5mnzXGn4S4WsNxKS&keywords=books&location=paris&date=Future
Any network operation should be done in an AsyncTask. And url.openStream should be helpful in this case.
class ParseTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... n) {
try {
URL url = new URL("http://api.eventful.com/rest/events/search?app_key=5mnzXGn4S4WsNxKS&keywords=books&location=paris&date=Future");
InputStream is = url.openStream();
is.setEncoding("ISO-8859-1");
ParseurEvent parseur = new ParseurEvent(is);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
You can call this task as:
new ParseTask().execute();
Related
since I'm still kinda just starting out on more advanced android development I wanna learn more about APIs and how to fetch JSON data into a ListView.
Let's say I want to be able to search for an actor and in return get all the movies he's been involved with displaying in a listview. I've been glancing at retrofit, but not sure if it does the job I'm looking for.
I'll take any info regarding this matter. Links, snippets, you name it.
Step 1: create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<ListView
android:id="#+id/actorslist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:color="#ffffff"
android:divider="#null"
android:scrollbars="none"
/>
</RelativeLayout>
Step 2: create your RequestSenderFiles
-first create one interface AsyncResponse.java
public interface AsyncResponse
{
void processFinish(Object output) throws JSONException;
}
-Now Create Another File RequestResponse.java
public class RequestResponse extends AsyncTask<String ,String,String>
{
Activity c;
public AsyncResponse delegate = null;
String req="";
HashMap<String,String> params;
boolean connect=true;
int responseCode;
String url;
ProgressDialog Loader;
public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod)
{
delegate = AsyncResponse;
c=context;
req=RequestMethod;
}
public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod, HashMap<String, String> postparam)
{
delegate = AsyncResponse;
c=context;
req=RequestMethod;
params=postparam;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
// your progressdialog your here
Loader=new ProgressDialog(c);
Loader.setMessage("Loading...");
Loader.show();
}
#Override
protected String doInBackground(String... params)
{
String json="";
Log.i("REposnse",""+params[0]);
url=params[0];
if(req.equals("GET"))
{
json=Client(params[0]);
}
else
{
json=ClientPost(params[0]);
}
Log.i("REposnse", "" + json);
return json;
}
#Override
protected void onPostExecute(String av)
{
super.onPostExecute(av);
if(connect)
{
try
{
delegate.processFinish(av);
}
catch (JSONException e)
{
e.printStackTrace();
}
try
{
if ((this.Loader != null) && this.Loader.isShowing())
{
this.Loader.dismiss();
}
}
catch (final IllegalArgumentException e)
{
// Handle or log or ignore
}
catch (final Exception e)
{
// Handle or log or ignore
}
finally
{
this.Loader = null;
}
}
else
{
try
{
if ((this.Loader != null) && this.Loader.isShowing())
{
this.Loader.dismiss();
}
}
catch (final IllegalArgumentException e)
{
// Handle or log or ignore
}
catch (final Exception e)
{
// Handle or log or ignore
}
finally
{
this.Loader = null;
}
c.runOnUiThread(new Runnable()
{
public void run()
{
if(req.equals("GET"))
{
RequestResponse requestget= RequestResponse(delegate, c);
requestget.execute(url);
}
else
{
RequestResponse requestpost = new RequestResponse(delegate, c, req, params);
requestpost.execute(url);
}
}
});
}
}
public String ClientPost(String url)
{
URL url1;
String response = "";
try
{
url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setReadTimeout(1500000);
conn.setConnectTimeout(1500000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
responseCode=conn.getResponseCode();
Log.i("REposnse",""+responseCode);
if(responseCode == HttpsURLConnection.HTTP_OK)
{
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null)
{
response+=line;
}
}
else
{
connect=false;
response="";
}
}
catch (Exception e)
{
connect=false;
}
return response;
}
public String Client(String url)
{
String result = "";
try
{
URL apiurl =null;
HttpURLConnection conn;
String line;
BufferedReader rd;
apiurl = new URL(url);
conn = (HttpURLConnection) apiurl.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(1500000);
conn.setConnectTimeout(1500000);
responseCode=conn.getResponseCode();
Log.i("REposnse",""+responseCode);
if(responseCode==HttpsURLConnection.HTTP_OK)
{
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
result += line;
}
rd.close();
}
else
{
connect=false;
}
}
catch (Exception e)
{
connect=false;
}
return result;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet())
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
Log.i("REposnse",""+params);
return result.toString();
}
}
Step 3: create Activity MainActivity.java
public class MainActivity extends Activity
{
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState)
{
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main.xml);
list = (ListView) findViewById(R.id.actorslist);
request();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void request()
{
// for POST Request
//suppose you need to send some data to server to fetch the response from server
HashMap<String,String> data=new HashMap<String,String>();
data.put("id","12");
try
{
RequestResponse crr = new RequestResponse(new AsyncResponse()
{
#Override
public void processFinish(Object output) throws JSONException
{
output.toString();//your response
// for example you got the response like this
String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}";
fetchandapplydata(actors);
}
}, this,"POST",data);
crr.execute(yourserversideurltofetchdata);
}
catch (Exception e)
{
e.printStacktrace();
}
// for GET Request
try
{
RequestResponse crr = new RequestResponse(new AsyncResponse()
{
#Override
public void processFinish(Object output) throws JSONException
{
output.toString();//your response
// for example you got the response like this
String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}";
fetchandapplydata(actors);
}
}, this,"GET");
crr.execute(yourserversideurltofetchdata);
}
catch (Exception e)
{
e.printStacktrace();
}
//Depend upon the request method use the code and comment the rest code.
}
public void fetchandapplydata(String data)
{
JSONObject object=new JSONObject(data);
JSONArray actors=object.getJSONArray("data");
ArrayList<HashMap<String,String>> actorsdata=new ArrayList<HashMap<String, String>>();
for(int i=0;i<actors.length();i++)
{
JSONObject actor=actors.getJSONObject(i);
HashMap<String,String> actorsnames=new HashMap<String,String>();
actorsnames.put("name",actor.getString("actorname"));
actorsdata.add(actorsnames);
}
ActorAdapter actoradapter = new ActorAdapter(this, actorsdata);
list.setAdapter(actoradapter);
}
}
Step 4: Create ActorAdapter.java
public class ActorAdapter extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
private Activity activity;
public ActorAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
data=d;
inflater = (LayoutInflater)Ced_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return data.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
try
{
View vi;
vi = inflater.inflate(R.layout.actor_item, null);
TextView name= (TextView) vi.findViewById(R.id.name);
HashMap<String, String> actor = new HashMap<String, String>();
actor = data.get(position);
name.setText(actor.get("name"));
return vi;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
Step 5 : create actor_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main">
<TextView
android:layout_width="wrap_parent"
android:layout_height="wrap_parent"
android:id="#+id/name" />
</RelativeLayout>
This is step by step process for your question , still if you have any doubt feel free to ask us.
I am new to Stackoverflow.
I am trying to make a Unit Converter in which the function "calculateCurrency" returns a Double value of the result. But the value of TextView "outputNumber" is always changing based on the previous input.
Ex- If I type 1, then the outputNumber is changed to "null" but when I enter another digit after 1, then the outputNumber changes to the value it was supposed to be changed on 1. But the Toast is displaying the correct value i.e. on 1, it is displaying 1 so the value of myInputNumber is correct according to the input.
Can anyone help me?
inputNumber.addTextChangedListener(
new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
try {
myInputNumber = Double.parseDouble(s.toString());
Double myText = calculations.calculateCurrency(myInputNumber, convertFrom, convertTo);
Toast.makeText(MainActivity.this, myInputNumber+"", Toast.LENGTH_SHORT).show();
outputNumber.setText(myText+"");
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}
);
The code of calculations.calculateCurrency is:
public Double calculateCurrency(Double input, String convertFrom, String convertTo) throws ExecutionException, InterruptedException {
myCurrencyFetcher fetchCurrency = new myCurrencyFetcher();
fetchCurrency.execute(Double.toString(input), convertFrom, convertTo);
return myText;
}
class myCurrencyFetcher extends AsyncTask<String, Double, Double>{
URL url;
StringBuffer stringBuffer;
#Override
protected Double doInBackground(String... params) {
try{
Double myInputNumber = Double.parseDouble(params[0]);
String convertFrom = params[1];
String convertTo = params[2];
url = new URL("http://api.fixer.io/latest?base="+convertFrom+"&symbols="+convertTo);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
stringBuffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
stringBuffer.append(line);
}
String finalJSON = stringBuffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONObject finalObject = parentObject.getJSONObject("rates");
String rate = finalObject.getString(convertTo);
//String year = finalObject.getString("year");
Double myRate = Double.parseDouble(rate);
return myInputNumber*myRate;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Double result) {
super.onPostExecute(result);
Calculations.myText = result;
}
}
You have to change your code.
#Override
public void afterTextChanged(Editable s) {
try {
myInputNumber = Double.parseDouble(s.toString());
Double myText = calculations.calculateCurrency(myInputNumber, convertFrom, convertTo);
Toast.makeText(MainActivity.this, myInputNumber+"", Toast.LENGTH_SHORT).show();
//outputNumber.setText(myText+""); // Remove this line
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
Add TextView (outputNumber) to Constructor as argument.
myCurrencyFetcher fetchCurrency = new myCurrencyFetcher(outputNumber);
class myCurrencyFetcher extends AsyncTask<String, Double, Double>{
private WeakReference<TextView> weakOutputNumber;
public myCurrencyFetcher (TextView outputNumber) {
weakOutputNumber= new WeakReference<TextView>(outputNumber);
}
/* ... Other methods are the same */
#Override
protected void onPostExecute(Double result) {
super.onPostExecute(result);
//Calculations.myText = result;
if (weakOutputNumber != null) {
TextView outputNumber = weakOutputNumber.get();
if (outputNumber != null) {
outputNumber.setText(new String(result));
}
}
}
}
Try again add synchronized at method calculations.calculateCurrency(myInputNumber, convertFrom, convertTo);
i want to make rss reader app.
i want to get rss first then pass it into another activity use intent.
here is my codes:
mainActivity.java
public class mainActivity extends Activity {
new AsyncTaskParseJson().execute();
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
RssParser parser = new RssParser("https://test/feed/");
Bundle extra = new Bundle();
extra.putSerializable("objects", parser);
Intent intent = new Intent(this, b.class);
intent.putExtra("extra", extra);
startActivity(intent);
}
}
RssParser.java
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssParser extends DefaultHandler implements Serializable {
private StringBuilder content;
private boolean inChannel;
private boolean inImage;
private boolean inItem;
private ArrayList<Item> items = new ArrayList<Item>();
private Channel channel = new Channel();
private Item lastItem;
public RssParser(String url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(url);
xr.setContentHandler(this);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public class Item {
public String title;
public String description;
public String link;
public String category;
public String pubDate;
public String guid;
public String imageUrl;
public String creator;
}
public class Channel {
public String title;
public String description;
public String link;
public String lastBuildDate;
public String generator;
public String imageUrl;
public String imageTitle;
public String imageLink;
public String imageWidth;
public String imageHeight;
public String imageDescription;
public String language;
public String copyright;
public String pubDate;
public String category;
public String ttl;
}
#Override
public void startDocument() throws SAXException {
// Log.i("LOG", "StartDocument");
}
#Override
public void endDocument() throws SAXException {
// Log.i("LOG", "EndDocument");
}
#Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = true;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = true;
}
if (localName.equalsIgnoreCase("item")) {
lastItem = new Item();
items.add(lastItem);
inItem = true;
}
content = new StringBuilder();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = false;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = false;
}
if (localName.equalsIgnoreCase("item")) {
inItem = false;
}
if (localName.equalsIgnoreCase("title")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.title = content.toString();
} else if (inImage) {
channel.imageTitle = content.toString();
} else if (inChannel) {
channel.title = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("dc:creator") || localName.equalsIgnoreCase("creator")) {
if (content == null) {
return;
}
lastItem.creator = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("description")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.description = android.text.Html.fromHtml(content.toString()).toString().substring(1);
lastItem.imageUrl = this.extractImageUrl(content.toString());
} else if (inImage) {
channel.imageDescription = content.toString();
} else if (inChannel) {
channel.description = android.text.Html.fromHtml(content.toString()).toString().substring(1);
}
content = null;
}
if (localName.equalsIgnoreCase("link")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.link = content.toString();
} else if (inImage) {
channel.imageLink = content.toString();
} else if (inChannel) {
channel.link = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("category")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.category = content.toString();
} else if (inChannel) {
channel.category = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("pubDate")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.pubDate = content.toString();
} else if (inChannel) {
channel.pubDate = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("guid")) {
if (content == null) {
return;
}
lastItem.guid = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("url")) {
if (content == null) {
return;
}
channel.imageUrl = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("width")) {
if (content == null) {
return;
}
channel.imageWidth = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("height")) {
if (content == null) {
return;
}
channel.imageHeight = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("language")) {
if (content == null) {
return;
}
channel.language = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("copyright")) {
if (content == null) {
return;
}
channel.copyright = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("ttl")) {
if (content == null) {
return;
}
channel.ttl = content.toString();
content = null;
}
}
private String extractImageUrl(String description) {
XmlPullParserFactory factory = null;
try {
factory = XmlPullParserFactory.newInstance();
}
catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
XmlPullParser xpp = null;
try {
xpp = factory.newPullParser();
}
catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
xpp.setInput(new StringReader(description));
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int eventType = 0;
try {
eventType = xpp.getEventType();
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && "img".equals(xpp.getName())) {
//found an image start tag, extract the attribute 'src' from here...
return xpp.getAttributeValue(null, "src").toString();
}
try {
eventType = xpp.next();
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return xpp.getAttributeValue(null, "src").toString();
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (content == null) {
return;
}
content.append(ch, start, length);
}
public Item getItem(int index) {
return items.get(index);
}
public ArrayList<Item> getItems() {
return items;
}
}
second activity that i want to get RssParser Items:
b.java
Bundle extra = getIntent().getBundleExtra("extra");
RssParser p = (RssParser) extra.getSerializable("objects");
ListView listView = (ListView) findViewById(R.id.content_frame);
listView.setAdapter((ListAdapter) p.getItems());
and i always get errors like:
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
java.lang.RuntimeException: Parcel: unable to marshal value
Caused by: java.lang.RuntimeException: Parcelable encountered IOException reading a Serializable object
if any suggestion i really Thankful.
Best Regards
In this case, instead of extending from Serializable, extend from Parcelable.
And, when sending, use:
RssParser parser = new RssParser("https://test/feed/");
Bundle extra = new Bundle();
extra.putParcelable("objects", parser);
Reception of it:
RssParser rssParser = getIntent().getExtras().getParcelable("objects");
Works like that, not precisely the best option, but works.
The error mainly said that was found a Serializable when a Parcelable was received. So, I changed it to Parcelable.
EDIT
gradle:
dependencies {
//...
compile 'com.google.code.gson:gson:2.2.4'
}
Send:
Intent intent = new Intent(MainActivity.this, b.class);
intent.putExtra("extra", new Gson().toJson(parser));
startActivity(intent);
Receive:
String toParse = getIntent().getExtras().getString("extra");
RssParser rssParser = new Gson().fromJson(toParse, RssParser.class);
From the edit, i was tested. It works.
EDIT2
If, you need to pass a Array or List:
Type rssListType = new TypeToken<ArrayList<RssParser>>(){}.getType();
List<RssParser> founderList = new Gson().fromJson(myStringToParse, rssListType);
Regards.
I'm developing an Xml parsing application. The URL is not trusted when it is opened from the browser. There is no way to correct it from server side. So I used "trsut anybody" code.
But still I'm getting a null pointer exception.
Please help me with this.
Thanx in advance
this is my code.
public class SitesList {
/** Variables */
private ArrayList<String> From_Currency = new ArrayList<String>();
private ArrayList<String> To_Currency = new ArrayList<String>();
private ArrayList<String> exrt_buy = new ArrayList<String>();
private ArrayList<String> exrt_sell = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getFrom_Currency() {
return From_Currency;
}
public void setFrom_Currency(String From_Currency) {
this.From_Currency.add(From_Currency);
}
public ArrayList<String> getTo_Currency() {
return To_Currency;
}
public void setTo_Currency(String To_Currency) {
this.To_Currency.add(To_Currency);
}
public ArrayList<String> getexrt_buy() {
return exrt_buy;
}
public void setexrt_buy(String exrt_buy) {
this.exrt_buy.add(exrt_buy);
}
public ArrayList<String> getexrt_sell() {
return exrt_sell;
}
public void setexrt_sell(String exrt_sell) {
this.exrt_sell.add(exrt_sell);
}
}
MyXMLHandler class
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("DOC"))
{
sitesList = new SitesList();
}
/*} else if (localName.equals("website")) {
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}*/
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("From_Currency"))
sitesList.setFrom_Currency(currentValue);
else if (localName.equalsIgnoreCase("To_Currency"))
sitesList.setTo_Currency(currentValue);
else if (localName.equalsIgnoreCase("exrt_buy"))
sitesList.setexrt_buy(currentValue);
else if (localName.equalsIgnoreCase("exrt_sell"))
sitesList.setexrt_sell(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
XMLParsingExample class
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
URL url;
HttpsURLConnection https;
HttpURLConnection conn = null;
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
url = new URL("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
try {
https = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
https.setHostnameVerifier(DO_NOT_VERIFY);
conn = https;
} else {
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView From_Currency[];
TextView To_Currency[];
TextView exrt_buy[];
TextView exrt_sell[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
From_Currency = new TextView[sitesList.getFrom_Currency().size()];
To_Currency = new TextView[sitesList.getTo_Currency().size()];
exrt_buy = new TextView[sitesList.getexrt_buy().size()];
exrt_sell = new TextView[sitesList.getexrt_sell().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getFrom_Currency().size(); i++) {
From_Currency[i] = new TextView(this);
From_Currency[i].setText("Name = "+sitesList.getFrom_Currency().get(i));
To_Currency[i] = new TextView(this);
To_Currency[i].setText("Website = "+sitesList.getTo_Currency().get(i));
exrt_buy[i] = new TextView(this);
exrt_buy[i].setText("Website Category = "+sitesList.getexrt_buy().get(i));
exrt_sell[i] = new TextView(this);
exrt_sell[i].setText("Website Category = "+sitesList.getexrt_sell().get(i));
layout.addView(From_Currency[i]);
layout.addView(To_Currency[i]);
layout.addView(exrt_buy[i]);
layout.addView(exrt_sell[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
private void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to use the API for our billing system in an Android Application, but I am having trouble figuring out how to parse the XML that it returns. Here is what my function looks like thus far...
public void ParseData(String xmlData)
{
try
{
// Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
// Input Stream
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlData));
// Parse Document into a NodeList
Document doc = db.parse(inStream);
NodeList nodes = doc.getElementsByTagName("ticket");
// Loop NodeList and Retrieve Element Data
for(int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
if (node instanceof Element)
{
Element child = (Element)node;
String id = child.getAttribute("id");
}
}
}
catch(SAXException e)
{
}
}
and here is what the XML data looks like that is returned. I need to loop through each and pull each element out, but I cant figure out how to do that with the DOM parser.
<whmcsapi>
<action>gettickets</action>
<result>success</result>
<totalresults>1</totalresults>
<startnumber>0</startnumber>
<numreturned>1</numreturned>
<tickets>
<ticket>
<id>1</id>
<tid>557168</tid>
<deptid>1</deptid>
<userid>1</userid>
<name><![CDATA[Array]]></name>
<email></email>
<cc></cc>
<c>TmDEga5v</c>
<date>2009-08-03 23:14:32</date>
<subject><![CDATA[Test Ticket]]></subject>
<message><![CDATA[This is a test ticket>
----------------------------
IP Address: xxx.xxx.xxx.xxx]]></message>
<status>Open</status>
<priority>Medium</priority>
<admin></admin>
<attachment></attachment>
<lastreply>2009-08-04 12:14:18</lastreply>
<flag>0</flag>
<service></service>
</ticket>
</tickets>
</whmcsapi>
Yes SAX parser is the solution and here is the basic code to get you started:
void parseExampleFunction(){
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
File myFile = new File( //the XML file which you need to parse );
myFile.createNewFile();
FileInputStream fOut = new FileInputStream(myFile);
BufferedInputStream bos = new BufferedInputStream( fOut );
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MessagesXMLHandler myXMLHandler = new MessagesXMLHandler(context);
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(bos));
}
// the class where the parsing logic needs to defined.This preferably can be in a different .java file
public class MessagesXMLHandler extends DefaultHandler{
//this function is called automatically when a start tag is encountered
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
//variable localName is the name of the tag
//this function is called autiomatically when an end tag is encountered
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
}
//this function gets called to return the value stored betweeen the closing and opening tags
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
//now variable value has the value stored between the closing and opening tags
String value=new String(ch,start,length);
}
}
for parse xml on android best way is to use SAXParser. i explained it bellow with demo....
first of all create your activity class like as bellw.
public class ActivityForSax extends ListActivity {
private ProgressDialog pDialog;
private ItemXMLHandler myXMLHandler;
private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
private TextView textview;
private ListView mListView;
private ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_dom);
textview = (TextView)findViewById(R.id.textView1);
doParsing();
mListView = getListView();
}
public void doParsing(){
if (isNetworkAvailable()) {
textview.setText("Loading...Please wait...");
new AsyncData().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}
class AsyncData extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
menuItems = new ArrayList<HashMap<String, String>>();
pDialog = new ProgressDialog(ActivityForSax.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new ItemXMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));
} catch (ParserConfigurationException pce) {
Log.e("SAX XML", "sax parse error", pce);
} catch (SAXException se) {
Log.e("SAX XML", "sax error", se);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
textview.setText("Done!!!");
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayList<Bean> itemsList = myXMLHandler.getItemsList();
for (int i = 0; i < itemsList.size(); i++) {
Bean objBean = itemsList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("TITLE :: ", objBean.getTitle());
map.put("DESC :: ", objBean.getDesc());
map.put("PUBDATE :: ", objBean.getPubDate());
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(ActivityForSax.this, menuItems,
R.layout.list_item,
new String[] { "TITLE :: ", "DESC :: ", "PUBDATE :: " }, new int[] {
R.id.name, R.id.email, R.id.mobile });
mListView.setAdapter(adapter);
}
}
public void showToast(String msg) {
Toast.makeText(ActivityForSax.this, msg, Toast.LENGTH_LONG).show();
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
now you need to create default handler class for parsing xml data.
public class ItemXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = "";
Bean item = null;
private ArrayList<Bean> itemsList = new ArrayList<Bean>();
public ArrayList<Bean> getItemsList() {
return itemsList;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if (localName.equals("item")) {
item = new Bean();
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equals("id")) {
item.setId(currentValue);
} else if (localName.equals("title")) {
item.setTitle(currentValue);
} else if (localName.equals("desc")) {
item.setDesc(currentValue);
} else if (localName.equals("pubDate")) {
item.setPubDate(currentValue);
} else if (localName.equals("link")) {
item.setLink(currentValue);
} else if (localName.equals("item")) {
itemsList.add(item);
}
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
}
and finally your Bean class like as...
public class Bean {
private String id;
private String title;
private String desc;
private String pubDate;
private String link;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
Add java-json.jar in library folder
Compile files ('libs/java-json.jar') //add this line into your build
Here is the code to convert xml response to json response:
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}