URLEncoder to search with multiple words - json

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.

Related

MySQL javafx search like

I'm losing my mind over this. Maybe its something very simple that I miss. But I can't seem to get it work. I received help from other users and edited my code. But really can't get it to work.
This is my table in my database
+----------------+-----------------------+---------------------+
| colID | colTitle | colKeywords |
+----------------+-----------------------+---------------------+
| 1 | Jumanji | comedy adventure |
| 2 | Moana | adventure animation |
| 3 | Shawshank Redemption | drama tearjerker |
| 4 | Avengers | action |
+----------------+-----------------------+---------------------+
+-----------------------------+ +---------+
Search: | adventure and action movies | |button GO|
+-----------------------------+ +---------+
What I want to do is if I type "adventure and action movies" in the textfield, and after I hit the button go, the result in the tableview should be:
Jumanji
Moana
Avengers
My updated code:
public class UserMainPageController implements Initializable {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
#FXML
private TableView table_title;
#FXML
private TableColumn titleCol;
#FXML
private TextField txt_search;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void logOut(ActionEvent event) throws IOException{
Main.showUserLogin();
}
#FXML
private void goSearch(ActionEvent event) throws IOException, SQLException{
try{
conn = SqlConnection.ConnectDB();
String criteria = txt_search.getText();
if (criteria.trim().length() == 0) { return; }
String[] arryCriterion = criteria.split(" ");
List<String> results = new ArrayList<>();
for (int i = 0; i < arryCriterion.length; i++) {
List<String> text = populateField(arryCriterion[i], conn);
results.addAll(text);
}
ObservableList<String> observableList = FXCollections.observableList(results);
table_title.setItems(observableList);
}finally{
conn.close();
}
}
private List<String> populateField(String s, Connection conn) throws SQLException{
List<String> myList = new ArrayList<>();
String sql = "SELECT * FROM table_entry WHERE colTitle LIKE ? ";
pst=conn.prepareStatement(sql);
pst.setString(1, "%" + s + "%");
rs = pst.executeQuery();
while (rs.next()) {
myList.add(rs.getString("colTitle"));
}
return myList;
}
}
If I press the search button, nothing seems to appear in the tableview
Basically, my approach is similar to what #James_D is suggesting. First get all the data from the Database. Then filter the data using Java.
In my Database, I use Unicode Character INFORMATION SEPARATOR THREE (U+001D) between each keyword. Example: comedy↔adventure. I do this so that I can get each keyword using String.split().
In the app, I use a FilteredList to filter the TableView. If a DB(Database) entry contains at least one of the keywords, That entry will be shown. !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor); handles this.
Also, I have created a Tag class. This helps me keep up with things. These Tags look terrible, but you can beautify them using ideas from here.
Code:
Main:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private final TableView<Movie> table = new TableView<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setWidth(450);
stage.setHeight(550);
TableColumn colID = new TableColumn("ID");
colID.setMinWidth(100);
colID.setCellValueFactory(new PropertyValueFactory<>("colID"));
TableColumn colTitle = new TableColumn("Title");
colTitle.setMinWidth(100);
colTitle.setCellValueFactory(new PropertyValueFactory<>("colTitle"));
TableColumn colKeywords = new TableColumn("Keywords");
colKeywords.setMinWidth(200);
colKeywords.setCellValueFactory(new PropertyValueFactory<>("colKeywords"));
DBHandler dbhandler = new DBHandler();
FilteredList<Movie> filteredList = new FilteredList(dbhandler.getDBMovies());
table.setItems(filteredList);
table.getColumns().addAll(colID, colTitle, colKeywords);
FlowPane flowPane = new FlowPane();
TextField searchField = new TextField();
searchField.setOnAction(event -> {
List<String> searchingFor = new ArrayList();
Tag tempTag = new Tag(searchField.getText());
tempTag.getCloseButton().setOnAction((actionEvent) -> {
flowPane.getChildren().remove(tempTag);
if(flowPane.getChildren().isEmpty())
{
filteredList.setPredicate(null);
}
else{
filteredList.setPredicate((t) -> {
return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
});
}
});
flowPane.getChildren().add(tempTag);
for(Node node : flowPane.getChildren())
{
searchingFor.add(((Tag)node).getText());
}
filteredList.setPredicate((t) -> {
return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
});
searchField.clear();
});
HBox hbox = new HBox(searchField, flowPane);
final VBox vbox = new VBox(table, hbox);
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
}
Movie Class:
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author Sedrick
*/
public class Movie {
private static final String INFORMATION_SEPARATOR_THREE = "\u001D";
private final IntegerProperty colID = new SimpleIntegerProperty();
private final StringProperty colTitle = new SimpleStringProperty();
private final StringProperty colKeywords = new SimpleStringProperty();
public Movie(int colID, String colTitle, String colKeywords)
{
this.colID.set(colID);
this.colTitle.set(colTitle);
this.colKeywords.set(colKeywords);
}
public void setColID(int colID)
{
this.colID.set(colID);
}
public int getColID()
{
return this.colID.get();
}
public void setColTitle(String colTitle)
{
this.colTitle.set(colTitle);
}
public String getColTitle()
{
return this.colTitle.get();
}
public void setColID(String colKeywords)
{
this.colKeywords.set(colKeywords);
}
public String getColKeywords()
{
return this.colKeywords.get();
}
//Utility Methods
//Converts a String of keywords to a list<String> of keywords
public static List<String> KeywordsStringToList(String keywords)
{
String[] keywordsArray = keywords.split(INFORMATION_SEPARATOR_THREE);
List<String> keywordsList = new ArrayList();
for(String entry : keywordsArray)
{
keywordsList.add(entry);
}
return keywordsList;
}
//Convert a List<String> of keywords to a String of keywords
public static String keywordsListToString(List<String> keywords)
{
return String.join(INFORMATION_SEPARATOR_THREE, keywords);
}
}
Database Handler Class: This example uses an SQLite DB
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* #author Sedrick
*/
public class DBHandler {
Connection connection;
public DBHandler()
{
try
{
connection = DriverManager.getConnection("jdbc:sqlite:movie.db");
System.out.println("connected to db!");
} catch (SQLException ex)
{
Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ObservableList<Movie> getDBMovies()
{
String query = "SELECT * FROM MovieInfo";
ObservableList<Movie> movies = FXCollections.observableArrayList();
try(Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(query))
{
while(result.next())
{
Movie movie = new Movie(result.getInt("id"), result.getString("title"), result.getString("keywords"));
movies.add(movie);
}
}
catch (SQLException ex) {
Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return movies;
}
}
Tag Class:
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
/**
*
* #author Sedrick
*/
final public class Tag extends HBox{
final private Label keyword;
final private Button closeButton;
public Tag(String keyword) {
this.keyword = new Label(keyword);
closeButton = new Button("x");
this.getChildren().addAll(this.keyword, closeButton);
}
public String getText()
{
return keyword.getText();
}
Button getCloseButton()
{
return closeButton;
}
}
Full Code including DB on GitHub

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
}

JSON parse to populate listview Android Studio

I am pulling my hair out over this. After numerous tutorials, I thought I found the perfect one (7th to be exact. But after following the tutorial, I found out that JSONparse is deprecated. Can someone please give me a solution for this. I just want to read an array from the url and populate a listview.
The array is:
{ "lotInfo":[{"lot":"A","spaces":"198","rates":"3.25"},
{"lot":"B","spaces":"165","rates":"7.50"}]}
MainActivity.Java:
package com.example.sahan.wtf;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private Context context;
private static String url = "http://192.168.0.199/get_info.php";
private static final String lot = "lot";
private static final String spaces = "spaces";
private static final String rates = "rates";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(ListActivity activity) {
Log.i("1", "Called");
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { lot, spaces, rates }, new int[] { R.id.lot, R.id.spaces, R.id.rates });
setListAdapter(adapter);
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vlot = c.getString(lot);
String vspaces = c.getString(spaces);
String vrates = c.getString(rates);
HashMap<String, String> map = new HashMap<String, String>();
map.put(lot, vlot);
map.put(spaces, vspaces);
map.put(rates, vrates);
jsonlist.add(map);
} catch (JSONException e)
{
e.printStackTrace();
}
}
return null;
}
}
}
JSONParser.Java:
package com.example.sahan.wtf;
import android.util.Log;
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.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("Error....", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return array;
}
}
The error I get is:
Error:(74, 13) error: cannot find symbol class JSONParse
It seems that you have a typo, instead of:
JSONParse jParser = new JSONParser();
Should be:
JSONParser jParser = new JSONParser();

Can't parse JSON because of recursive relationships when using #RelatedToVia

I am new to Neo4j and I want to connect a node (Person) with a node (Asset) but also, store the time that this connection has been created. I figured out that I have to use #RelatedtoVia annotation. I have followed the Spring cineasts tutorial ([https://github.com/spring-projects/spring-data-neo4j/tree/master/spring-data-neo4j-examples/cineasts][1] ) Although, everything works fine as far as the tests and the database population are concerned, I get weird results at the REST service. Here is my code:
Node Person
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import org.springframework.data.neo4j.template.Neo4jOperations;
import java.util.*;
#NodeEntity
public class Person {
#GraphId
Long id;
#Indexed
private String displayName;
#Indexed(unique = true, failOnDuplicate = true)
private Long personId;
private String firstName;
private String lastName;
private Date birthday;
private String aboutMe;
private String thumbnailURL;
private String email;
private enum gendertypes {male, female, other};
private gendertypes gender;
private String[] languages;
private boolean active;
public static final String CONSUMED = "CONSUMED";
//empty & full constructor
//getters&setters
#RelatedToVia(type = "CONSUMED", elementClass = ConsumedDate.class)
#Fetch
Iterable<ConsumedDate> consumedDates;
public ConsumedDate consumedDate(Neo4jOperations template, Asset asset, Date timestamp) {
final ConsumedDate consumedDate = template.createRelationshipBetween(this, asset, ConsumedDate.class, CONSUMED, false).consumedDate(timestamp);
return template.save(consumedDate);
}
public Collection<ConsumedDate> getConsumedDates() {
return IteratorUtil.asCollection(consumedDates);
}
}
Node Asset
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import static org.neo4j.graphdb.Direction.INCOMING;
#NodeEntity
public class Asset {
#GraphId
private Long id;
#Indexed(unique=true, failOnDuplicate = true)
private Long assetId;
private String description;
private String type;
private String[] tags;
public Asset() {}
public Asset(Long assetId, String description, String type, String[] tags) {
this.assetId = assetId;
this.description = description;
this.type = type;
this.tags = tags;
}
public Long getAssetId() {return assetId; }
public void setAssetId(Long assetId) {
this.assetId = assetId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getTags() {
return tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
#RelatedTo(type = "CONSUMED", direction = INCOMING)
Set<Person> persons;
#RelatedToVia(type="CONSUMED", elementClass=ConsumedDate.class, direction=INCOMING)
#Fetch
Iterable<ConsumedDate> consumedDates;
public Collection<Person> getPersons() {
return persons;
}
public Collection<ConsumedDate> getConsumedDates() {
Iterable<ConsumedDate> allConsumedDates = consumedDates;
return allConsumedDates == null ? Collections.<ConsumedDate>emptyList() : IteratorUtil.asCollection(allConsumedDates);
}
#Override
public String toString() {
return "An asset with ID " + assetId + " description " + description + " type " + type;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Asset asset = (Asset) o;
if (id == null) return super.equals(o);
return id.equals(asset.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Relationship Entity ConsumedDate
import org.springframework.data.neo4j.annotation.EndNode;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.RelationshipEntity;
import org.springframework.data.neo4j.annotation.StartNode;
import java.util.Date;
#RelationshipEntity(type = "CONSUMED")
public class ConsumedDate {
#GraphId
Long id;
#EndNode
Asset asset;
#StartNode
Person person;
Date timestamp;
public ConsumedDate consumedDate(Date timestamp){
this.timestamp=timestamp;
return this;
}
public Asset getAsset() {
return asset;
}
public Person getPerson() {
return person;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConsumedDate consumedDate = (ConsumedDate) o;
if (id == null) return super.equals(o);
return id.equals(consumedDate.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Controller
import gr.ntua.sam.context.neo4j.AssetRepository;
import gr.ntua.sam.context.neo4j.LocationRepository;
import gr.ntua.sam.context.neo4j.PersonRepository;
import gr.ntua.sam.context.resources.*;
import com.wordnik.swagger.annotations.ApiOperation;
import org.neo4j.graphdb.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.*;
import java.util.List;
#RestController
#Configuration
#EnableNeo4jRepositories
public class ContextController {
#Autowired
Neo4jTemplate template;
#Autowired
AssetRepository assetRepository;
#Autowired
PersonRepository personRepository;
#ApiOperation(value = "Show the available assets", response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.GET)
public ResponseEntity<List<Asset>> getAssets() throws NotFoundException {
List<Asset> results = assetRepository.all();
return new ResponseEntity<List<Asset>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Create a new asset",response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Asset> saveAsset(#RequestBody Asset asset) {
Asset savedAsset = assetRepository.save(asset);
return new ResponseEntity<Asset>(savedAsset, HttpStatus.CREATED);
}
//Persons
#ApiOperation(value = "Get a list of all the available Persons")
#RequestMapping(value = "/person", method = RequestMethod.GET)
public ResponseEntity<List<Person>> getPersons() throws ParseException {
List<Person> results = personRepository.all();
return new ResponseEntity<List<Person>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Creates a new Person node to store information about a user", response = Person.class)
#RequestMapping(value = "/person", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Person> savePerson(#RequestBody Person person) {
Person savedPerson = personRepository.save(person);
return new ResponseEntity<Person>(savedPerson, HttpStatus.CREATED);
}
#ApiOperation(value = "Creates relationship between a Person and an Asset")
#RequestMapping(value = "/person/{personId}/consumes/", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> consumes(#PathVariable("personId") Long personId, #RequestBody LinkedAsset linkedAsset) {
Person person = personRepository.findByPersonId(personId);
List<Long> assetIds = linkedAsset.getAssetIDs();
for (Long assetId : assetIds) {
Asset currentAsset = assetRepository.findByAssetId(assetId);
Date date= linkedAsset.getTimestamp();
ConsumedDate consumedDate= person.consumedDate(template,currentAsset,date);
template.save(consumedDate);
}
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
The problem is that when I create a relationship between a Person and an Asset, along with a timestamp (I have created the class LinkedAsset which serves as a JSON input model and has nothing to do with Neo4j) and then try to get through REST the person or the asset, all I get is something definitely not JSON with the person or the asset appearing infinite times. Is there a way to face this problem?
Thank you in advance!

fetching data json to my list view

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...