How do I add an AsyncTask to this? - java

I am creating a Android app and I am fairly new to threading in general I have two different methods that I use to call two different webservices as shown below, so how do I change these to use the AsyncTask to run on a background thread?
My Code:
public List<String> getEvacRouteNames(){
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
BufferedReader in = null;
String page;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(URI)
//Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field
List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(0);
request.setEntity(new UrlEncodedFormEntity(nameValPairs));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(page)));
// normalize the document
doc.getDocumentElement().normalize();
// get the root node
NodeList nodeList = doc.getElementsByTagName("string");
// the node has three child nodes
for (int n = 0; n < nodeList.getLength(); n++) {
Node node=nodeList.item(n);
String upperNode = node.getNodeName();
Node temp=node.getChildNodes().item(n);
if (upperNode.equals("string")){
String routeName = node.getTextContent();
routeNamesList.add(node.getTextContent());
}
}
//System.out.println(page);
} catch (Exception E) {
E.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return routeNamesList;
}
public EvacRoute getEvacuationRoute(String routeName, LatLng currentLocation, String lat, String lon) throws URISyntaxException, ClientProtocolException, IOException, ParserConfigurationException, SAXException{
evacRouteList = new ArrayList<EvacRoute>();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
EvacRoute evacRoute = new EvacRoute();
evacRoute.setDestinationName(routeName);
BufferedReader in = null;
String page;
latslngsList = new ArrayList<LatLng>();
try {
latslngsList.add(currentLocation);
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(URI)
//Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field
List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(2);
nameValPairs.add(new BasicNameValuePair("Route_Name", routeName));
nameValPairs.add(new BasicNameValuePair("In_Lat", lat));
nameValPairs.add(new BasicNameValuePair("In_Lon", lon));
request.setEntity(new UrlEncodedFormEntity(nameValPairs));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(page)));
// normalize the document
doc.getDocumentElement().normalize();
// get the root node
NodeList nodeList = doc.getElementsByTagName("simple_ll_waypoint");
double latitude = 0;
double longitude= 0;
// the node has three child nodes
for (int n = 0; n < nodeList.getLength(); n++) {
String latString = "";
String longString = "";
Node node=nodeList.item(n);
String upperNode = node.getNodeName();
StringBuilder addressStrBlder = new StringBuilder();
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
Node temp=node.getChildNodes().item(i);
String nodeName = temp.getNodeName();
String nodevalue = temp.getNodeValue();
if(temp.getNodeName().equalsIgnoreCase("Lat")){
latString = temp.getTextContent();
latitude = Double.parseDouble(latString);
} else if(temp.getNodeName().equalsIgnoreCase("Lon")){
longString = temp.getTextContent();
longitude = Double.parseDouble(longString);
LatLng latlng = new LatLng(latitude, longitude);
latslngsList.add(latlng);
}
}
//Log.e("Fuel Stop", fuelStop.toString());
}
//System.out.println(page);
} catch (Exception E) {
E.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
evacRoute.setLatLngList(latslngsList);
evacRouteList.add(evacRoute);
return evacRoute;
}

You can extend your class from AsyncTask and do like this:
public class AsyncCustomTask extends AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... params) {
return getEvacRouteNames();
}
#Override
protected void onPostExecute(List<String> result) {
// Function finished and value has returned.
}
}
And to call it:
new AsyncCustomTask().execute();
Updated for second question
For the method that have parameters, you can use constructor of your class like:
public class AsyncSecondCustomTask extends AsyncTask<Void, Void, EvacRoute> {
private final String routeName;
private final LatLng currentLocation;
private final String lat;
private final String lon;
public AsyncSecondCustomTask(String routeName, LatLng currentLocation, String lat, String lon) {
this.routeName = routeName;
this.currentLocation = currentLocation;
this.lat = lat;
this.lon = lon;
}
#Override
protected EvacRoute doInBackground(Void... params) {
return getEvacuationRoute(routeName, currentLocation, lat, lon);
}
#Override
protected void onPostExecute(EvacRoute result) {
// Function finished and value has returned.
}
}
And you can call it like:
new AsyncSecondCustomTask("", null, "", "").execute();

Related

NullPointerException while invoking method getInputParameters()

I am doing Parameterized Java Mapping in SAP PI 7.5 with following parameters bound by the tag names specified in the Operation Mapping
(BS_NAME,CHANNEL_NAME,EMAIL).
On testing the below java mapping in the test tab of OM using the payload, it gives the following error:
NullPointerException while trying to invoke the method com.sap.aii.mapping.api.TransformationInput.getInputParameters() of a null object loaded from field of an object loaded from local variable "this**"
I debugged the code but didn't found the issue, any suggestions?
Please find below Java code for XmlNFe_To_Mail Class. BodyText Class is also used to fetch some content. The error is encountered in the XmlNFe_To_Mail Class.
public class XmlNFe_To_Mail extends AbstractTransformation {
private String prefixoSubject = new String();
private String emailFrom = new String();
private String prefixoDocumento = new String();
private String frase = new String();
private String gap = "\n\r";
private AbstractTrace trace = null;
private Map map = null;
private String BSSystem = "";
private String ComChannel = "";
private String Emails = "";
private final String NFE_EMPRESA = "NFE Company: ";
private final String NFe = "NFE";
private final String NFe_Mail = "nfe#company.com";
TransformationInput input = null;
TransformationOutput output = null;
public void execute(InputStream in , OutputStream out) throws StreamTransformationException {
// TODO Auto-generated method stub
{
BSSystem = input.getInputParameters().getString("BS_NAME");
ComChannel = input.getInputParameters().getString("CHANNEL_NAME");
Emails = input.getInputParameters().getString("EMAIL");
try {
configParamEmail();
BufferedReader inpxml = new BufferedReader(new InputStreamReader( in ));
StringBuffer buffer = new StringBuffer();
String line = "";
String quebra = System.getProperty("line.separator");
while ((line = inpxml.readLine()) != null) {
line.replaceAll("\r\n", "");
line.replaceAll(quebra, "");
line.replaceAll(" />", "/>");
line.replaceAll(" />", "/>");
line.replaceAll(" />", "/>");
buffer.append(line);
}
String inptxml = buffer.toString();
inptxml = inptxml.replace("\r\n", "");
inptxml = inptxml.replaceAll(quebra, "");
inptxml = inptxml.replaceAll(" />", "/>");
inptxml = inptxml.replaceAll(" />", "/>");
inptxml = inptxml.replaceAll(" />", "/>");
String idNFe = "";
String numeroNF = "";
String idEvent = "";
idNFe = inptxml.substring(inptxml.indexOf("<chNFe>") + 7, inptxml.indexOf("</chNFe>"));
numeroNF = idNFe.substring(25, 34);
if (inptxml.indexOf("infEvento") > 0) {
idEvent = inptxml.substring(inptxml.indexOf("<tpEvento>") + 10, inptxml.indexOf("</tpEvento>"));
if (idEvent.length() > 0) {
if (idEvent.equals("111111")) {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CancNFe"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "NFE CANCELADA"));
} else if (idEvent.equals("100000")) {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CCE"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "CCE"));
} else {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "ManDest"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "MANIFESTO"));
}
}
}
Channel chn = null;
RfcAccessor rfc = null;
String email = "";
String pdf = "";
chn = LookupService.getChannel(getBSystem(), getCChannel());
rfc = LookupService.getRfcAccessor(chn);
String req = "<ns0:TEST_NFE_MAIL_OPT xmlns:ns0='urn:sap-com:document:sap:rfc:functions'><I_ACCESS_KEY>" +
idNFe + "<I_ACCESS_KEY></ns0:ZOTC_NFE_EMAIL_OUTPUT>";
InputStream inputRFC = new ByteArrayInputStream(req.getBytes("UTF-8"));
XmlPayload rfcPayload = LookupService.getXmlPayload(inputRFC);
XmlPayload result = rfc.call(rfcPayload);
InputStream resp = result.getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(resp);
Node node = (Node) doc.getElementsByTagName("E_EMAIL").item(0);
if (node.hasChildNodes() && !node.getFirstChild().getNodeValue().equals("")) {
email = node.getFirstChild().getNodeValue();
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transform = tf.newTransformer();
Document docout = db.newDocument();
Element root = docout.createElement("ns0:Mail");
root.setAttribute("xmlns:ns0", "http://sap.com/xi/XI/Mail/30");
docout.appendChild(root);
Element subject = docout.createElement("Subject");
root.appendChild(subject);
Text subjectText = docout.createTextNode(getPrefixoSubject() + numeroNF);
subject.appendChild(subjectText);
Element from = docout.createElement("From");
root.appendChild(from);
Text fromText = docout.createTextNode(getEmailFrom());
from.appendChild(fromText);
if (email.length() > 0) {
email += ";";
} else {
email = this.getEmaillist();
}
Element to = docout.createElement("To");
root.appendChild(to);
Text toText = docout.createTextNode(email);
to.appendChild(toText);
Element contentType = docout.createElement("Content_Type");
root.appendChild(contentType);
Text contentTypeText = docout.createTextNode("multipart/mixed;boundary=--AaZz");
contentType.appendChild(contentTypeText);
BodyText texto = new BodyText(idNFe, getFrase(), inptxml, pdf);
Element content = docout.createElement("Content");
root.appendChild(content);
Text contentText = null;
if ("NFE Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getnfeText());
} else if ("NFE CANCELADA Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getCnfeText());
} else if ("CCE Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getcceText());
}
content.appendChild(contentText);
DOMSource domS = new DOMSource(docout);
transform.transform((domS), new StreamResult(out));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// Exception Handling }
}
}
}
public String getGap() {
return gap;
}
public void setGap(String gap) {
this.gap = gap;
}
public String getFrase() {
return frase;
}
public void setFrase(String frase) {
this.frase = frase;
}
public String getBSystem() {
return BSSystem;
}
public String getEmaillist() {
return Emails;
}
public String getCChannel() {
return ComChannel;
}
public String getPrefixoSubject() {
return prefixoSubject;
}
public void setPrefixoSubject(String prefixoSubject) {
this.prefixoSubject = prefixoSubject;
}
public String getEmailFrom() {
return emailFrom;
}
public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
}
public String getPrefixoDocumento() {
return prefixoDocumento;
}
public void setPrefixoDocumento(String prefixoDocumento) {
this.prefixoDocumento = prefixoDocumento;
}
private void configParamEmail() {
setEmailFrom(NFe_Mail);
setPrefixoDocumento(NFe);
setPrefixoSubject(NFE_EMPRESA);
}
#Override
public void transform(TransformationInput in , TransformationOutput out) throws StreamTransformationException {
this.execute( in .getInputPayload().getInputStream(), out.getOutputPayload().getOutputStream());
}
/*public void setParameter(Map arg0) {
// TODO Auto-generated method stub
}*/
}
Kindly let me know what changes should be done.
Thanks.
It's missing instance from the TransformationInput/TransformationOutput classes because their variables are null,
TransformationInput input = null;
TransformationOutput output = null;
So you need to instance them or pass them as reference on some setter.

FileNotFoundException in collection of tweets from Twitter - Java

I have an algorithm that search old tweets in Twitter between two dates. My objective is to return all tweets. But I am getting an exception.
Code:
public static List<Tweet> getTweets(String username, String since, String until, String querySearch) {
List<Tweet> results = new ArrayList<Tweet>();
try {
String refreshCursor = null;
while (true) {
String response = getURLResponse(username, since, until, querySearch, refreshCursor);
System.out.println(response);
JSONObject json = new JSONObject(response);
refreshCursor = json.getString("min_position");
Document doc = Jsoup.parse((String) json.get("items_html"));
Elements tweets = doc.select("div.js-stream-tweet");
if (tweets.size() == 0) {
break;
}
for (Element tweet : tweets) {
String usernameTweet = tweet.select("span.username.js-action-profile-name b").text();
String txt = tweet.select("p.js-tweet-text").text().replaceAll("[^\\u0000-\\uFFFF]", "");
int retweets = Integer.valueOf(tweet.select("span.ProfileTweet-action--retweet span.ProfileTweet-actionCount").attr("data-tweet-stat-count").replaceAll(",", ""));
int favorites = Integer.valueOf(tweet.select("span.ProfileTweet-action--favorite span.ProfileTweet-actionCount").attr("data-tweet-stat-count").replaceAll(",", ""));
long dateMs = Long.valueOf(tweet.select("small.time span.js-short-timestamp").attr("data-time-ms"));
Date date = new Date(dateMs);
Tweet t = new Tweet(usernameTweet, txt, date, retweets, favorites);
results.add(t);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return results;
}
Method that makes the page request:
private static String getURLResponse(String from, String since, String until, String querySearch, String scrollCursor) throws Exception {
String appendQuery = "";
if (from != null) {
appendQuery += "from:"+from;
}
if (since != null) {
appendQuery += " since:"+since;
}
if (until != null) {
appendQuery += " until:"+until;
}
if (querySearch != null) {
appendQuery += " "+querySearch;
}
String url = String.format("https://twitter.com/i/search/timeline?f=realtime&q=%s&src=typd&max_position=%s", URLEncoder.encode(appendQuery, "UTF-8"), scrollCursor);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
Exception:
java.io.FileNotFoundException: https://twitter.com/i/search/timeline?f=realtime&q=+since%3A2014-10-08+until%3A2014-10-10+dilma&src=typd&max_position=TWEET-520341224046469121-520363066366496768-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at Manager.TweetManager.getURLResponse(TweetManager.java:58)
at Manager.TweetManager.getTweets(TweetManager.java:121)
at Main.Main.main(Main.java:54)
JSON downloaded: JSON

Array and Object JSON from URL Parsing

I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..
here my MainActivity.java
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;
// panggil class parser
JSONparser parser = new JSONparser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getJSONArray(TAG_ID);
page = json.getJSONArray(TAG_page);
pages = json.getJSONArray(TAG_total_pages);
tot_result = json.getJSONArray(TAG_total_results);
for (int i = 0; i < results.length(); i++) {
JSONObject data = results.getJSONObject(i);
String backdrop = data.getString(TAG_backdrop_path);
String idd = data.getString(TAG_id).toString();
String ori = data.getString(TAG_original_title);
String releas = data.getString(TAG_release_date);
String poster = data.getString(TAG_poster_path);
String title = data.getString(TAG_title);
String average = data.getString(TAG_vote_average);
String count = data.getString(TAG_vote_count);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_backdrop_path, backdrop);
map.put(TAG_ID, idd);
map.put(TAG_original_title, ori);
map.put(TAG_release_date, releas);
map.put(TAG_poster_path, poster);
map.put(TAG_title, title);
map.put(TAG_vote_average, average);
map.put(TAG_vote_count, count);
genreList.add(map);
}
// Sort by
/*********************************
* Collections.sort(genreList, new Comparator<HashMap<String,
* String>>() {
*
* #Override public int compare(HashMap<String, String> a,
* HashMap<String, String> b) { return
* a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
******************************/
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
// tampilkan ke listadapter
ListAdapter adapter = new SimpleAdapter(this, genreList,
R.layout.list_data, new String[] { TAG_ID, TAG_page,
TAG_results, TAG_backdrop_path, TAG_id,
TAG_original_title, TAG_release_date, TAG_poster_path,
TAG_title, TAG_vote_average, TAG_vote_count,
TAG_total_pages, TAG_total_results }, new int[] {
R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
R.id.idd, R.id.original_title, R.id.release_date,
R.id.poster_path, R.id.title, R.id.vote_average,
R.id.vote_count, R.id.total_pages, R.id.total_results });
setListAdapter(adapter);
}
}
here my JSONparser.java
public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONparser() {
}
public JSONObject getJSONFromUrl(String url) {
// http request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("BUffer Error", "Error converting result" + e.toString());
}
// try parse string to a json
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO: handle exception
Log.e("Json parser", "error parsing data" + e.toString());
}
return jObj;
}
}
here my json data.
{
"id": 18,
"page": 1,
"results": [
{
"backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
"id": 238,
"original_title": "The Godfather",
"release_date": "1972-03-24",
"poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
"title": "The Godfather",
"vote_average": 9.1999999999999993,
"vote_count": 125
},
{
"backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
"id": 857,
"original_title": "Saving Private Ryan",
"release_date": "1998-07-24",
"poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
"title": "Saving Private Ryan",
"vote_average": 8.9000000000000004,
"vote_count": 83
}
],
"total_pages": 25,
"total_results": 499
}
JSONObject jObject_Main= new JSONObject(jsonstring);
//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");
//get json Array and parse it.
JSONArray jsonArray = jObject_Main
.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");
}
i hope its useful to you.
please change this in your code:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString("id");
page = json.getString("page");
tot_result = json.getJSONArray(results);
i hope you understand it.
Try this..
In your Global:
JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;
Inside Try Catch:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString(TAG_ID); // Changes here
page = json.getString(TAG_page); // Changes here
pages = json.getString(TAG_total_pages); // Changes here
tot_result = json.getString(TAG_total_results); // Changes here
results = json.getJSONArray(TAG_results); // Add this line
for (int i = 0; i < results.length(); i++) {
// Remaining all correct
}
EDIT:
new DownloadImageTask()
.execute("your image url");
}
and DownloadImageTask.class
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}
Your JSON is JSONObject and it contains JSONArray
Parse Object
Parse Array
Example:
JSONObject jsonObj = new JSONObject(your_json_string);
String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");
JSONArray results = jsonObj.getJSONArray("results");
int len = results.length(); // length or size, I don't remember, you can check it
for (int i = 0; i < len; i++) {
JSONObject obj = results.getJSONObject(i);
String backdropPath = obj.getString("backdrop_path");
// ...
}
you need add " results= json.getJSONArray(TAG_results);" below
"tot_result = json.getJSONArray(TAG_total_results);"

reading XML File from URL in Android

I experimented with several ways of opening an XML file from the link, but all the roads did not do any good.
In order to make sure that parsing XML File is good, I downloaded the file and put it in Asset folder to make parsing all of this good.
We can deduce from this the error in reading from url
URL is http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httppost);
InputStream in=response.getEntity().getContent();
OR
HttpURLConnection con=(HttpURLConnection)url.openConnection();
InputStream in=con.getInputStream();
OR
InputStream in =url.openStream();
please help me
My Problem solved thanx to all for your help.I should use AsyncTask class when i get File from Url
public void xmlReader() {
try {
URL url = new URL("http://feeds.bbci.co.uk/sport/0/football/rss.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
Document document = documentBuilder.parse(new InputSource(url
.openStream()));
nodlist = document.getElementsByTagName("Youritem");
for (int i = 0; i < nodlist.getLength(); i++) {
Element element = (Element) nodlist.item(i);
NodeList nodlistid = element.getElementsByTagName("Id");
Element id = (Element) nodlistid.item(0);
NodeList nodlistBaslik = element.getElementsByTagName("tagname1");
Element baslik = (Element) nodlistBaslik.item(0);
NodeList nodlistDetay = element.getElementsByTagName("tagname2");
Element detay = (Element) nodlistDetay.item(0);
NodeList nodlistKaynak = element.getElementsByTagName("tagname3");
Element lat = (Element) nodlistKaynak.item(0);
NodeList nodelistMedia = element.getElementsByTagName("tagname4");
Element longi = (Element) nodelistMedia.item(0);
NodeList nodelistTur = element.getElementsByTagName("tagname5");
Element tur = (Element) nodelistTur.item(0);
// String resimURL =
// resim.getAttributes().getNamedItem("url").getNodeValue();
NodeList nodelistMedia1 = element.getElementsByTagName("enclosure");
Element picture= (Element) nodelistMedia1.item(0);
String pictureURL = resim.getAttributes().getNamedItem("picturetagname").getNodeValue();
xmltagname1.add(tagname1.getChildNodes().item(0).getNodeValue());
xmltagname2.add(tagname2.getChildNodes().item(0).getNodeValue());
xmltagname3.add(tagname3.getChildNodes().item(0).getNodeValue());
xmltagname4.add(tagname4.getChildNodes().item(0).getNodeValue());
xmltagname5.add(tagname5.getChildNodes().item(0).getNodeValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think this method helps you.. Take it easy
String TextHolder = "", TextHolder2 = "";
public class GetNotePadFileFromServer extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String userId = SharedPrefHelper.getPrefsHelper().getPref(SharedPrefHelper.PREF_USER_ID);
try {
URL url = new URL(baseUrl+"fileName.xml");
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
while ((TextHolder2 = bufferReader.readLine()) != null) {
TextHolder += TextHolder2;
}
bufferReader.close();
} catch (MalformedURLException malformedURLException) {
malformedURLException.printStackTrace();
TextHolder = malformedURLException.toString();
} catch (IOException iOException) {
iOException.printStackTrace();
TextHolder = iOException.toString();
}
return null;
}
#Override
protected void onPostExecute(Void finalTextHolder) {
Document doc = convertStringToXMLDocument( TextHolder );
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(ApiConstant.ApiKeys.SMS_MESSAGE);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Sms sms = new Sms(
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_IDS).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_ADDRESS).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_BODY).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_READ).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_DATE).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_TYPE).item(0).getTextContent(),
false
);
LogClass.e("mysms",""+sms.getAddress());
smsArrayList.add(sms);
}
}
setUi();
progressDialog.dismiss();
super.onPostExecute(finalTextHolder);
}
}
new GetNotePadFileFromServer().execute();

Google Data Api library for Blackberry

I want to get google contacts in my Blackberry Application. Is there any public libraries availabile for blackberry to do this?
I try to use Oauth-SignPost. But the libraies used in it not supported by blackberry.Then I try the following code
public static String requestToken(){
String url = C.REQUEST_URL;
String header = oauth_header(url, HttpProtocolConstants.HTTP_METHOD_GET);
String requestTokenUrl = concatURL(url, header);
HttpConnection httpConn = null;
InputStream input = null;
try{
HttpConnectionFactory factory = new HttpConnectionFactory( requestTokenUrl,
HttpConnectionFactory.TRANSPORT_WIFI |
HttpConnectionFactory.TRANSPORT_WAP2 |
HttpConnectionFactory.TRANSPORT_BIS |
HttpConnectionFactory.TRANSPORT_BES |
HttpConnectionFactory.TRANSPORT_DIRECT_TCP);
httpConn = factory.getNextConnection();
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
input = httpConn.openDataInputStream();
int resp = httpConn.getResponseCode();
if (resp == HttpConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
int ch;
while ( (ch = input.read()) != -1){
buffer.append( (char) ch);
}
String content = buffer.toString();
System.out.println("Response"+content);
}
return "";
} catch (IOException e) {
return "exception";
} catch (NoMoreTransportsException nc) {
return "noConnection";
} finally {
try {
httpConn.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The oauth_header() which create the appending parameters
public static String oauth_header(String url, String method) {
String nonce = nonce();
long timestamp = timestamp();
Hashtable pairs = new Hashtable();
pairs.put(C.OAUTH_CONSUMER_KEY, C.CONSUMER_KEY);
pairs.put(C.OAUTH_NONCE, nonce);
pairs.put(C.OAUTH_SIGNATURE_METHOD, C.SIGNATURE_METHOD);
pairs.put(C.OAUTH_TIMESTAMP, Long.toString(timestamp));
pairs.put(C.OAUTH_SCOPE,C.SCOPE);
pairs.put(C.OAUTH_VERSION, "1.0");
String sig = signature(method, url, pairs);
StringBuffer header_sb = new StringBuffer();
header_sb.append(C.OAUTH_CONSUMER_KEY).append("=").append(C.CONSUMER_KEY).append(",");
header_sb.append(C.OAUTH_NONCE).append("=").append(nonce).append(",");
header_sb.append(C.OAUTH_SIGNATURE).append("=").append(URLUTF8Encoder.encode(sig)).append(",");
header_sb.append(C.OAUTH_SIGNATURE_METHOD).append("=").append(C.SIGNATURE_METHOD).append(",");
header_sb.append(C.OAUTH_TIMESTAMP).append("=").append(Long.toString(timestamp)).append(",");
header_sb.append(C.OAUTH_SCOPE).append("=").append(C.SCOPE);
header_sb.append(C.OAUTH_VERSION).append("=").append("1.0");
return header_sb.toString();
}
Signature() and concatUrl() here
private static String signature(String method, String requestURL, Hashtable pairs) {
StringBuffer sb = new StringBuffer();
String[] keys = new String[pairs.size()];
Enumeration e = pairs.keys();
int i = 0;
while(e.hasMoreElements()) {
String k = (String)e.nextElement();
keys[i++] = k + "=" + URLUTF8Encoder.encode((String)pairs.get(k));
}
Arrays.sort(keys, new Comparator() {
public int compare(Object arg0, Object arg1) {
return ((String)arg0).compareTo((String)arg1);
}
});
for(i = 0; i < keys.length; i++) {
sb.append(keys[i]).append('&');
}
sb.deleteCharAt(sb.length()-1);
String msg = method.toUpperCase() +"&" + URLUTF8Encoder.encode(requestURL) + "&" + URLUTF8Encoder.encode(sb.toString());
System.out.println(msg);
StringBuffer key = new StringBuffer();
if(C.CONSUMER_SECRET != null) key.append(URLUTF8Encoder.encode(C.CONSUMER_SECRET));
key.append('&');
/* if(Const.tokenSecret != null){
key.append(URLUTF8Encoder.encode(Const.tokenSecret));
}*/
try {
return hmacsha1(key.toString(), msg);
} catch (Exception ex) {
return null;
}
}
private static String hmacsha1(String key, String message)
throws CryptoTokenException, CryptoUnsupportedOperationException, IOException {
HMACKey k = new HMACKey(key.getBytes());
HMAC hmac = new HMAC(k, new SHA1Digest());
hmac.update(message.getBytes());
byte[] mac = hmac.getMAC();
return Base64OutputStream.encodeAsString(mac, 0, mac.length, false, false);
}
public static String concatURL(String url, String header){
String newurl=url;
header = header.replace(',', '&');
newurl = newurl+"?"+header;
return newurl;
}
Then I get the signature_invalid Message. please Help me to find out the error.

Categories