fetching data json to my list view - json

package com.example.velichamjson;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://velicham.co.in/index.php?option=com_obrss&task=feed&id=4:politics&format=json&Itemid=351";
// JSON Node names
private static final String TAG_ITEMS= "items";
private static final String TAG_TITLE= "title";
private static final String TAG_LINK = "link";
private static final String TAG_PUBDATE = "pubDate";
private static final String TAG_DESCRIPTION= "description";
// private static final String TAG_GENDER = "gender";
// private static final String TAG_PHONE = "phone";
// private static final String TAG_PHONE_MOBILE = "mobile";
// private static final String TAG_PHONE_HOME = "home";
// private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> itemList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String link = ((TextView) view.findViewById(R.id.link))
.getText().toString();
String pubDate = ((TextView) view.findViewById(R.id.pubdate))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.description))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_LINK, link);
in.putExtra(TAG_PUBDATE, pubDate);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
// Calling async task to get json
new GetItems().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
System.out.println(items);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String link = c.getString(TAG_LINK);
String pubDate = c.getString(TAG_PUBDATE);
String description = c.getString(TAG_DESCRIPTION);
//String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject(TAG_PHONE);
// String mobile = phone.getString(TAG_PHONE_MOBILE);
// String home = phone.getString(TAG_PHONE_HOME);
// String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> item = new HashMap<String, String>();
// adding each child node to HashMap key => value
item.put(TAG_TITLE, title);
item.put(TAG_LINK, link);
item.put(TAG_PUBDATE, pubDate);
item.put(TAG_DESCRIPTION, description);
// adding contact to contact list
itemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, itemList,
R.layout.list_item, new String[] { TAG_LINK, TAG_PUBDATE,
TAG_DESCRIPTION ,TAG_TITLE}, new int[] { R.id.link,
R.id.pubdate, R.id.description,R.id.title });
setListAdapter(adapter);
}
}
}
iam trying to parse json data it is a tamil news am fetching from my json data but it shows an error NO VALUE FOR ITEMS am trying more than an half a day any can answer where it goes wrong i dont know where it goes wrong anyone reponse me thanks in advance

UPDATE - Using the JsonObject you can do as below
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arr = new JSONArray(jsonObj.get(TAG_ITEMS));
// looping through All data
for (int i = 0; i < arr.length(); i++) {
JSONObject temp = arr.getJSONObject(i);
String title = temp.get(TAG_TITLE);
String link = temp.get(TAG_LINK);
String pubDate = temp.get(TAG_PUBDATE);
String description = temp.get(TAG_DESCRIPTION);
}
} catch (JSONException e) {
e.printStackTrace();
}
You can use the JsonReader
Like Below for your json data,
NOTE - I have not tested the code and you have to tweak it as per your requirement but thats how you can parse the JsonData using the androids JsonReader.You can look up the android developers page to more info.
JsonReader reader = new JsonReader(new InputStreamReader(yourResponseStream, Encoding));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("count")) {
string count = reader.nextString();
} else if (name.equals("value")) {
//Method to process the value object
processValueObject(reader);
} else {
reader.skipValue();
}
}
private void processValueObject(JsonReader reader)
{
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("feedUrl")) {
string feedUrl = reader.nextString();
} else if (name.equals("title")) {
string title = reader.nextString();
} ....and so on
//For array of data
}else if (name.equals("items"))
{
reader.beginArray();
reader.beginObject();
//then use the same methods to get name and value pair.
processReader(reader);
//at the end dont forget to end your array and object
reader.endObject();
reader.endArray();
}
else {
reader.skipValue();
}
}
}
Hope it helps...

Related

Getting json data from Spoonacular in Android Studio

trying to get to an Android App random recipes from Spoonacular. For some reason, I'm not getting the data from the json. I know how to do this in Javascript, but that's no use to me in Java.
My repository file:
public class RecipeRepository {
private static final String API_KEY = "472f31ce4a5e4e5792ca9ab6d1833e51";
private static final String URL = "https://api.spoonacular.com/recipes/random?apiKey=%s";
private final Application application;
private final MutableLiveData<ArrayList<Recipe>> recipeLiveData;
private final ArrayList<Recipe> arrayList = new ArrayList<>();
public RecipeRepository(Application application) {
this.application = application;
recipeLiveData = new MutableLiveData<>();
}
public void getDayRecipe() {
Ion.with(application)
.load(String.format(URL,API_KEY)).asJsonObject()
.setCallback((e, result) -> {
Log.i( "getRandomRecipe",result.getAsJsonPrimitive().toString());
parseResults(result);
});
}
public String removeAbles(String text) {return text.substring(1,text.length()-1); }
private void parseResults(JsonObject result) {
JsonObject randomRecipe = (JsonObject) result.getAsJsonArray("recipes").get(0);
String title = String.valueOf(randomRecipe.get("title"));
String instructions = String.valueOf(randomRecipe.get("Instructions"));
//ingredients
//image
recipeLiveData.setValue(arrayList);
}
public MutableLiveData<ArrayList<Recipe>> getRecipeLiveData() {
return recipeLiveData;
}
}
I get a 'variable is never used' with title, instructions and removeAbles

Is there a method built in spring MockMVC to get json content as Object?

In my Spring project i created some tests that check the controllers/ http-api. Is there a way to get the json content of response as de-serialized object?
In other project i used rest assured and there methods to acquire results directly as expected objects.
Here is an example:
MvcResult result = rest.perform( get( "/api/byUser" ).param( "userName","test_user" ) )
.andExpect( status().is( HttpStatus.OK.value() ) ).andReturn();
String string = result.getResponse().getContentAsString();
The method returns a specific type as json. how to convert this json back to an object to tests its contents?
I know ways with jackson or with rest-assured but is there a way within spring/test/mockmvc
Like getContentAs(Class)
As far as I know MockHttpServletResponse (Unlike RestTemplate) doesn't have any method which could convert returned JSON to a particular type.
So what you could do is use Jackson ObjectMapper to convert JSON string to a particular type
Something like this
String json = rt.getResponse().getContentAsString();
SomeClass someClass = new ObjectMapper().readValue(json, SomeClass.class);
This will give you more control for you to assert different things.
Having said that, MockMvc::perform returns ResultActions which has a method andExpect which takes ResultMatcher. This has a lot of options to test the resulting json without converting it to an object.
For example
mvc.perform( .....
......
.andExpect(status().isOk())
.andExpect(jsonPath("$.firstname").value("john"))
.andExpect(jsonPath("$.lastname").value("doe"))
.andReturn();
This might be of use:
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.togondo.config.database.MappingConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
#Slf4j
#Getter
public class CustomResponseHandler<T> implements ResultHandler {
private final Class<? extends Collection> collectionClass;
private T responseObject;
private String responseData;
private final Class<T> type;
private Map<String, String> headers;
private String contentType;
public CustomResponseHandler() {
this.type = null;
this.collectionClass = null;
}
public CustomResponseHandler(Class type) {
this.type = type;
this.collectionClass = null;
}
public CustomResponseHandler(Class type, Class<? extends Collection> collectionClass) {
this.type = type;
this.collectionClass = collectionClass;
}
protected <T> T responseToObject(MockHttpServletResponse response, Class<T> type) throws IOException {
String json = getResponseAsContentsAsString(response);
if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
return null;
}
return MappingConfig.getObjectMapper().readValue(json, type);
}
protected <T> T responseToObjectCollection(MockHttpServletResponse response, Class<? extends Collection> collectionType, Class<T> collectionContents) throws IOException {
String json = getResponseAsContentsAsString(response);
if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
return null;
}
ObjectMapper mapper = MappingConfig.getObjectMapper();
JavaType type = mapper.getTypeFactory().constructCollectionType(collectionType, collectionContents);
return mapper.readValue(json, type);
}
protected String getResponseAsContentsAsString(MockHttpServletResponse response) throws IOException {
String content = "";
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getContentAsByteArray())));
String line;
while ((line = br.readLine()) != null)
content += line;
br.close();
return content;
}
#Override
public void handle(MvcResult result) throws Exception {
if( type != null ) {
if (collectionClass != null) {
responseObject = responseToObjectCollection(result.getResponse(), collectionClass, type);
} else {
responseObject = responseToObject(result.getResponse(), type);
}
}
else {
responseData = getResponseAsContentsAsString(result.getResponse());
}
headers = getHeaders(result);
contentType = result.getResponse().getContentType();
if (result.getResolvedException() != null) {
log.error("Exception: {}", result.getResponse().getErrorMessage());
log.error("Error: {}", result.getResolvedException());
}
}
private Map<String, String> getHeaders(MvcResult result) {
Map<String, String> headers = new HashMap<>();
result.getResponse().getHeaderNames().forEach(
header -> headers.put(header, result.getResponse().getHeader(header))
);
return headers;
}
public String getHeader(String headerName) {
return headers.get(headerName);
}
public String getContentType() {
return contentType;
}
}
And then use it in your tests like this:
CustomResponseHandler<MyObject> responseHandler = new CustomResponseHandler(MyObject.class);
mockMvc.perform(MockMvcRequestBuilders.get("/api/yourmom"))
.andDo(responseHandler)
.andExpect(status().isOk());
MyObject myObject = responseHandler.getResponseObject();
Or if you want to fetch collections:
CustomResponseHandler<Set<MyObject>> responseHandler = new CustomResponseHandler(MyObject.class, Set.class);
.
.
.
Set<MyObject> myObjectSet = responseHandler.getResponseObject();

Database is overwriting. Last entry from json is written in database and all other entry is overwritten. Showing only last Entry of Json File

PlayerService
this is srvice class of my boot app.
package io.anuj.springbootquickstart.topic;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class PlayerService {
#Autowired
private PlayerRespository playerRespository;
// private List<Topic> topics = new ArrayList<> (Arrays.asList(
// new Topic("Spring","Spring Framework","SpringFramework Description"),
// new Topic("Core","Core Framework","CoreFramework Description"),
// new Topic("JavaScript","JavaScript Framework","JavaScript Description")));
public List<Player> getAllPlayer(){
List<Player> player = new ArrayList();
playerRespository.findAll()
.forEach(player::add); //lambda expressions
return player;
}
public Player getPlayer(Long id){
//return topics.stream().filter(t -> t.getId().equals(id).findFirst().get());
return playerRespository.findOne(id);
}
public void addPlayer(Player player) {
playerRespository.save(player);
}
public void updatePlayer(Long id, Player player) {
playerRespository.save(player);
}
public void deletePlayer(Long id) {
//topics.removeIf(t -> t.getId().equals(id));
playerRespository.delete(id);
}
}
PLayerRepository
this is player repository of my app.
package io.anuj.springbootquickstart.topic;
import org.springframework.data.repository.CrudRepository;
public interface PlayerRespository extends CrudRepository <Player, Long>{
//crud repository-logic of any entity class
//getallTopic()
//gettopic(string id)
//update topic(topic t)
//deletetopic(string id)
}
PLayerController
this is player controller
package io.anuj.springbootquickstart.topic;
import java.io.FileReader;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
//wherever rest controller is written it will give json as output send back as a HTTP response
public class PlayerController {
#Autowired
private PlayerService playerService;
//get request by default
#RequestMapping("/player")
public List<Player> getallPlayer(){
return playerService.getAllPlayer();
}
//get request
#RequestMapping("/player/{id}")
public Player getPlayer(#PathVariable Long id){
return playerService.getPlayer(id);
}
//
#RequestMapping(method=RequestMethod.GET, value= "/getplayer")
public void addAllPlayer(){
Player player = new Player();
JSONParser parser = new JSONParser();
try {
Object ob = parser.parse(new FileReader("/home/bridgeit/Desktop/P.D-anuj/Json/newPlayerInfo.json"));
JSONObject object = (JSONObject) ob;
JSONArray data = (JSONArray) object.get("Playersinfo");
for (int i = 0; i < data.size(); i++)
{
JSONObject itemObj = (JSONObject) data.get(i);
Object nameObj = itemObj.get("player_name");
String playerName = (String) nameObj;
player.setPlayer_name(playerName);
Object imgObject = itemObj.get("player_img_url");
String playerPic = (String) imgObject;
player.setPlayer_img_url(playerPic);
Object roleObj = itemObj.get("player_role");
String roleName = (String) roleObj;
player.setPlayer_role(roleName);
Object battingStyleObj = itemObj.get("player_batting_style");
String battingStyleName = (String) battingStyleObj;
player.setPlayer_batting_style(battingStyleName);
Object bowlingObj = itemObj.get("player_bowling_style");
String bowlingName = (String) bowlingObj;
player.setPlayer_bowling_style(bowlingName);
Object nationalityObj = itemObj.get("player_nationality");
String nationalityName = (String) nationalityObj;
player.setPlayer_nationality(nationalityName);
Object dobObj = itemObj.get("player_dob");
String dobName = (String) dobObj;
player.setPlayer_dob(dobName);
Object teamIdObj = itemObj.get("team_id");
String teamIdName = (String) teamIdObj;
player.setTeam_id(teamIdName);
playerService.addPlayer(player);
}
} catch (Exception e) {
System.out.println(e);
}
}
/*#RequestMapping(method=RequestMethod.PUT, value= "/player/{id}")
public void updatePlayer(#RequestBody Player player,#PathVariable String id){
playerService.updatePlayer(id,player);
}
#RequestMapping(method=RequestMethod.DELETE, value= "/player/{id}")
public void deletePlayer(#PathVariable String id){
playerService.deletePlayer(id);
}*/
}
this is POJO class
Player.java
package io.anuj.springbootquickstart.topic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
#Entity
/*#Table(name = "Player")*/
public class Player {
/*#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
#Column(name = "id")
private Long id;*/
#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
private long id;
private String team_id;
/*#Column(name = "name")*/
private String player_name;
/*#Column(name = "display_picture")*/
private String player_img_url;
/*#Column(name = "role")*/
private String player_role;
public Player(long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
/* #Column(name = "batting_style")*/
private String player_batting_style;
/*#Column(name = "bowling_style")*/
private String player_bowling_style;
/*#Column(name = "nationality")*/
private String player_nationality;
/*#Column(name = "dob")*/
private String player_dob;
/*#Column(name = "teamId")*/
public Player(){
}
public String getTeam_id() {
return team_id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTeam_id(String team_id) {
this.team_id = team_id;
}
public String getPlayer_name() {
return player_name;
}
public void setPlayer_name(String player_name) {
this.player_name = player_name;
}
public String getPlayer_img_url() {
return player_img_url;
}
public void setPlayer_img_url(String player_img_url) {
this.player_img_url = player_img_url;
}
public String getPlayer_role() {
return player_role;
}
public void setPlayer_role(String player_role) {
this.player_role = player_role;
}
public String getPlayer_batting_style() {
return player_batting_style;
}
public void setPlayer_batting_style(String player_batting_style) {
this.player_batting_style = player_batting_style;
}
public String getPlayer_bowling_style() {
return player_bowling_style;
}
public void setPlayer_bowling_style(String player_bowling_style) {
this.player_bowling_style = player_bowling_style;
}
public String getPlayer_nationality() {
return player_nationality;
}
public void setPlayer_nationality(String player_nationality) {
this.player_nationality = player_nationality;
}
public String getPlayer_dob() {
return player_dob;
}
public void setPlayer_dob(String player_dob) {
this.player_dob = player_dob;
}
/*public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}*/
/*public Player(Long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
*/
}
When i execute from json file it shows only last entry of json file. JSON file contains around 150 players but in databse is shows only last entry of the player. i think all the data is getting overwritten. Only last entry is shown of that json file in database. That is last player. Only one player which is last in json is there in database.
It's a little difficult to tell because you have a lot of commented out code that makes things harder to follow, but I think it is because of where you are creating the Player in your controller. Since you're doing this:
Player player = new Player()
outside of the loop, and Java is pass by value of reference, after the first time you addPlayer, you're just updating the same player with new data each time. You could confirm this if you simply debug your code and see if player has an ID after the first save call.
You'd probably want to do this to fix it:
for (int i = 0; i < data.size(); i++) {
Player player = new Player();
// rest of your code here
}

URLEncoder to search with multiple words

Below is library app. In its current state, the app is only able to search for single words. Searches like "Harry Potter" yield no result. I was told to use an URLEncoder but I tried and even that didn't work. Below are my java files.'
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Books>>, SearchView.OnQueryTextListener {
LoaderManager loaderManager;
String mQuery;
SearchView mSearchView;
MenuItem mMenuSearchItem;
private static final String LOG_TAG = MainActivity.class.getName();
private static final String GOOGLE_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?maxResults=40&q=";
private String url = GOOGLE_REQUEST_URL + "android";
private static final int BOOK_LOADER_ID = 1;
private BookAdapter adapter;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView bookListView = (ListView) findViewById(R.id.list);
adapter = new BookAdapter(this, new ArrayList<Books>());
bookListView.setAdapter(adapter);
loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Books currentBook = adapter.getItem(position);
Uri bookUri = Uri.parse(currentBook.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
startActivity(websiteIntent);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
#Override
public boolean onQueryTextSubmit(String query) {
if(isOnline()){
url = GOOGLE_REQUEST_URL + query;
loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
}else{
Toast.makeText(this, "No Internet Connection Found!", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mQuery = newText;
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
mMenuSearchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
if (mSearchView != null) {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean queryTextFocused) {
if (!queryTextFocused) {
if (TextUtils.isEmpty(mQuery))
adapter.clear();
}
}
});
}
return true;
}
#Override
public Loader<List<Books>> onCreateLoader(int i, Bundle bundle) {
return new BookLoader(this, url);
}
#Override
public void onLoadFinished(Loader<List<Books>> loader, List<Books> books) {
adapter.clear();
if (books != null && !books.isEmpty()) {
adapter.addAll(books);
}
}
#Override
public void onLoaderReset(Loader<List<Books>> loader) {
adapter.clear();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
BookUtils.java
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class BookUtils {
private static final String LOG_TAG = BookUtils.class.getSimpleName();
private BookUtils() {}
public static List<Books> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {jsonResponse = makeHttpRequest(url);}
catch (IOException e) {Log.e(LOG_TAG, "Problem making the HTTP request.", e);}
List<Books> books = extractFeatureFromJson(jsonResponse);
return books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {url = new URL(stringUrl);}
catch (MalformedURLException e) {Log.e(LOG_TAG, "Problem building the URL ", e);}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {return jsonResponse;}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());}
}
catch (IOException e) {Log.e(LOG_TAG, "Problem retrieving the book JSON results.", e);}
finally {
if (urlConnection != null) {urlConnection.disconnect();}
if (inputStream != null) {inputStream.close();}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Books> extractFeatureFromJson(String bookJSON) {
if (TextUtils.isEmpty(bookJSON)) {return null;}
List<Books> books = new ArrayList<>();
try {
JSONObject jsonResponse = new JSONObject(bookJSON);
JSONArray booksArray = jsonResponse.getJSONArray("items");
for (int i = 0; i < booksArray.length(); i++) {
JSONObject currentBook = booksArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
JSONArray authorsArray = volumeInfo.getJSONArray("authors");
String title = "", publisher = "", publishedDate = "", language = "", pageCount = "", printType = "", maturityRating = "", authors = "";
if(volumeInfo.has("title")){
language = volumeInfo.getString("language");
}
for (int j = 0; j < authorsArray.length(); j++) {
if (volumeInfo.has("authors")){
authors = authorsArray.getString(j);
}
}
if(volumeInfo.has("publisher")){
publisher = volumeInfo.getString("publisher");
}
if(volumeInfo.has("publishedDate")){
publishedDate = volumeInfo.getString("publishedDate");
}
if(volumeInfo.has("language")){
language = volumeInfo.getString("language");
}
if(volumeInfo.has("pageCount")){
pageCount = volumeInfo.getString("pageCount");
}
if(volumeInfo.has("printType")){
printType = volumeInfo.getString("printType");
}
if(volumeInfo.has("maturityRating")){
maturityRating = volumeInfo.getString("maturityRating");
}
Books book = new Books(title, authors, publisher, publishedDate, language, pageCount, printType, maturityRating);
books.add(book);
}
}
catch (JSONException e) {Log.e("QueryUtils", "Problem parsing the book JSON results", e);}
return books;
}
}
Books.java
public class Books {
private String mTitle;
private String mAuthors;
private String mPublisher;
private String mPublishingDate;
private String mLanguage;
private String mCount;
private String mPrintType;
private String mMaturityRating;
private String mURL;
public Books(String title, String authors, String publisher, String publishingDate, String language, String count, String printType, String maturityRating) {
mTitle = title;
mAuthors = authors;
mPublisher = publisher;
mPublishingDate = publishingDate;
mLanguage = language;
mCount = count;
mPrintType = printType;
mMaturityRating = maturityRating;
}
public String getTitle() {return mTitle;}
public String getAuthors(){return mAuthors;}
public String getPublisher(){return mPublisher;}
public String getPublishedDate(){return mPublishingDate;}
public String getLanguage(){return mLanguage;}
public String getCount(){return mCount;}
public String getPrintType(){return mPrintType;}
public String getMaturityRating(){return mMaturityRating;}
public String getUrl() {return mURL;}
}
BookLoader.java
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
public class BookLoader extends AsyncTaskLoader<List<Books>> {
private static final String LOG_TAG = BookLoader.class.getName();
private String mUrl;
public BookLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {forceLoad();}
#Override
public List<Books> loadInBackground() {
if (mUrl == null) {return null;}
List<Books> books = BookUtils.fetchBookData(mUrl);
return books;
}
}
BookAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Books> {
public BookAdapter(Context context, List<Books> books) {
super(context, 0, books);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {listItemView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_item, parent, false);}
Books currentBook = getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.book_title);
title.setText(currentBook.getTitle());
TextView authors = (TextView) listItemView.findViewById(R.id.book_author);
authors.setText(currentBook.getAuthors());
TextView publisher = (TextView) listItemView.findViewById(R.id.book_publisher);
publisher.setText(currentBook.getPublisher());
TextView publishingDate = (TextView) listItemView.findViewById(R.id.book_publishing_date);
publishingDate.setText(currentBook.getPublishedDate());
TextView language = (TextView) listItemView.findViewById(R.id.book_language);
language.setText(currentBook.getLanguage());
TextView pageCount = (TextView) listItemView.findViewById(R.id.book_page_count);
pageCount.setText(currentBook.getCount());
TextView printType = (TextView) listItemView.findViewById(R.id.book_print_type);
printType.setText(currentBook.getPrintType());
TextView maturityRating = (TextView) listItemView.findViewById(R.id.book_maturity_rating);
maturityRating.setText(currentBook.getMaturityRating());
return listItemView;
}
}
On my onQueryTextSubmit method, I tried replacing url = GOOGLE_REQUEST_URL + query; with:
Uri.Builder uriBuilder = Uri.parse(GOOGLE_REQUEST_URL).buildUpon().appendQueryParameter("q", query);
url = uriBuilder.toString();
But it didn't work.

Restlet accepts JSON input from client and respond with POST

I am writing a program which accepts a JSON input with the following format from client:
{
"campaignID": 1,
"clientID": 1,
"pmapID": 1,
"ward": "1-Bedded (Private)",
"age": 20,
"attr1": "EXA1(A)",
"attr2": "EO",
"attr3": "11/02/2012",
"attr4": "SIN",
"attr5": "N",
"attr6": "Y"
}
I'd like to read the JSON input, save all the attributes into local variables (String, int, ...) and finally respond with a POST("JSON") which will return a single float/double value (e.g. {"PMC": 30.12} ).
public class RestletApplication extends Application
{
#Override
public synchronized Restlet createInboundRoot()
{
Router router = new Router(getContext());
router.attach("/pmc/calculate", PMCResource.class);
return router;
}
}
I have written the function so far but am lost how to read the JSON input:
public class PMCResource extends ServerResource
{
#Post("JSON")
public Representation post(Representation entity) throws ResourceException {
try {
if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON))
{
// Read JSON file and parse onto local variables
// Do processing & return a float value
}
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
}
}
5 May 2016 - Edited the resource class
// Imports
public class PMCResource extends ServerResource
{
static Logger LOGGER = LoggerFactory.getLogger(PMCResource.class);
#Override
#Post("JSON")
public Representation post(Representation entity) throws ResourceException
{
PMCMatrixDAO matrix = new PMCMatrixDAOImpl();
JsonObjectBuilder response = Json.createObjectBuilder();
try
{
if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON))
{
InputStream is = new FileInputStream(getClass().getResource("/input.json").getFile());
try (JsonReader reader = Json.createReader(is)) {
JsonObject obj = reader.readObject();
double result = matrix.calculatePMC(obj);
response.add("PMC", result);
}
}
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
return new StringRepresentation(response.build().toString());
}
}
The Implementation class
public class PMCMatrixDAOImpl implements PMCMatrixDAO
{
public double calculatePMC(JsonObject obj)
{
int campaignID = obj.getInt("campaignID");
int clientID = obj.getInt("clientID");
int pmapID = obj.getInt("pmapID");
String ward = obj.getString("ward");
int age = obj.getInt("age");
String attr1 = obj.getString("attr1");
String attr2 = obj.getString("attr2");
String attr3 = obj.getString("attr3");
String attr4 = obj.getString("attr4");
String attr5 = obj.getString("attr5");
String attr6 = obj.getString("attr6");
// SQL processing
double dPMC = sqlQueryCall(...);
return dPMC;
}
}
In order to parse your JSON file, and since you're using Maven I'll assume you have it on your classpath, you can do it using a FileInputStream or a FileReader. So, assuming your JSON file is called input.json and it is on the root of your src/main/resources folder, you can load it the following way:
using a FileInputStream:
InputStream is = new FileInputStream(getClass().getResource("/input.json").getFile());
try (JsonReader reader = Json.createReader(is)) {
// file processing is done here
}
using a FileReader:
FileReader fr = new FileReader(getClass().getResource("/input.json").getFile());
try (JsonReader reader = Json.createReader(fr)) {
// file processing is done here
}
Ok, so now that we have our JsonReader created, lets retrieve the contents of our JSON file:
InputStream is = new FileInputStream(getClass().getResource("/input.json").getFile());
try (JsonReader reader = Json.createReader(is)) {
JsonObject obj = reader.readObject();
// retrieve JSON contents
int campaingID = obj.getInt("campaignID");
int clientID = obj.getInt("clientID");
int pmapID = obj.getInt("pmapID");
String ward = obj.getString("ward");
int age = obj.getInt("age");
String attr1 = obj.getString("attr1");
String attr2 = obj.getString("attr2");
String attr3 = obj.getString("attr3");
String attr4 = obj.getString("attr4");
String attr5 = obj.getString("attr5");
String attr6 = obj.getString("attr6");
}
As an alternative of having several variables across your method, you could create a simple POJO, having those variable as attributes, and then populate it using Jackson:
public class MyPojo {
private int campaingID;
private int clientID;
private int pmapID;
private String ward;
private int age;
private String attr1;
private String attr2;
private String attr3;
private String attr4;
private String attr5;
private String attr6;
// getters & setters
}
Finally, in order to send the response back to your client, you could do this:
JsonObject response = Json.createObjectBuilder().add("PMC", 30.12).build();
return new StringRepresentation(response.toString());
So, the entire solution could look like this:
#Override
#Post("JSON")
public Representation post(Representation entity) throws ResourceException {
JsonObjectBuilder response = Json.createObjectBuilder();
try {
if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON)) {
InputStream is = new FileInputStream(getClass().getResource("/input.json").getFile());
try (JsonReader reader = Json.createReader(is)) {
JsonObject obj = reader.readObject();
// retrieve JSON contents
int campaingID = obj.getInt("campaignID");
int clientID = obj.getInt("clientID");
int pmapID = obj.getInt("pmapID");
String ward = obj.getString("ward");
int age = obj.getInt("age");
String attr1 = obj.getString("attr1");
String attr2 = obj.getString("attr2");
String attr3 = obj.getString("attr3");
String attr4 = obj.getString("attr4");
String attr5 = obj.getString("attr5");
String attr6 = obj.getString("attr6");
}
// Do processing & execute your SQL query call here
double result = sqlQueryCall(...);
response.add("PMC", result);
}
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
return new StringRepresentation(response.build().toString());
}
As a side note, the JsonReader class belongs to the Java EE API which, for compiling purposes it's okay. Although, for running purposes, one requires the declaration of a JSON-API implementation dependency in one's Maven project. For instance:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
Below is the way one can communicate to the REST web service through a client:
Create a simple POJO object that will contain the information to send, as mentioned above (MyPojo).
Your REST service would look something like this:
public class PMCResource extends ServerResource {
static Logger LOGGER = Logger.getLogger(RestletMain.class.getName());
#Post("JSON")
public Representation post(MyPojo entity) throws ResourceException {
PMCMatrixDAO matrix = new PMCMatrixDAOImpl();
JsonObjectBuilder response = Json.createObjectBuilder();
try {
double result = matrix.calculatePMC(entity);
response.add("PMC", result);
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
return new StringRepresentation(response.build().toString());
}
}
Modify your PMCMatrixDAOImpl in order to process your POJO:
public double calculatePMC(MyPojo pojo) {
(...)
}
Create a client that allows you to test your REST service:
public class PMCResourceMain {
public static void main(String[] args) {
// take into account the context-root, if exists, and path to your REST service
ClientResource resource = new ClientResource("http://<host>:<port>");
MyPojo myPojo = new MyPojo();
myPojo.setCampaingID(1);
myPojo.setClientID(1);
myPojo.setPmapID(1);
myPojo.setWard("1-Bedded (Private)");
myPojo.setAge(20);
myPojo.setAttr1("EXA1(A)");
myPojo.setAttr2("EO");
myPojo.setAttr3("11/02/2012");
myPojo.setAttr4("SIN");
myPojo.setAttr5("N");
myPojo.setAttr6("Y");
try {
resource.post(myPojo, MediaType.APPLICATION_JSON).write(System.out);
} catch (ResourceException | IOException e) {
e.printStackTrace();
}
}
}
Full Restlet documentation can be found here.
For the benefit of those who landed in the same situation as me, here's my solution:
Resource class
#Override
#Post("JSON")
public Representation post(Representation entity) throws ResourceException
{
PMCMatrixDAO matrix = new PMCMatrixDAOImpl();
JsonObjectBuilder response = Json.createObjectBuilder();
try {
String json = entity.getText(); // Get JSON input from client
Map<String, Object> map = JsonUtils.toMap(json); // Convert input into Map
double result = matrix.calculatePMC(map);
response.add("PMC", result);
} catch (IOException e) {
LOGGER.error(this.getClass() + " - IOException - " + e);
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
return new StringRepresentation(response.build().toString());
}
JSON conversion utility class
public class JsonUtils {
private static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class);
private JsonUtils() {
}
public static String toJson(Object object) {
String jsonString = null;
ObjectMapper mapper = new ObjectMapper();
try {
jsonString = mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
LOG.error(e.getMessage(), e);
}
return jsonString;
}
public static Map<String, Object> toMap(String jsonString) {
Map<String, Object> map = new ConcurrentHashMap<>();
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {
});
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
return map;
}
}
And the implementation class which handles all the processing
public class PMCMatrixDAOImpl implements PMCMatrixDAO
{
public double calculatePMC(Map<String, Object> map)
{
int campaignID = (int) map.get("campaignID");
int clientID = (int) map.get("clientID");
int pmapID = (int) map.get("pmapID");
String ward = (String) map.get("ward");
int age = (int) map.get("age");
String attr1 = (String) map.get("attr1");
String attr2 = (String) map.get("attr2");
String attr3 = (String) map.get("attr3");
String attr4 = (String) map.get("attr4");
String attr5 = (String) map.get("attr5");
String attr6 = (String) map.get("attr6");
// SQL processing
double dPMC = sqlQueryCall(...);
return dPMC;
}
}