I have a problem with my adapter. I already succeeded to display some informations from my JSON (codeLieu and libelle) that looks like this:
[
{
"codeLieu": "OTAG",
"libelle": "50 Otages",
"distance": null,
"ligne": [
{
"numLigne": "2"
},
{
"numLigne": "C2"
},
{
"numLigne": "12"
},
{
"numLigne": "23"
}
]
},
...
]
Here is my model:
package material.romain.com.projentreprise.Adapter;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class Response implements Serializable{
private String codeLieu;
private String libelle;
private String distance;
private List<LigneEntities> ligne;
public String getCode() {
return codeLieu;
}
public void setCode(String codeLieu) {
this.codeLieu = codeLieu;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public List<LigneEntities> getLigne() {return ligne;}
public void setLigne(List<LigneEntities> ligne) {
this.ligne = ligne;
}
public static class LigneEntities {
private String numLigne;
public String getLigne() {
return numLigne;
}
public void setLigne(String numLigne) {
this.numLigne = numLigne;
}
}
}
And finally this is my adapter :
package material.romain.com.projentreprise.Adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.iconics.IconicsDrawable;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import material.romain.com.projentreprise.R;
import material.romain.com.projentreprise.Util.CircularTextView;
import material.romain.com.projentreprise.Util.ColorLigne;
public class ListAdapter extends BaseAdapter implements Filterable {
private ArrayList<Response> arret;
private Context context;
private LayoutInflater inflater;
private MyFilter mFilter;
private ArrayList<Response> mSearchArret;
public ListAdapter(Context mContext, ArrayList<Response> mArretItem) {
this.context = mContext;
this.arret = mArretItem;
this.mSearchArret = mArretItem;
getFilter();
}
#Override
public int getCount() {
return mSearchArret.size();
}
#Override
public Object getItem(int position) {
return mSearchArret.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Response item = (Response) getItem(position);
ColorLigne.ViewHolder holder = null;
if (convertView == null) {
holder = new ColorLigne.ViewHolder();
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.each_list_item, parent, false);
holder.circleImage = (CircleImageView) convertView.findViewById(R.id.circleView);
holder.textArret = (TextView) convertView.findViewById(R.id.tvListArret);
holder.circle = (CircularTextView) convertView.findViewById(R.id.tvArretColor);
convertView.setTag(holder);
} else {
holder = (ColorLigne.ViewHolder) convertView.getTag();
}
Drawable color = new ColorDrawable(ContextCompat.getColor(context, R.color.tanVert));
Drawable image = new IconicsDrawable(context).icon(FontAwesome.Icon.faw_bus).color(Color.WHITE).sizeDp(48).paddingDp(10);
LayerDrawable ld = new LayerDrawable(new Drawable[]{color, image});
holder.circleImage.setImageDrawable(ld);
holder.textArret.setText(item.getLibelle());
return convertView;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyFilter();
}
return mFilter;
}
class MyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (prefix != null && prefix.length() > 0) {
ArrayList<Response> tempList = new ArrayList<>();
for (Response value : arret) {
if (value.getLibelle().toLowerCase().contains(prefix.toString().toLowerCase())) {
tempList.add(value);
}
}
results.count = tempList.size();
results.values = tempList;
} else {
results.count = arret.size();
results.values = arret;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
try {
mSearchArret = (ArrayList<Response>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And I would like to get strings from "ligne" but it's in a list and I don't know how to access it. My goal is to put the strings into a circleTextView.
Edit:
I tried this in getView method
Response item = getItem(position);
for(Response value: arret){
value = item;
String ligneItem = value.getLigne().toString();
ColorLigne.setColorLigne(ligneItem, holder, context);
holder.circle.setText(ligneItem);
holder.circle.setStrokeWidth(0);
}
Add below method to your Response.java
public String getItems() {
StringBuilder builder = new StringBuilder();
for (LigneEntities entity : getLigne()) { //loop through every item from the list
builder.append(entity.getLigne() + ","); //add to StringBuilder
}
builder.replace(builder.length() - 1, builder.length(), "");//remove last ,(semicolon)
return builder.toString();
}
setting to your CircleTextView
holder.circle.setText(item.getItems());
Related
The result coming from an external API as..
BIBREF are dynamic, the we do not know how will be fetched
The index is appended to the name "BIBREF+number"
"bib_entries": {
"BIBREF0": {
"ref_id": <str>,
"title": <str>,
},
"BIBREF1": {
"ref_id": <str>,
"title": <str>,
},
...
...
"BIBREF25": {}
},
Defined a pojo as..
public class BibEntries {
private BibRef bibRef;
# ...getters/setters
public class BibRef {
private String ref_id;
private String title;
# ...getters/setters
}
}
Defined the class as:
JsonObject bibEntriesObject = jsonObject.get("bib_entries").getAsJsonObject();
BibEntries bibEntries = new Gson().fromJson(bibEntriesObject, BibEntries.class);
Learning GSON and using GenericTypes seemed confusing. How can i update the above code to read the dynamic objects (using gson 2.8.6)?
With some help from my colleague, here's the solution
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static final Gson gson = new
GsonBuilder().serializeNulls().setPrettyPrinting().create();
public static void main(String[] args) {
// Original Json Input
String jsonRequest = "{ \"bib_entries\": { \"BIBREF0\": { \"ref_id\": \"One\", \"title\": \"two\"},"
+ "\"BIBREF1\": { \"ref_id\": \"three\", \"title\": \"four\"} } }";
//Convert string to JsonObject
JsonObject convertedObject = new Gson().fromJson(jsonRequest, JsonObject.class);
JsonObject object = convertedObject.get("bib_entries").getAsJsonObject();
//Init Class
BibEntries bibEntries = new BibEntries();
List<BibEntries.Bibref> list = new ArrayList<>();
//Mapping the object to class
object.keySet().stream().forEach((key) -> {
// We can add more here..
BibEntries.Bibref bibref = gson.fromJson(object.get(key), BibEntries.Bibref.class);
list.add(bibref);
bibEntries.setListBibref(list);
});
//Original
System.out.println(convertedObject);
// Print the final result
System.out.println(gson.toJson(bibEntries));
}
public static class BibEntries {
List<Bibref> listBibref;
public static class Bibref {
#SerializedName("ref_id")
private String refId;
#SerializedName("title")
private String title;
public String getRefId() {
return refId;
}
public void setRefId(final String refId) {
this.refId = refId;
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
}
public List<Bibref> getListBibref() {
return listBibref;
}
public void setListBibref(final List<Bibref> listBibref) {
this.listBibref = listBibref;
}
}
}
I am trying to expose the Id of my domain on the Json response using Spring Data Rest, besides getting it on the self object. I try what I saw on the internet but it is not working. I am using Spring Boot and this is my starting class and my config class for exposing the Id.
package com.desingfreed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.designfreed")
public class GaliasBackendApplication {
public static void main(String[] args) {
SpringApplication.run(GaliasBackendApplication.class, args);
}
}
package com.desingfreed.config;
import com.desingfreed.domain.Articulo;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.stereotype.Component;
#Component
public class ConfigurationRest extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Articulo.class);
}
}
package com.desingfreed.repositories;
import com.desingfreed.domain.Articulo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "articulos", path = "articulos")
public interface ArticuloRepository extends CrudRepository<Articulo, Long> {
}
package com.desingfreed.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "STA11")
public class Articulo {
#Id
#GeneratedValue
#Column(name = "ID_STA11")
private Long id;
#Column(name = "COD_ARTICU")
private String codigo;
#Column(name = "DESCRIPCIO")
private String descripcion;
// #OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "articulo")
// private List<Precio> precios = new ArrayList<>();
public Articulo() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
// public List<Precio> getPrecios() {
// return precios;
// }
//
// public void setPrecios(List<Precio> precios) {
// this.precios = precios;
// }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Articulo articulo = (Articulo) o;
if (id != null ? !id.equals(articulo.id) : articulo.id != null) return false;
if (codigo != null ? !codigo.equals(articulo.codigo) : articulo.codigo != null) return false;
return descripcion != null ? descripcion.equals(articulo.descripcion) : articulo.descripcion == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (codigo != null ? codigo.hashCode() : 0);
result = 31 * result + (descripcion != null ? descripcion.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Articulo{" +
"id=" + id +
", codigo='" + codigo + '\'' +
", descripcion='" + descripcion + '\'' +
'}';
}
}
Although doing this I still can get the Id on the Json response, I still get like this:
"_embedded" : {
"articulos" : [ {
"codigo" : "111012082",
"descripcion" : "VIRGEN LEV. FRESCA X 500G",
"_links" : {
"self" : {
"href" : "http://localhost:8080/articulos/1"
},
"articulo" : {
"href" : "http://localhost:8080/articulos/1"
}
}
Thanks very much!
For your information, i've created a simple component to dynamically expose every id.
#Component
public class EntityExposingIdConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
try {
Field exposeIdsFor = RepositoryRestConfiguration.class.getDeclaredField("exposeIdsFor");
exposeIdsFor.setAccessible(true);
ReflectionUtils.setField(exposeIdsFor, config, new ListAlwaysContains());
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
class ListAlwaysContains extends ArrayList {
#Override
public boolean contains(Object o) {
return true;
}
}
}
I get java.io.IOException: java.lang.NullPointerException: Argument Error: Parameter url is null.
xhtml file:
<p:dataTable var="vehicleTransactionList" value="#{viewCompanyManagedBean.vehicleTransactionList}">
<p:column headerText="#{messages.saptrn}">
<h:outputText value="#{vehicleTransactionList.vehicleTransactionId}" />
</p:column>
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>
</p:contentFlow>
</p:column>
</p:dataTable>
The error is on the 2nd column #{newimage.imageLocations}
Managed Bean:
package com.company.beans;
import com.company.entities.Company;
import com.company.entities.Scale;
import com.company.entities.ScaleMeasurement;
import com.company.entities.VehicleTransaction;
import com.company.services.db.ScaleMeasurementService;
import com.company.services.db.ScaleService;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.primefaces.event.SelectEvent;
import sunw.io.Serializable;
#SuppressWarnings("deprecation")
#ManagedBean
#ViewScoped
public class ViewCompanyManagedBean implements Serializable {
static Logger webRecySys = null;
static {
webRecySys = Logger.getLogger("com.company.webRecySys");
}
public ViewCompanyManagedBean() {
}
#PostConstruct
public void populateCompanyData() {
prepareData(new Date());
images = new ArrayList<String>();
for (int i = 1; i <= 7; i++) {
images.add("file_" + i + ".jpg");
}
}
#PostConstruct
public void onDateSelect(SelectEvent event) throws UnknownHostException {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String date = format.format(event.getObject());
try {
Date selectedDate = format.parse(date);
prepareData(selectedDate);
} catch (ParseException e) {
e.printStackTrace();
}
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected",format.format(event.getObject())));
}
private void prepareData(Date forData) {
ScaleService ss = new ScaleService();
ScaleMeasurementService sms = new ScaleMeasurementService();
Scale right = ss.find(getRightScale());
Scale left = ss.find(getLeftScale());
this.measurements = sms.getMeasurementForScale(right,forData);
this.measurements.addAll(sms.getMeasurementForScale(left,forData));
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
this.fileName = "Shredder_Measurements_"+ sdf.format(forData);
for ( ScaleMeasurement s : measurements ) {
if ( s.getScale().getScaleId().equalsIgnoreCase(rightScale) ) {
this.rightScaleMeasurementSum += s.getMeasurement();
}
if ( s.getScale().getScaleId().equalsIgnoreCase(leftScale) ) {
this.leftScaleMeasurementSum += s.getMeasurement();
}
}
vehicleTransactionList = getVehicleTransactionList( sdf.format(forData) , (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest() );
}
private ArrayList<VehicleTransaction> getVehicleTransactionList(String fileDateFormat,HttpServletRequest request) {
ResourceBundle resourceb = ResourceBundle.getBundle("com.company.messages.image");
String imgRootPath = resourceb.getString("imagerootpath");
ArrayList<VehicleTransaction> images = new ArrayList<VehicleTransaction>();
String name = request.getLocalName();
if ( name != null ) {
if ( name.startsWith("0") ) {
name = "localhost";
}
}
else {
name = "localhost";
}
Scale scale = new ScaleService().find("01");
Company c = new ScaleService().getCompanyFromScale(scale);
String companyName = c.getCompanyName().trim().replace(" ", "_");
String URL = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/";
ArrayList<String> picUrls = new ArrayList<String>();
Document doc;
try {
doc = Jsoup.connect(URL).get();
for (Element file : doc.select("a")) {
String urlPathToFile = file.attr("href");
String fileName = file.text();
if ( urlPathToFile.endsWith(".jpg") && fileName.endsWith(".jpg") ) {
String picUrl = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/"+fileName;
picUrls.add(picUrl);
}
}
} catch (IOException e) {
webRecySys.logp(Level.WARNING, this.getClass().getCanonicalName() , "getAllImagesList", "Cannot get list of Images: "+e.getMessage() );
}
ArrayList<String> vehicleTransactionIdList = getVehicleTransactionIds(picUrls);
for ( String vehicleTransactionId : vehicleTransactionIdList) {
ArrayList<String> imagesForTransaction = getVehicleTransaction(vehicleTransactionId,picUrls);
VehicleTransaction s = new VehicleTransaction(imagesForTransaction, vehicleTransactionId);
images.add(s);
}
return images;
}
private ArrayList<String> getVehicleTransaction(String vehicleTransactionId,ArrayList<String> picUrls) {
ArrayList<String> imagesForTransaction = new ArrayList<String>();
for (String url : picUrls) {
if ( url.contains(vehicleTransactionId)) {
imagesForTransaction.add(url);
}
}
return imagesForTransaction;
}
private ArrayList<String> getVehicleTransactionIds(ArrayList<String> picUrls) {
ArrayList<String> vehicleTransactionIds = new ArrayList<String>();
for ( String pic : picUrls ) {
String vehicleTransactionId = pic.substring(pic.lastIndexOf("/")+1);
vehicleTransactionId = vehicleTransactionId.substring(0,vehicleTransactionId.indexOf("_"));
if ( !existsInArl(vehicleTransactionId,vehicleTransactionIds) ) {
vehicleTransactionIds.add(vehicleTransactionId);
}
}
return vehicleTransactionIds;
}
private boolean existsInArl (String s , ArrayList<String> arl) {
boolean exists = false;
for ( String c : arl ) {
if ( c.equalsIgnoreCase(s) ) {
exists = true;
}
}
return exists;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<ScaleMeasurement> getMeasurements() {
return measurements;
}
public void setMeasurements(List<ScaleMeasurement> measurements) {
this.measurements = measurements;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public String getRightScale() {
return rightScale;
}
public void setRightScale(String rightScale) {
this.rightScale = rightScale;
}
public String getLeftScale() {
return leftScale;
}
public void setLeftScale(String leftScale) {
this.leftScale = leftScale;
}
public int getRightScaleMeasurementSum() {
return rightScaleMeasurementSum;
}
public void setRightScaleMeasurementSum(int rightScaleMeasurementSum) {
this.rightScaleMeasurementSum = rightScaleMeasurementSum;
}
public int getLeftScaleMeasurementSum() {
return leftScaleMeasurementSum;
}
public void setLeftScaleMeasurementSum(int leftScaleMeasurementSum) {
this.leftScaleMeasurementSum = leftScaleMeasurementSum;
}
public ArrayList<VehicleTransaction> getVehicleTransactionList() {
return vehicleTransactionList;
}
public void setVehicleTransactionList(
ArrayList<VehicleTransaction> vehicleTransactionList) {
this.vehicleTransactionList = vehicleTransactionList;
}
// Used for Calendar
private Date date;
// Used for Shredder Measurements
private List<ScaleMeasurement> measurements = new ArrayList<ScaleMeasurement>();
private String fileName;
private String rightScale = "02";
private String leftScale = "03";
private int rightScaleMeasurementSum;
private int leftScaleMeasurementSum;
// Used for Pictures
private List<String> images;
private ArrayList<VehicleTransaction> vehicleTransactionList = new ArrayList<VehicleTransaction>();
private static final long serialVersionUID = 7449888248791054139L;
}
VehicleTransaction Pojo:
package com.company.entities;
import java.util.ArrayList;
public class VehicleTransaction {
public VehicleTransaction() {
}
public VehicleTransaction(ArrayList<String> imageLocations, String vehicleTransactionId) {
super();
this.imageLocations = imageLocations;
this.vehicleTransactionId = vehicleTransactionId;
}
public ArrayList<String> getImageLocations() {
return imageLocations;
}
public void setImageLocations(ArrayList<String> imageLocations) {
this.imageLocations = imageLocations;
}
public String getVehicleTransactionId() {
return vehicleTransactionId;
}
public void setVehicleTransactionId(String vehicleTransactionId) {
this.vehicleTransactionId = vehicleTransactionId;
}
private ArrayList<String> imageLocations;
private String vehicleTransactionId;
}
What's my mistake?
resolved - the right xhtml code is:
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{vehicleTransactionList.imageLocations}" var="images">
<p:graphicImage value="#{images}" styleClass="content" />
<div class="caption">#{images}</div>
</p:contentFlow>
</p:column>
Whereas the wrong code was:
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>
I am not able to get step count. I've been stuck on getting the onDataPoint method to be called. This code is almost correct. I am not able to find why it is not showing step count.
package com.example.akkisocc.heath;
import android.content.Intent;
import android.content.IntentSender;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSource;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.data.Value;
import com.google.android.gms.fitness.request.DataSourcesRequest;
import com.google.android.gms.fitness.request.OnDataPointListener;
import com.google.android.gms.fitness.request.SensorRequest;
import com.google.android.gms.fitness.result.DataSourcesResult;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity implements OnDataPointListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_OAUTH = 1;
private static final String AUTH_PENDING = "auth_state_pending";
TextView msg;
private boolean authInProgress = false;
private GoogleApiClient mApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (TextView) findViewById(R.id.msg);
msg.setText("On Create");
Log.e("GoogleFit", "Oncreate");
if (savedInstanceState != null) {
authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
}
mApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
mApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == RESULT_OK) {
if (!mApiClient.isConnecting() && !mApiClient.isConnected()) {
mApiClient.connect();
}
} else if (resultCode == RESULT_CANCELED) {
Log.e("GoogleFit", "RESULT_CANCELED");
}
} else {
Log.e("GoogleFit", "requestCode NOT request_oauth");
}
}
#Override
public void onConnected(Bundle bundle) {
DataSourcesRequest dataSourceRequest = new DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setDataSourceTypes(DataSource.TYPE_RAW)
.build();
ResultCallback<DataSourcesResult> dataSourcesResultCallback = new ResultCallback<DataSourcesResult>() {
#Override
public void onResult(DataSourcesResult dataSourcesResult) {
for (DataSource dataSource : dataSourcesResult.getDataSources()) {
if (DataType.TYPE_STEP_COUNT_CUMULATIVE.equals(dataSource.getDataType())) {
registerFitnessDataListener(dataSource, DataType.TYPE_STEP_COUNT_CUMULATIVE);
}
}
}
};
Fitness.SensorsApi.findDataSources(mApiClient, dataSourceRequest)
.setResultCallback(dataSourcesResultCallback);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!authInProgress) {
try {
authInProgress = true;
connectionResult.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
}
} else {
Log.e("GoogleFit", "authInProgress");
}
}
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {
SensorRequest request = new SensorRequest.Builder()
.setDataSource(dataSource)
.setDataType(dataType)
.setSamplingRate(3, TimeUnit.SECONDS)
.build();
Fitness.SensorsApi.add(mApiClient, request, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e("GoogleFit", "SensorApi successfully added");
}
}
});
}
#Override
public void onDataPoint(DataPoint dataPoint) {
for (final Field field : dataPoint.getDataType().getFields()) {
final Value value = dataPoint.getValue(field);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Field: " + field.getName() + " Value: " + value, Toast.LENGTH_SHORT).show();
}
});
}
}
}
(As solved in the comments) The issue is that TYPE_STEP_COUNT_CUMULATIVE is not a raw data type—Google uses a combination of sensors, accelerometer, machine learning, etc. to determine step count. So the .setDataSourceTypes(DataSource.TYPE_RAW) line needs to be removed.
OP noticed that just removing the line gives less accurate results than replacing it with DataSource.TYPE_DERIVED.
Also, the Google Fit FAQ has an example which uses TYPE_DERIVED.
I have an entity like this:
#Entity
#Table(name = "PLATFORM")
public class Platform{
#Id
#Column(name = "PLATFORM_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer platformId;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="PLATFORM_TYPE_ID")
private PlatformType platformType;
//must be manytomany but how?
private List<MimeType> supportedMimeTypes;
...
And I have a MimeType class which is a org.hibernate.usertype.UserType indeed.
import java.sql.Types;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MimeType extends EnumarationType{
private static final long serialVersionUID = 1L;
public static final MimeType XML = new MimeType(new Integer(0), "XML");
public static final MimeType JSON = new MimeType(new Integer(1), "JSON");
protected static ArrayList<MimeType> list = new ArrayList<MimeType>();
static {
SQL_TYPES = new int[] { Types.INTEGER };
list.add(XML);
list.add(JSON);
}
public MimeType(){
}
public MimeType(Integer value, String label) {
super(value, label);
}
public List<?> getList() {
return list;
}
public static MimeType getById(int id) {
Iterator<MimeType> it = list.iterator();
while (it.hasNext()) {
MimeType status = it.next();
int statusId = Integer.parseInt(status.getValue());
if (statusId == id)
return status;
}
return null;
}
public static MimeType getByName(String name) {
Iterator<MimeType> it = list.iterator();
while (it.hasNext()) {
MimeType status = it.next();
String statusName = status.getLabel();
if (statusName.equalsIgnoreCase(name))
return status;
}
return null;
}
}
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
public abstract class EnumarationTypeBase implements UserType, Serializable {
protected static int[] SQL_TYPES = { Types.VARCHAR };
protected String label;
protected Object value;
protected String resourceKey;
public EnumarationTypeBase() {
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public abstract List<?> getList();
private Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public EnumarationTypeBase resolveFromValue(Object value) {
List<?> list = getList();
if (list == null)
return null;
EnumarationTypeBase result = null;
for (Iterator<?> itr = list.iterator(); itr.hasNext();) {
EnumarationTypeBase enm = (EnumarationTypeBase) itr.next();
if (enm.getValue().toString().equals(value.toString())) {
result = enm;
break;
}
}
return result;
}
public EnumarationTypeBase resolveFromLabel(Object label) {
List<?> list = getList();
if (list == null)
return null;
EnumarationTypeBase result = null;
for (Iterator<?> itr = list.iterator(); itr.hasNext();) {
EnumarationTypeBase enm = (EnumarationTypeBase) itr.next();
if (enm.getLabel().equals(label.toString())) {
result = enm;
break;
}
}
return result;
}
public String toString() {
return getLabel();
}
public int[] sqlTypes() {
return SQL_TYPES;
}
public Class<?> returnedClass() {
return getClass();
}
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException,
SQLException {
value = resultSet.getString(names[0]);
return resultSet.wasNull() ? null : resolveFromValue(value);
}
public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException,
SQLException {
EnumarationTypeBase enumType = (EnumarationTypeBase) value;
if (value == null) {
statement.setNull(index, sqlTypes()[0]);
} else {
statement.setString(index, enumType.getValue().toString());
}
}
public boolean equals(Object x, Object y) {
if (x == y)
return true;
if (null == x || null == y)
return false;
return x.equals(y);
}
public boolean equals(Object obj) {
if (obj instanceof EnumarationTypeBase)
return this.getValue().equals(((EnumarationTypeBase) obj).getValue());
return super.equals(obj);
}
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
public Object deepCopy(Object value) {
return value;
}
public boolean isMutable() {
return false;
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public int hashCode() {
return (new Integer(this.getValue().toString())).intValue();
}
public String getResourceKey() {
if (resourceKey == null)
resourceKey = resolveFromValue(this.value).resourceKey;
return resourceKey;
}
public void setResourceKey(String resourceKey) {
this.resourceKey = resourceKey;
}
}
public abstract class EnumarationType extends EnumarationTypeBase {
protected static int[] SQL_TYPES = { Types.VARCHAR };
public EnumarationType() {
}
public EnumarationType(Integer value, String label) {
this.value = value.toString();
this.label = label;
}
public EnumarationType(String value, String label) {
this.value = value.toString();
this.label = label;
}
public EnumarationType(Integer value, String label, String resourceKey) {
this.value = value.toString();
this.label = label;
this.resourceKey = resourceKey;
}
public String getValue() {
return (String) value;
}
public BigDecimal getBigDecimalValue() {
BigDecimal tValue = new BigDecimal(getValue());
return tValue;
}
public void setValue(String value) {
this.value = value;
}
}
So how could i define a manytomany relationship between the entity Platform and non-entity usertype MimeType.
Please help.
I solved the problem. Here is the working code
...
#ElementCollection(targetClass = MimeType.class,fetch=FetchType.EAGER)
#CollectionTable(name = "PLATFORM_MIME_TYPE", joinColumns = #JoinColumn(name = "PLATFORM_ID"))
#Enumerated(EnumType.ORDINAL)
#Column(name = "MIME_TYPE_ID", columnDefinition="integer")
#Type(
type = Constants.ENUMERATION_TYPE,
parameters = {
#Parameter(
name = "enumClass",
value = "com.ba.reme.model.enums.MimeType"),
#Parameter(
name = "identifierMethod",
value = "toInt"),
#Parameter(
name = "valueOfMethod",
value = "fromInt")
}
)
private Set<MimeType> supportedMimeTypes;
...
And the MimeType enum :
public enum MimeType {
XML(1),
JSON(2),
RSS(3);
private int value;
MimeType(int value) {
this.value = value;
}
// the identifierMethod
public int toInt() {
return value;
}
// the valueOfMethod
public static MimeType fromInt(int value) {
switch(value) {
case 2: return JSON;
case 3: return RSS;
default: return XML;
}
}
public String toString() {
switch(this) {
case RSS: return "rss";
case JSON: return "json";
default: return "xml";
}
}
}