I have an assignment where I am supposed to send a youtube song in the format to a url. (Further Explanation):
{"title":"Roar", "artist":"Katy Perry", "rating":5, "youtubeID":"CevxZvSJLk8", "key":"rf3498phfwqvwlie457fghwlriq347fl"}
The song is supposed to show up in a database:
http://fury.cse.buffalo.edu/musicRatings/getAllSongs
This is what I have so far which I feel is completed, also no errors:
import java.io.IOException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import com.eclipsesource.json.JsonObject;
public class Lab10 {
public static void main(String[] args) {
}
public static String postRequest(String url, String params){
String response = "";
try{
response = Request.Post(url)
.bodyString(params, ContentType.DEFAULT_TEXT)
.execute().returnContent().asString();
}catch(IOException ex){
ex.printStackTrace();
}
return response;
}
public static String lab() {
JsonObject song = new JsonObject();
song.add("title", "Sweater Weather");
song.add("artist","TheNeighbourhood");
song.add("rating",4);
song.add("youtubeID","GCdwKhTtNNw");
song.add("key","v5eysvylja457gnu0p62szurzrqcf6n8");
String ans = song.toString();
return postRequest("http://fury.cse.buffalo.edu/musicRatings/addSong", ans);
}
}`
It still does not show in the database when searching with ctrl+F. Is the way I'm returning it wrong?
Related
The project I am working on is trying to communicate with the FDA API and retrieve certain information. However, with my nested JSON, the object I am trying to retrieve is returning a null value. Does anybody know what I am doing wrong? Thank you and please let me know if I am missing any information.
URL I am trying to access information from:
https://api.fda.gov/drug/label.json?
JSON Tester Class
package com.example.user.searchbarapp;
import java.net.*;
import java.io.*;
import com.google.gson.*;
public class JSONTester {
public static void main(String[] args) throws Exception {
Gson g = new Gson();
URL FDAServer = new URL("https://api.fda.gov/drug/label.json?");
HttpURLConnection conn = (HttpURLConnection)
FDAServer.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8");
Medication advil = g.fromJson(inputStream, Medication.class);
System.out.print(advil);
}
}
Medication Class
package com.example.user.searchbarapp;
import java.net.URL;
import java.util.Arrays;
public class Medication {
private NestedMedication[] NestedMedication;
public Medication(com.example.user.searchbarapp.NestedMedication[] nestedMedication) {
NestedMedication = nestedMedication;
}
public com.example.user.searchbarapp.NestedMedication[] getNestedMedication() {
return NestedMedication;
}
public void setNestedMedication(com.example.user.searchbarapp.NestedMedication[] nestedMedication) {
NestedMedication = nestedMedication;
}
#Override
public String toString() {
return "Medication{" +
"NestedMedication=" + Arrays.toString(NestedMedication) +
'}';
}
}
NestedMedication Class
package com.example.user.searchbarapp;
public class NestedMedication {
String route;
#Override
public String toString() {
return "NestedMedication{" +
"route='" + route + '\'' +
'}';
}
}
Output
Medication{NestedMedication=null}
Process finished with exit code 0
I started with this :http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/
and created a JSON on localhost:8080...
I am not sure if there is any way to generate new Json every 3 or 5 second. for example just add one digit to new JSON every 3 sec.
#Path("/LNU.se")
public class EntryPoint {
#GET
#Path("get")
#Produces(MediaType.TEXT_PLAIN)
public String test() {
return "mahdi Test";
}
#POST
#Path("post")
#Consumes(MediaType.TEXT_PLAIN)
public Response postTest(Track track){
String resault = " the track is saved mahdi: "+ track;
return Response.status(201).entity(resault).build();
}
}
and another class:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter( "jersey.config.server.provider.classnames", EntryPoint.class.getCanonicalName());
try {
jettyServer.start();
System.out.println(" open your browser on http://localhost:8080/LNU.se/get");
jettyServer.join();
} catch (Exception e)
{
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
======================
UPDATE: -->
My server is:
package rest;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class RestServer {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
Calculator.class.getCanonicalName());
try {
jettyServer.start();
System.out.println(" open the browser on http://localhost:8080/calculator/squareRoot?input=16");
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
and this class:
package rest;
import java.awt.event.ItemEvent;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
#Path("calculator")
public class Calculator {
Result ress = new Result("mahdi84");
public static String resul1;
#GET
#Path("mahdi")
#Produces(MediaType.APPLICATION_JSON)
public Result mahdi(){
JSONObject json = new JSONObject();
json.put("validTime", "2016-02-24T11:00:00Z");
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("mcc", resul1);
obj.put("temprature", resul1+1);
obj.put("Humidity", resul1+10);
jsonArray.add(obj);
json.put("\n JSONdata --> ", jsonArray);
ress.setInput(Double.parseDouble(resul1));
ress.setOutput(Double.parseDouble(resul1));
ress.setTestVar(resul1);
ress.setTestVar2(json);
return ress;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
resul1= data;
return Response.status(201).entity(result).build();
}
static class Result{
double input;
double output;
String action;
Object testVar;
JSONObject testVar2;
public Result(){}
public JSONObject getTestVar2() {
return testVar2;
}
public void setTestVar2(JSONObject testVar2) {
this.testVar2 = testVar2;
}
public Object getTestVar() {
return testVar;
}
public void setTestVar(Object testVar) {
this.testVar = testVar;
}
public Result(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public double getInput() {
return input;
}
public void setInput(double input) {
this.input = input;
}
public double getOutput() {
return output;
}
public void setOutput(double output) {
this.output = output;
}
}
}
and my client is:
import java.util.Timer;
import java.util.TimerTask;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost extends TimerTask{
public int cuntr = 0;
public static void main(String[] args) {
TimerTask mytask = new JerseyClientPost();
Timer timer = new Timer();
timer.schedule(mytask, 1000, 1000);
}
#Override
public void run() {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/calculator/post");
String input = Integer.toString(cuntr++);
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
}
String output = response.getEntity(String.class);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
the client will post to the server every 1 sec and the server will generate new JSON on "http://localhost:8080/calculator/mahdi"
when i try to read from "http://localhost:8080/calculator/mahdi" by apache http1.1 in another program :
package HttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MyHttpClient {
public static void main(String[] args) throws Exception{
HttpGet requset = new HttpGet("http://localhost:8080/calculator/mahdi");
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(requset);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
System.out.println("Reading began ... ");
while (true) {
String line = br.readLine();
if (line != null && !line.isEmpty()) {
System.out.println(line);
}
}
}
}
edit:
thank you I did that by using TImeTask class
it only print the first JSON! but when I refresh the weblink, it is updating on browser.
would you please correct me if I am wrong? I want to see the stream of JSON on MyHttpClient, but it only shows the first JSON!
I think you are mixing things. The server should only be a server, and not extend TimerTask. The client should call the server at a specific intervall
Do the follwing:
Test your server in a web-browser. Make sure that it will respond.
Write a client either in Java or javascript If you are using Java
the client should have a http-client.
The client should hava a timertask calling the the server at a specific intervall
This is the main class in which query is being fired
package extractKeyword;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
// private static String powered_by ="non";
// private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
//private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
//private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT)
//, String powered_by,String spotter,String disambiguator,String showScores)
{
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
// this.powered_by=powered_by;
//this.spotter=spotter;
//this.disambiguator=disambiguator;
//showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
// LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
// + "&spotter=" + spotter
// + "&disambiguator=" + disambiguator
// + "&showScores=" + showScores
// + "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
//LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
//((Object) LOG).error("JSON exception "+e);
}
}
return resources;
}
}
The extended class
package extractKeyword;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.HttpMethod;
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
//public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(GetMethod getMethod) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
( getMethod).getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod((org.apache.commons.httpclient.HttpMethod) getMethod);
if (statusCode != HttpStatus.SC_OK) {
// LOG.error("Method failed: " + ((HttpMethodBase) method).getStatusLine());
}
// Read the response body.
byte[] responseBody = ((HttpMethodBase) getMethod).getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
// LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
//((Object) LOG).error("Fatal transport error: " + e.getMessage());
//((Object) LOG).error(((HttpMethodBase) method).getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
((HttpMethodBase) getMethod).releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
//LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
The Main Class
package extractKeyword;
public class startAnnonation {
public static void main(String[] args) throws Exception {
String question = "What is the winning chances of BJP in New Delhi elections?";
db c = new db ();
c.configiration(0.25,0);
//, 0, "non", "AtLeastOneNounSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
}
The main problem is here when I am using DBPedia spotlight using spotlight jar (above code)then i am getting different result as compared to the dbpedia spotlight endpoint(dbpedia-spotlight.github.io/demo/)
Result using the above code:-
Text :-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Election]
Result on DBPedia Spotlight endpoint(//dbpedia-spotlight.github.io/demo/)
Text:-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Bharatiya_Janata_Party, New_Delhi, Election]
Why also the spotlight now don't have support as a parameter?
Following a tutorial which I didn't fully understand I did the following:
I created four classes.
package com.example.android.wearable.watchface;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class Beansubject {
#SerializedName("subject")
private static String subject;
#SerializedName("price")
private static String price;
#SerializedName("author")
private static String author;
#SerializedName("topics")
private static ArrayList<BeanTopic> beanTopics;
public Beansubject(ArrayList<BeanTopic> beanTopics, String subject, String price, String author) {
this.beanTopics = beanTopics;
this.subject = subject;
this.price = price;
this.author = author;
}
public static String getSubject() {
return subject;
}
public static void setSubject(String subj) {
subject = subj;
}
public static String getPrice() {
return price;
}
public static void setPrice(String pric) {
price = pric;
}
public String getAuthor() {
return author;
}
public static void setAuthor(String aue) {
author = aue;
}
public static ArrayList<BeanTopic> getBeanTopics() {
return beanTopics;
}
public static void setBeanTopics(ArrayList<BeanTopic> beantcs) {
beanTopics = beantcs;
}
}
Next
package com.example.android.wearable.watchface;
import com.google.gson.annotations.SerializedName;
public class BeanTopic {
#SerializedName("title")
private String title;
public BeanTopic(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Next
package com.example.android.wearable.watchface;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class API {
private static Reader reader=null;
public static Reader getData(String SERVER_URL) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new InputStreamReader(content);
} else {
// Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader;
}
}
Finally
package com.example.android.wearable.watchface;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import com.google.gson.GsonBuilder;
import java.io.Reader;
import java.util.ArrayList;
public class MainActivity extends Activity {
ProgressDialog progressDialog;
TextView txtSubject;
TextView txtAuthor;
TextView txtPrice;
TextView txtTopicsList;
Beansubject beanSubject;
StringBuffer topicList;
public void Json() {
new AsyncTask<Void,Void,Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
Reader reader=API.getData("http://beta.json-generator.com/api/json/get/OkS85Le");
beanSubject = new GsonBuilder().create().fromJson(reader, Beansubject.class);
Log.e("Subject: ", beanSubject.getSubject() + "");
Log.e("Author: ", beanSubject.getAuthor() + "");
Log.e("Price: ", beanSubject.getPrice() + "");
ArrayList<BeanTopic> topicArrayList = beanSubject.getBeanTopics();
topicList = new StringBuffer();
for(BeanTopic topic: topicArrayList){
Log.e("topic title: ",topic.getTitle()+"");
topicList.append("* " + topic.getTitle()+"\n");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
txtSubject.setText("Subject: " + beanSubject.getSubject());
txtPrice.setText("price: "+beanSubject.getPrice());
txtAuthor.setText("Author: "+beanSubject.getAuthor());
txtTopicsList.setText("Topics: "+"\n" + topicList);
}
}.execute();
}
}
The error is that I'm not sure how to create the objects that are in the tutorial in the last part for the activity class.
For the parts I did not understand in this last part of the tutorial where objects are being created which are possibly linked and possibly not to other classes I took random guesses for what they are.
I even made some stuff static in the other classes and removed "this." to get something to work. Please help me understand that last part of the tutorial so I could understand fully how to do this simple task. Thanks.
Here is the link to this simple tutorial:
http://www.nkdroid.com/2014/11/json-object-parsing-using-url-in-android.html
Okay, so these are my unknown variables: MyActivity.this, progressdialog, txtpostlist, postlist, beanpostarraylist. I am using a different tutorial now -> more basic. So I'm not sure why the tutorial is so vague with creating the MainActivity Class. What is missing? http://nkdroid.com/2014/11/json-parsing-using-gson-in-android.html
May help to look at the data being provided by API call.
paste result belo to http://json.parser.online.fr/
curl -v http://beta.json-generator.com/api/json/get/OkS85Le
{"topics": [{"title": "how to add fontawesome icons in android example"},
{"title": "how to parse json parsing using gson library"},
{"title": "how to store arraylist in sharedpreferences"}],
"auther": "nirav kalola",
"price": "free",
"subject": "Android Application Development Tutorial"}
So , the 3 "title" elements in the JSON wind up in UI because of the following :
beanSubject = new GsonBuilder().create().fromJson(reader, Beansubject.class);
ArrayList<BeanTopic> topicArrayList = beanSubject.getBeanTopics();
for(BeanTopic topic: topicArrayList){
topicList.append("* " + topic.getTitle()+"\n");
}
txtTopicsList.setText("Topics: "+"\n" + topicList);
code gets data
MVC model/collection objs created from JSON Array
UI list set from collection obj
see here for more on Adapters getting data from the collection Object holders.
You would need to create a layout that have some TextView components with the corresping ids. So create one xml file with some textviews with the proper ids. Then override the onCreate method, and call the JSON method:
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.id.my_layout);
txtSubject = (TextView) findViewById(R.id.txtSubject);
...
Json();
}
If something is unclear, I recommend you to read a basic android tutorial (the one from the official site is great).
Is there a way to programmatically fetch Google+ updates for a user's profile? I can't seem to find much in the documentation at https://developers.google.com/+/api/latest/people and http://developer.android.com/reference/com/google/android/gms/plus/model/people/Person.html about fetching statuses. I would like to fetch the data by making an HTTP request or if there is some sort of SDK for Android that will help me, that would work to.
The API you are looking for is plus.activities.list. This will list the Google+ equivalent of Facebook status updates. The referenced page has example code to get you started.
When accessing the API, you should use the Google API client as documented here.
The following code will be useful to retrieve the Http responses.
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GooglePlusStatusHelper {
public GooglePlusStatusHelper() {
}
public static void main(String... args) {
GooglePlusStatusHelper googlePlusStatusHelper = new GooglePlusStatusHelper();
try {
googlePlusStatusHelper.tagsUsed();
} catch (IOException e) {
e.printStackTrace();
}
}
private void tagsUsed() throws IOException {
URL url = createQuery("users");
Type dataType = new TypeToken<Wrapper<Status>>(){}.getType();
Status status = executeQuery(url, dataType);
System.out.println(status);
}
private URL createQuery(String inputParam) throws MalformedURLException {
String baseUrl = "http://api.example.com/" + inputParam ;
System.out.println(baseUrl);
URL url = new URL(baseUrl);
return url;
}
private Status executeQuery(URL url, Type clz) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
System.out.println("Response Code:" + conn.getResponseCode());
System.out.println("Response Message:" + conn.getResponseMessage());
System.out.println("TYPE:" + conn.getContentType());
InputStream content = conn.getInputStream();
String encoding = conn.getContentEncoding();
if (encoding != null && encoding.equals("gzip")) {
content = new GZIPInputStream(content);
}
String result = new Scanner(content, "UTF-8").useDelimiter("\\A").next();
content.close();
Gson gson = new Gson();
return gson.fromJson(result, clz);
}
}
Status class :
public class Status {
private int count;
private String status;
......
public String toString() {
String result = "\ncount: " + count +
"\status:" + status;
result = result + "\n------------";
return result;
}
}