I'm working in a project where after retrieving JSON from a URL, I need to manipulate the JSON file. I retrieved my JSON file from the following link:
http://api.openeventdatabase.org/event/b2e7df60-3f25-4d80-b7ac-cffc10dd5313
That JSON file contains information on a specific Service Station in France such as:
The Station Service details (steet,name,mark ...)
The Services (Washing,WC ....)
And the most importantly! The recent price of fuels
For that, I've tried to follow a solution given here at stackoverflow, by other user, to a similar problem. You can see:
Android JSON parsing of multiple JSONObjects inside JSONObject
Here is my code (full method):
#GET
#Path("/DecouvrirJSONInfo/{stationServiceInfo}")
public StationService DecouvrirJSON(#PathParam ("stationServiceInfo") String jsonString) throws JSONException
{
JSONObject myResponse = new JSONObject(jsonString);
String nom;
String carburantGazole, carburantSP95, carburantSP98, carburantGPL;
float prixCarburantGazole, prixCarburantSP95, prixSP98, prixGPL;
Date dtActGazole, dtActSP98, dtActSP95,dtActGPL;
StationService actuelStationService = new StationService();
Carburant carburant = new Carburant();
List<Carburant> carburants = new ArrayList<Carburant>();
try
{
//nom = myResponse.getString("nom");
Iterator<String> keysRoot = myResponse.keys();
while (keysRoot.hasNext())
{
String rootKey = keysRoot.next();
if(rootKey == "properties")
{
JSONObject innerZeroJObject = myResponse.getJSONObject(rootKey);
Iterator<String> keys = innerZeroJObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
//Log.v("**********", "**********");
//Log.v("category key", key);
if(key=="carburant")
{
JSONObject innerJObject = myResponse.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
if(innerKkey == "1") // gazole
{
JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
Iterator<String> innerIKeys = innerIIJObject.keys();
while( innerIKeys.hasNext() )
{
carburantGazole = innerIIJObject.getString("carburant");
dtActGazole = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse(innerIIJObject.getString("maj"));
prixCarburantGazole = Float.parseFloat( innerIIJObject.getString("prix"));
carburant.DefinirNomCarburant(carburantGazole);
carburant.DefinirPrixCarburant(prixCarburantGazole);
carburants.add(carburant);
carburant = new Carburant();
}
}
else if(innerKkey == "2") // Sp95
{
JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
Iterator<String> innerIKeys = innerIIJObject.keys();
while( innerIKeys.hasNext() )
{
carburantSP95 = innerIIJObject.getString("carburant");
dtActSP95 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse(innerIIJObject.getString("maj"));
prixCarburantSP95 = Float.parseFloat( innerIIJObject.getString("prix"));
carburant.DefinirNomCarburant(carburantSP95);
carburant.DefinirPrixCarburant(prixCarburantSP95);
carburants.add(carburant);
carburant = new Carburant();
}
}
else if(innerKkey == "3") // SP98
{
JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
Iterator<String> innerIKeys = innerIIJObject.keys();
while( innerIKeys.hasNext() )
{
carburantSP98 = innerIIJObject.getString("carburant");
dtActSP98 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse(innerIIJObject.getString("maj"));
prixSP98 = Float.parseFloat( innerIIJObject.getString("prix"));
carburant.DefinirNomCarburant(carburantSP98);
carburant.DefinirPrixCarburant(prixSP98);
carburants.add(carburant);
carburant = new Carburant();
}
}
//String value = innerJObject.getString(innerKkey);
//Log.v("key = "+key, "value = "+value);
}
}
}
}
}
//actuelStationService.DefinirNomStationService(nom);
actuelStationService.DefinirCarburants(carburants);
}
catch(Exception ex)
{
}
return actuelStationService;
}
Can you help me and find the error(s). Please see the first link, which contains the JSON response.
I would recommend using library like JsonPath to search through the json instead of iterating manually. If you can use JsonPath in your project, here is a way to do this:
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
public class SearchJson {
public static void main(String[] args) throws Exception {
URL url = new URL("http://api.openeventdatabase.org/event/b2e7df60-3f25-4d80-b7ac-cffc10dd5313");
URLConnection connection = url.openConnection();
String jsonString = toString(new InputStreamReader(connection.getInputStream()));
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonString);
Integer nbDesCarburants = (Integer) JsonPath.read(document, "$.properties.carburants.length()");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Carburant> carburants = new ArrayList<>();
for (int i = 0; i < nbDesCarburants; i++) {
Map<String, Object> carburantMap = (Map<String, Object>) JsonPath.read(document,
"$.properties.carburants[" + i + "]");
String nom = (String) carburantMap.get("carburant");
Date maj = simpleDateFormat.parse(carburantMap.get("maj").toString());
float prix = Float.parseFloat(carburantMap.get("prix").toString());
Carburant carburant = new Carburant(nom, maj, prix);
carburants.add(carburant);
}
for (Carburant carburant : carburants) {
System.out.println(carburant);
}
}
static class Carburant {
private final String nom;
private final Date date;
private final float prix;
public Carburant(String nom, Date date, float prix) {
super();
this.nom = nom;
this.date = date;
this.prix = prix;
}
#Override
public String toString() {
return "Carburant [nom=" + nom + ", date=" + date + ", prix=" + prix + "]";
}
}
public static String toString(InputStreamReader reader) throws IOException {
char[] charBuf = new char[1024];
int read = reader.read(charBuf, 0, 1024);
StringBuilder sb = new StringBuilder();
while (read != -1) {
sb.append(new String(charBuf));
charBuf = new char[1024];
read = reader.read(charBuf, 0, 1024);
}
sb.append(new String(charBuf));
return sb.toString();
}
}
To run the example, make sure you have JsonPath jar in your classpath or if you are using maven to build your project, add json-path in your dependencies.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.3.0</version>
</dependency>
Related
I am using JsonArray as input in my REST API. Here I attached my coding part.
After deployment I getting input value as null or internal server error or glass-fish error. Kindly suggest some ideas to resolve this issue.
I tried to change #Consumes(MediaType.APPLICATION_JSON) to #Consumes("application/json") and also command the #XmlRootElement annotation.
This is TransactionData.java class:
#Path("/CreditProcess")
public class TransactionData {
//private Object ipxml;
#POST
#Path("/SOHold")
//#Consumes("application/json")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public TransactionDataResponse Serv(TransactionDataRequest req) throws IOException, JPISException, Exception {
String Status = null, ErrorCode = null;
TransactionDataResponse ObjRes = new TransactionDataResponse();
CommonFunction ObjCF = new CommonFunction();
String SessionId = "";
boolean boolREADINI;
String Webservice = "Hold_Creation";
boolREADINI = ObjCF.ReadINIProperties();
String MISC_ID = "";
String PID = "", SaleOrder = "", Hold_Type = "", Hold_Status = "",
Approved_User = "", Date = "", Remarks = "", Hold_Desc = "", SO_COUNT = "", CH_COUNT = "", flag = "",WorkitemID="";
String Output_data = "", Input_data = "";
DMSXmlResponse Query_Response = null;
SessionId = ObjCF.ConnectCabinet(Webservice);
// PID = req.get();
ObjCF.ReportLog("Input_data request---" + req, Webservice);
JSONArray Data = new JSONArray();
try {
ObjCF.ReportLog("Before Check1---", Webservice);
Data = req.getData();
ObjCF.ReportLog("After Check2---"+Data, Webservice);
int size = Data.size();
for (int row = 0; row < size; row++) {
ObjCF.ReportLog("test1--", Webservice);
JSONObject obj;
HashMap<String, String> passedValues = (HashMap<String, String>) Data.get(row);
ObjCF.ReportLog("test2-- ", Webservice);
// ObjCF.ReportLog("test2--Data.get(i)" + Data.get(i), Webservice);
// obj = (JSONObject) Data.get(i);
for (Entry<String, String> mapTemp : passedValues.entrySet()) {
if (mapTemp.getKey().equalsIgnoreCase("SalesOrder")) {
SaleOrder = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + SaleOrder, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_Type")) {
Hold_Type = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Type" + Hold_Type, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status")) {
Hold_Status = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + Hold_Status, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Approved_User")) {
Approved_User = mapTemp.getValue();
ObjCF.ReportLog("json Approved_User" + Approved_User, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Date_Time")) {
Date = mapTemp.getValue();
ObjCF.ReportLog("json Date" + Date, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Remarks")) {
Remarks = mapTemp.getValue();
ObjCF.ReportLog("json Remarks" + Remarks, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status_Desc")) {
Hold_Desc = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Desc" + Hold_Desc, Webservice);
}
}
}
} catch(Exception e){
}
}
}
This is my TransactionDataRequest.java class:
import com.newgen.Utils.CommonFunction;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.json.simple.JSONArray;
#XmlRootElement
public class TransactionDataRequest {
private JSONArray Data;
CommonFunction ObjCF = new CommonFunction();
public JSONArray getData() {
ObjCF.ReportLog("Inside getData---", "Hold_Creation");
ObjCF.ReportLog("Inside getData return data---" + Data, "Hold_Creation");
return Data;
}
#XmlElement(name = "Data")
public void setData( JSONArray Data) {
ObjCF.ReportLog("Inside Data:---" + Data, "Hold_Creation");
this.Data = Data;
ObjCF.ReportLog("After this Data:---" + Data, "Hold_Creation");
}
}
I am new to the HTTP request in java. I have been trying to send an HTTP Post request to my NODE.JS server with the parameter key:12345. However, it doesn't send anything to my server. I tried tested my NOEDJS server to see if it worked in POSTMAN, and it did. So I am sure that this is something with the java that I made. I think a look at my code would help. Here it is down below.
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class ConnectionFactory {
private double API_VERSION = 0;
private String API = "";
private String METHOD = "POST";
private String USER_AGENT = "Mozilla/5.0";
private String TYPE = "application/x-www-form-urlencoded";
private String data = "";
private URL connection;
private HttpURLConnection finalConnection;
private HashMap<String, String> fields = new HashMap<String, String>();
public ConnectionFactory(String[] endpoint, String url, double version) {
this.API_VERSION = version;
this.API = url;
fields.put("version", String.valueOf(version));
for (int i = 0; i < endpoint.length; i++) {
String[] points = endpoint[i].split(";");
for (int f = 0; f < points.length; f++) {
fields.put(points[f].split(":")[0], points[f].split(":")[1]);
}
}
}
public String buildConnection() {
StringBuilder content = new StringBuilder();
if (!this.getEndpoints().equalsIgnoreCase("") && !this.getEndpoints().isEmpty()) {
String vars = "";
String vals = "";
try {
for (Map.Entry<String, String> entry: fields.entrySet()) {
vars = entry.getKey();
vals = entry.getValue();
data += ("&" + vars + "=" + vals);
}
if (data.startsWith("&")) {
data = data.replaceFirst("&", "");
}
connection = new URL(API);
BufferedReader reader = new BufferedReader(new InputStreamReader(readWithAccess(connection, data)));
String line;
while ((line = reader.readLine()) != null) {
content.append(line + "\n");
}
reader.close();
return content.toString();
} catch (Exception e) {
System.err.println(e.getMessage());
}
} else {
return null;
}
return null;
}
private InputStream readWithAccess(URL url, String data) {
try {
byte[] out = data.toString().getBytes();
finalConnection = (HttpURLConnection) url.openConnection();
finalConnection.setRequestMethod(METHOD);
finalConnection.setDoOutput(true);
finalConnection.addRequestProperty("User-Agent", USER_AGENT);
finalConnection.addRequestProperty("Content-Type", TYPE);
finalConnection.connect();
try {
OutputStream os = finalConnection.getOutputStream();
os.write(out);
} catch (Exception e) {
System.err.println(e.getMessage());
}
return finalConnection.getInputStream();
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
public String getApiVersion() {
return String.valueOf(API_VERSION);
}
public String getEndpoints() {
return fields.toString();
}
public String getEndpointValue(String key) {
return fields.get(key);
}
public void setUserAgent(String userAgent) {
this.USER_AGENT = userAgent;
}
public void setMethod(String method) {
this.METHOD = method;
}
public void setSubmissionType(String type) {
this.TYPE = type;
}
}
public class example {
public static void main(String[] args) {
double version = 0.1;
String url = "http://localhost:3000";
String[] fields = {
"key:12345"
};
ConnectionFactory connection = new ConnectionFactory(fields, url, version);
connection.setUserAgent("Mozilla/5.0");
String response = connection.buildConnection();
System.out.println(response);
}
}
Here is the code for my node.js server
var http = require('http');
var url = require('url');
var queryString = require('querystring')
var StringDecoder = require('string_decoder').StringDecoder;
var server = http.createServer(function(req, res) {
//parse the URL
var parsedURL = url.parse(req.url, true);
//get the path
var path = parsedURL.pathname;
var trimmedPath = path.replace(/^\/+|\/+$/g, '');
//queryString
var queryStringObject = parsedURL.query;
console.log(queryStringObject);
if (queryStringObject.key == 12345) {
console.log("true")
res.end("true")
} else {
console.log("failed")
res.end("false")
}
// var query = queryStringObject.split()
});
server.listen(3000, function() {
console.log("Listening on port 3000");
});
The is no problem with your java client
The problem is that you are sending the content of your POST request as ""application/x-www-form-urlencoded" and then in your nodeJS server you are reading it as a query string
Here is a correct example using ExpressJS :
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/test', function(req, res) {
var key = req.body.key;
if (key==12345)
res.send(true );
else
res.send(false);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject
my json string is
{
"type": "already_planted",
"crops": [
{
"crop_id": 1,
"crop_name": "apple",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "10"
},
{
"planted_by": "A person"
}
]
},
{
"created_id": "2017-01-30",
"questions": [
{
"plants": "15"
},
{
"planted_by": "B person"
}
]
}
]
},
{
"crop_id": 2,
"crop_name": "Cashew",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "11"
},
{
"planted_by": "c person"
}
]
}
]
}
]
}
First of all, you need to create the class that you are going to map JSON inside.
Fortunately, there is a website that can do it for you here
secondly, you can use google Gson library for easy mapping
1. add the dependency.
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
2. from your object to JSON.
MyData data =new MyData() ; //initialize the constructor
Gson gson = new Gson();
String Json = gson.toJson(data ); //see firstly above above
//now you have the json string do whatever.
3. from JSON to object .
String jsonString =doSthToGetJson(); //http request
MyData data =new MyData() ;
Gson gson = new Gson();
data= gson.fromJson(jsonString,MyData.class);
//now you have Pojo do whatever
for more information about gson see this tutorial.
If you use JsonObject, you can define your entity class as this:
public class Entity {
String type;
List<Crops> crops;
}
public class Crops {
long crop_id;
String crop_name;
List<CropDetail> crop_details;
}
public class CropDetail {
String created_id;
List<Question> questions;
}
public class Question {
int plants;
String planted_by;
}
public void convert(String json){
JsonObject jsonObject = new JsonObject(jsonstring);
Entity entity = new Entity();
entity.type = jsonObject.optString("type");
entity.crops = new ArrayList<>();
JsonArray arr = jsonObject.optJSONArray("crops");
for (int i = 0; i < arr.length(); i++) {
JSONObject crops = arr.optJSONObject(i);
Crops cps = new Crops();
cps.crop_id = crops.optLong("crop_id");
cps.crop_name = crops.optString("crop_name");
cps.crop_details = new ArrayList<>();
JsonArray details = crops.optJsonArray("crop_details");
// some other serialize codes
..........
}
}
So you can nested to convert your json string to an entity class.
Here is how I do it without any packages, this do the work for me for small use cases:
My modal class:
package prog.com.quizapp.models;
import org.json.JSONException;
import org.json.JSONObject;
public class Question {
private String question;
private String correct_answer;
private String answer_a;
private String answer_b;
private String answer_c;
private String answer_d;
public Question() {
}
public Question(String question, String answer_a, String answer_b, String answer_c, String answer_d, String correct_answer) {
this.question = question;
this.answer_a = answer_a;
this.answer_b = answer_b;
this.answer_c = answer_c;
this.answer_d = answer_d;
this.correct_answer = correct_answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getCorrect_answer() {
return correct_answer;
}
public void setCorrect_answer(String correct_answer) {
this.correct_answer = correct_answer;
}
public String getAnswer_a() {
return answer_a;
}
public void setAnswer_a(String answer_a) {
this.answer_a = answer_a;
}
public String getAnswer_b() {
return answer_b;
}
public void setAnswer_b(String answer_b) {
this.answer_b = answer_b;
}
public String getAnswer_c() {
return answer_c;
}
public void setAnswer_c(String answer_c) {
this.answer_c = answer_c;
}
public String getAnswer_d() {
return answer_d;
}
public void setAnswer_d(String answer_d) {
this.answer_d = answer_d;
}
#Override
public String toString() {
return "Question{" +
"question='" + question + '\'' +
", correct_answer='" + correct_answer + '\'' +
", answer_a='" + answer_a + '\'' +
", answer_b='" + answer_b + '\'' +
", answer_c='" + answer_c + '\'' +
", answer_d='" + answer_d + '\'' +
'}';
}
public static Question fromJson(JSONObject obj) throws JSONException {
return new Question(
obj.getString("question"),
obj.getString("answer_a"),
obj.getString("answer_b"),
obj.getString("answer_c"),
obj.getString("answer_d"),
obj.getString("correct_answer"));
}
}
And I have another class to get the json file from assets directory and mapped JsonObject to my model class Question:
package prog.com.quizapp.utils;
import android.content.Context;
import android.util.Log;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import prog.com.quizapp.models.Question;
public class JsonSqlQueryMapper {
private Context mContext;
public JsonSqlQueryMapper(Context context) {
this.mContext = context;
}
private static final String TAG = "JsonSqlQueryMapper";
public JSONObject loadJSONFromAsset() {
String json = null;
try {
InputStream is = mContext.getAssets().open("quiz_app.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
try {
JSONObject quizObject = new JSONObject(json).getJSONObject("quiz");
return quizObject;
} catch (Exception e) {
Log.d(TAG, "loadJSONFromAsset: " + e.getMessage());
return null;
}
}
public ArrayList<Question> generateInsertQueryForJsonObjects() {
ArrayList<Question> questions = new ArrayList<>();
JSONObject jsonObject = loadJSONFromAsset();
try {
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject value = jsonObject.getJSONObject(key);
Question question = Question.fromJson(value.getJSONObject("question_two"));
questions.add(question);
Log.d(TAG, "generateInsertQueryForJsonObjects: " + question.getAnswer_a());
}
} catch (Exception e) {
e.printStackTrace();
}
return questions;
}
}
And in my MainActivity -> onCreate:
JsonSqlQueryMapper mapper = new JsonSqlQueryMapper(MainActivity.this);
mapper.generateInsertQueryForJsonObjects();
To check that everything working as I want. Here is the json file if you want to check https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json
Regards!
[{"user_id":"5633795","username":"_Vorago_","count300":"203483","count100":"16021","count50":"1517","playcount":"1634","ranked_score":"179618425","total_score":"1394180836","pp_rank":"34054","level":"59.6052","pp_raw":"1723.43","accuracy":"96.77945709228516","count_rank_ss":"1","count_rank_s":"19","count_rank_a":"17","country":"US","events":[]}]
I'm trying to convert the JSON above with GSON but am running into errors.
package com.grapefruitcode.osu;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import com.google.gson.Gson;
public class Main {
static String ApiKey = "";
public static void main(String[]Args) throws Exception{
String json = readUrl("");
System.out.println(json);
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
System.out.println();
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
The url and api key are left blank for security reasons, the variables are filled when I run the code and the json is converted to a string properly. I've tested it already. If somebody could tell me what is causing the error that would be wonderful.
package com.grapefruitcode.osu;
public class User {
String user_id = "";
String username = "";
String count300 = "";
String count100= "";
}
In JSON
[ ... ] represents array
{ ... } represents object,
so [ {...} ] is array containing one object. Try using
Gson gson = new Gson();
User[] users = gson.fromJson(json, User[].class);
System.out.println(Arrays.toString(users));
//or since we know which object from array we want to print
System.out.println(users[0]);
Using RetroFit 2 Solution
interface APIInterface {
#POST("GetDataController/GetData")
Call<GeoEvent> getGeofanceRecord(#Body GeoEvent geoEvent);
}
APIInterface apiInterface; // Declare Globally
apiInterface = APIClient.getClient().create(APIInterface.class);
final GeoEvent geoEvent = new GeoEvent(userId);
Call<GeoEvent> call = apiInterface.getGeofanceRecord(geoEvent);
call.enqueue(new Callback<GeoEvent>() {
#Override
public void onResponse(Call<GeoEvent> call, Response<GeoEvent> response) {
GeoEvent geoEvent1 = response.body();
// Log.e("keshav","Location -> " +geoEvent1.responseMessage);
List<GeoEvent.GeoEvents> geoEventsList = geoEvent1.Table; // Array Naame
List<GeoEvent.GeoEvents> geoEventsArrayList = new ArrayList<GeoEvent.GeoEvents>();
geoEventsArrayList.addAll(geoEventsList);
for (GeoEvent.GeoEvents geoEvents : geoEventsList) {
Log.e("keshav", "Location -> " + geoEvents.Location);
Log.e("keshav", "DateTime -> " + geoEvents.DateTime);
}
if (geoEventsArrayList != null) {
adapter.clear();
adapter.addAll(geoEventsArrayList);
adapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<GeoEvent> call, Throwable t) {
call.cancel();
}
});
Your Pojo Class Like This
package pojos;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class GeoEvent {
public String userId;
public GeoEvent(String userId){
this.userId= userId;
}
public List<GeoEvents> Table = new ArrayList<>();
public class GeoEvents {
#SerializedName("Location")
public String Location;
#SerializedName("DateTime")
public String DateTime;
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getDateTime() {
return DateTime;
}
public void setDateTime(String dateTime) {
DateTime = dateTime;
}
}
}
I'm creating an employee time clock for a java class. This portion of my program is for reporting an individual's time, and reporting all employees time. My code works well for the individual, but I'm having trouble converting it to work for all employees. Should I try looping through the whole file and retrieving as it goes? The information being inside a control statement is causing me problems. Also, to only look at a two-week period, would using calendar and date -14 days be a good way to accomplish that?
Any feedback on how to proceed appreciated.
package PunchinPunchout;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class IDchecker {
private static BufferedReader br;
private static BufferedReader br1;
static int total;
static int total1;
public static void main(String args[]) throws IOException {
getsubject();
}
public static void getsubject() throws FileNotFoundException, IOException {
ArrayList<Integer> totalhours = new ArrayList<>();
br = new BufferedReader(new FileReader("timeclock1.txt"));
br1 = new BufferedReader(new FileReader("newemployee8.txt"));
String line = "";
String line1 = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter an employee ID number: ");
String idnumber = sc.next();//read the choice
sc.nextLine();// discard any other data entered on the line
while ((line1 = br1.readLine()) != null) {
if (line1.contains(idnumber)) {
System.out.println("Employee Name & ID ");
System.out.println(line1);
}
}
while ((line = br.readLine()) != null) {
if (line.contains(idnumber + " ") && line.contains("in")) {
System.out.println();
System.out.println(" Date Time ID Punched");
System.out.println(line);
String regexp = "[\\s:\\n]+"; // these are my delimiters
String[] tokens; // here i will save tokens
for (int i = 0; i < 1; i++) {
tokens = line.split(regexp);
total = Integer.parseInt(tokens[1]);
}
} else if (line.contains(idnumber + " ") && line.contains("out")) {
System.out.println(line);
String regexp = "[\\s:\\n]+";
String[] tokens;
for (int i = 0; i < 1; i++) {
tokens = line.split(regexp);
total1 = Integer.parseInt(tokens[1]);
System.out.print("Total hours for " + tokens[0] + " are: ");
}
int dailytotal = total1 - total;
System.out.println(dailytotal + " hours");
totalhours.add(dailytotal);
}
}
System.out.println();
int sum = totalhours.stream().mapToInt(Integer::intValue).sum();
System.out.println("The total hours for the last two weeks is " + sum + " hours.");
}
}
*Output from timeclock1.txt
05/05/2014 05:00:00 508 in
05/05/2014 09:00:00 508 out
05/05/2014 03:00:00 509 in
05/05/2014 09:00:00 509 out
05/05/2014 03:00:00 510 in
05/05/2014 08:00:00 510 out
05/05/2014 08:00:00 511 in
05/05/2014 10:00:00 511 out
*Output from newemployee8.txt
james bush 10
bobby bush 11
john hunt 12
mick jag 13
jacob sanchez 14
Okay, this a little of an over the top example, but it highlights the power of a OO language like Java...
There are a number of ways that this might be achieved, based on your requirements. I've made a few assumptions (like a in is followed by an out for the same employee), but the basic gist is demonstrated.
The intention is centralise some of the functionality into re-usable and manageable blocks, reducing the code duplication. Access to the data is simplified and because it's done in memory, is faster...
To start with, you will want to create object representations of the employee and time clock data, this will make it easier to manager...
Employee Example
public class Employee {
private final int id;
private final String name;
public Employee(String text) {
String[] parts = text.split(" ");
id = Integer.parseInt(parts[2]);
name = parts[0] + " " + parts[1];
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
TimeClockEntry example
public class TimeClockEntry {
private Date inTime;
private Date outTime;
private int employeeID;
public TimeClockEntry(String text) throws ParseException {
String parts[] = text.split(" ");
employeeID = Integer.parseInt(parts[2]);
setClockTimeFrom(text);
}
public void setClockTimeFrom(String text) throws ParseException {
String parts[] = text.split(" ");
if ("in".equalsIgnoreCase(parts[3])) {
inTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
} else if ("out".equalsIgnoreCase(parts[3])) {
outTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
}
}
public int getEmployeeID() {
return employeeID;
}
public Date getInTime() {
return inTime;
}
public Date getOutTime() {
return outTime;
}
}
Now, we need some kind of "manager" to manage the details of these two classes, these managers should provide access methods which allow use to retrieve information that they manage. These managers will also be responsible for loading the data from the files...
EmployeeManager example
public class EmployeeManager {
private Map<Integer, Employee> employees;
public EmployeeManager() throws IOException {
employees = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("NewEmployee8.txt")))) {
String text = null;
while ((text = br.readLine()) != null) {
Employee emp = new Employee(text);
employees.put(emp.getId(), emp);
}
}
}
public List<Employee> getEmployees() {
return Collections.unmodifiableList(new ArrayList<Employee>(employees.values()));
}
public Employee getEmployee(int id) {
return employees.get(id);
}
}
TimeClockManager example
public class TimeClockManager {
private Map<Integer, List<TimeClockEntry>> timeClockEntries;
public TimeClockManager() throws IOException, ParseException {
timeClockEntries = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("TimeClock1.txt")))) {
String text = null;
TimeClockEntry entry = null;
int line = 0;
while ((text = br.readLine()) != null) {
if (line % 2 == 0) {
entry = new TimeClockEntry(text);
} else {
entry.setClockTimeFrom(text);
List<TimeClockEntry> empEntries = timeClockEntries.get(entry.getEmployeeID());
if (empEntries == null) {
empEntries = new ArrayList<>(25);
timeClockEntries.put(entry.getEmployeeID(), empEntries);
}
empEntries.add(entry);
}
line++;
}
}
}
public List<TimeClockEntry> getByEmployee(Employee emp) {
List<TimeClockEntry> list = timeClockEntries.get(emp.getId());
list = list == null ? new ArrayList<>() : list;
return Collections.unmodifiableList(list);
}
}
Now, internally, these managers are managing the data through the use of Maps, to make it easier to find data, specifically, this is most keyed on the employee's id
Now, once we have these, we can ask for information from the as we please...
public Report() {
try {
EmployeeManager empManager = new EmployeeManager();
TimeClockManager timeClockManager = new TimeClockManager();
for (Employee emp : empManager.getEmployees()) {
System.out.println("[" + emp.getId() + "] " + emp.getName());
for (TimeClockEntry tce : timeClockManager.getByEmployee(emp)) {
System.out.println(" "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getInTime())
+ " to "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getOutTime()));
}
}
} catch (IOException | ParseException exp) {
exp.printStackTrace();
}
}
Another approach would be to incorporate both managers into a single class. The basic idea would be to load the employee and time clock data, the time clock data would become a property of the Employee and you could simply be able to access it directly.
This is a slightly more elegant solution, as you have all the data contained within a single construct, but might not meet your needs
Fully runnable example
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oracle.jrockit.jfr.parser.ParseException;
public class Report {
public static void main(String[] args) {
new Report();
}
public Report() {
try {
EmployeeManager empManager = new EmployeeManager();
TimeClockManager timeClockManager = new TimeClockManager();
for (Employee emp : empManager.getEmployees()) {
System.out.println("[" + emp.getId() + "] " + emp.getName());
for (TimeClockEntry tce : timeClockManager.getByEmployee(emp)) {
System.out.println(" "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getInTime())
+ " to "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getOutTime()));
}
}
} catch (IOException | ParseException exp) {
exp.printStackTrace();
}
}
public class EmployeeManager {
private Map<Integer, Employee> employees;
public EmployeeManager() throws IOException {
employees = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("NewEmployee8.txt")))) {
String text = null;
while ((text = br.readLine()) != null) {
if (!text.trim().isEmpty()) {
Employee emp = new Employee(text);
employees.put(emp.getId(), emp);
}
}
}
}
public List<Employee> getEmployees() {
return Collections.unmodifiableList(new ArrayList<Employee>(employees.values()));
}
public Employee getEmployee(int id) {
return employees.get(id);
}
}
public class TimeClockManager {
private Map<Integer, List<TimeClockEntry>> timeClockEntries;
public TimeClockManager() throws IOException, ParseException {
timeClockEntries = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("TimeClock1.txt")))) {
String text = null;
TimeClockEntry entry = null;
int line = 0;
while ((text = br.readLine()) != null) {
if (!text.trim().isEmpty()) {
if (line % 2 == 0) {
entry = new TimeClockEntry(text);
} else {
entry.setClockTimeFrom(text);
List<TimeClockEntry> empEntries = timeClockEntries.get(entry.getEmployeeID());
if (empEntries == null) {
empEntries = new ArrayList<>(25);
timeClockEntries.put(entry.getEmployeeID(), empEntries);
}
empEntries.add(entry);
}
line++;
}
}
}
}
public List<TimeClockEntry> getByEmployee(Employee emp) {
List<TimeClockEntry> list = timeClockEntries.get(emp.getId());
list = list == null ? new ArrayList<>() : list;
return Collections.unmodifiableList(list);
}
}
public class Employee {
private final int id;
private final String name;
public Employee(String text) {
System.out.println("[" + text + "]");
for (char c : text.toCharArray()) {
System.out.print((int) c + ",");
}
System.out.println("");
String[] parts = text.split("\\s+");
id = Integer.parseInt(parts[2]);
name = parts[0] + " " + parts[1];
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
public static final SimpleDateFormat CLOCK_DATE_TIME_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public static final SimpleDateFormat CLOCK_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
public class TimeClockEntry {
private Date inTime;
private Date outTime;
private int employeeID;
public TimeClockEntry(String text) throws ParseException {
System.out.println("[" + text + "]");
for (char c : text.toCharArray()) {
System.out.print((int) c + ",");
}
System.out.println("");
String parts[] = text.split("\\s+");
employeeID = Integer.parseInt(parts[2]);
setClockTimeFrom(text);
}
public void setClockTimeFrom(String text) throws ParseException {
String parts[] = text.split("\\s+");
if ("in".equalsIgnoreCase(parts[3])) {
inTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
} else if ("out".equalsIgnoreCase(parts[3])) {
outTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
}
}
public int getEmployeeID() {
return employeeID;
}
public Date getInTime() {
return inTime;
}
public Date getOutTime() {
return outTime;
}
}
}