i have some problem with room database i guess.
I created an entity class:
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.os.Parcel;
import android.os.Parcelable;
#Entity
public class Supplier implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Long id;
private String mastro;
private String partitario;
private String description;
// region Construction
public Supplier() {
super();
}
// region Public getters and setters
protected Supplier(Parcel in) {
if (in.readByte() == 0) {
id = null;
} else {
id = in.readLong();
}
mastro = in.readString();
partitario = in.readString();
description = in.readString();
}
public static final Creator<Supplier> CREATOR = new Creator<Supplier>() {
#Override
public Supplier createFromParcel(Parcel in) {
return new Supplier(in);
}
#Override
public Supplier[] newArray(int size) {
return new Supplier[size];
}
};
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMastro() {
return mastro;
}
public void setMastro(String mastro) {
this.mastro = mastro;
}
public String getPartitario() {
return partitario;
}
public void setPartitario(String partitario) {
this.partitario = partitario;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeLong(id);
}
dest.writeString(mastro);
dest.writeString(partitario);
dest.writeString(description);
}
// endregion
}
Then i create a Dao class with simple queries:
#Dao
public interface SupplierDao {
#Query("SELECT * FROM Supplier WHERE id = :id")
Supplier getById(Long id);
#Insert
Long insert(Supplier supplier);
#Insert
Long insert(List<Supplier> suppliers);
#Update
void update(Supplier supplier);
#Delete
void delete(Supplier supplier);
#Query("DELETE FROM Supplier")
void deleteAll();
}
And this is the class when i create database:
package com.poltronesofa.plt.storage;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverter;
import android.arch.persistence.room.TypeConverters;
import android.content.Context;
import com.poltronesofa.plt.storage.dao.AnomalyDao;
import com.poltronesofa.plt.storage.dao.ContractorDao;
import com.poltronesofa.plt.storage.dao.LoadingPlanDao;
import com.poltronesofa.plt.storage.dao.ProductDao;
import com.poltronesofa.plt.storage.dao.SupplierDao;
import com.poltronesofa.plt.storage.dao.UsersDao;
import com.poltronesofa.plt.storage.model.Anomaly;
import com.poltronesofa.plt.storage.model.Contractor;
import com.poltronesofa.plt.storage.model.LoadingPlan;
import com.poltronesofa.plt.storage.model.Product;
import com.poltronesofa.plt.storage.model.Supplier;
import com.poltronesofa.plt.storage.model.User;
import java.util.Date;
/**
* #author arinaldi
*/
#Database(entities = {User.class, LoadingPlan.class, Contractor.class, Product.class, Anomaly.class, Supplier.class}, version = PLTDatabase.DB_VERSION, exportSchema = false)
#TypeConverters({PLTDatabase.Converters.class})
public abstract class PLTDatabase
extends RoomDatabase {
static final String DB_NAME = "plt_db";
static final int DB_VERSION = 1;
private static PLTDatabase INSTANCE = null;
public static void init(Context context) {
if (INSTANCE != null) {
INSTANCE.close();
}
INSTANCE = Room.databaseBuilder(context, PLTDatabase.class, DB_NAME)
.allowMainThreadQueries()
.build();
}
public static PLTDatabase get() {
if (INSTANCE == null) {
throw new RuntimeException("DATABASE not initialized");
}
return INSTANCE;
}
public void clear() {
users().deleteAll();
loadingPlans().deleteAll();
contractors().deleteAll();
products().deleteAll();
anomalies().deleteAll();
//suppliers().deleteAll();
}
public abstract UsersDao users();
public abstract LoadingPlanDao loadingPlans();
public abstract ContractorDao contractors();
public abstract ProductDao products();
public abstract AnomalyDao anomalies();
public abstract SupplierDao suppliers();
public static class Converters {
#TypeConverter
public Date fromTimeStamp(Long timestamp) {
return timestamp == null ? null : new Date(timestamp);
}
#TypeConverter
public Long toTimeStamp(Date date) {
return date == null ? null : date.getTime();
}
}
}
When I compile I get errors related to the databinding and I can not go back to the real error because it's not specified:
C:/Documents/Android Studio/PLT
app/build/generated/data_binding_base_class_source_out/devDebug/dataBindingGenBaseClassesDevDebug/out
com/poltronesofa/plt/databinding/ActivityHomeBinding.java
error: cannot find symbol class DataBindingComponent
error: cannot find symbol class DataBindingComponent
error: cannot find symbol class DataBindingComponent
error: cannot find symbol class DataBindingComponent
com/poltronesofa/plt/databinding/ViewToolbarBinding.java
com/poltronesofa/plt/databinding/FragmentWelcomeBinding.java
com/poltronesofa/plt/databinding/ListItemLoadingPlanBinding.java
com/poltronesofa/plt/databinding/FragmentLoadingPlansBinding.java
com/poltronesofa/plt/databinding/ActivityLoginBinding.java
com/poltronesofa/plt/databinding/ActivityCheckTissueBinding.java
com/poltronesofa/plt/databinding/ActivitySuppliersBinding.java
com/poltronesofa/plt/databinding/ListItemSupplierBinding.java
com/poltronesofa/plt/databinding/ActivityContractorsBinding.java
com/poltronesofa/plt/databinding/ListItemContractorBinding.java
com/poltronesofa/plt/databinding/ActivityLoadingPlanBinding.java
com/poltronesofa/plt/databinding/ActivityProductDetailBinding.java
com/poltronesofa/plt/databinding/ActivityProductsBinding.java
com/poltronesofa/plt/databinding/ListItemProductBinding.java
com/poltronesofa/plt/databinding/ActivitySettingsBinding.java
com/poltronesofa/plt/databinding/ActivitySplashBinding.java
com/poltronesofa/plt/databinding/FragmentProductBinding.java
com/poltronesofa/plt/databinding/ListItemArticleBinding.java
app/src/main/java
com/poltronesofa/plt/storage/dao/SupplierDao.java
error: Method returns long but it should return one of the following: `void, long[], java.lang.Long[], java.util.List<java.lang.Long>`. If you want to return the list of row ids from the query, your insertion method can receive only 1 parameter.
How can i solve this?
Related
I was creating a simple reminder app with room database based on a youtube tutorial.
but it ends with java.lang.NullPointerException: Attempt to invoke virtual method 'com.dev.alarmreminder.Database.EventDao com.dev.alarmreminder.Database.DatabaseClass.EventDao()' on a null object reference.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dev.alarmreminder.Database.EventDao com.dev.alarmreminder.Database.DatabaseClass.EventDao()' on a null object reference
at com.dev.alarmreminder.MainActivity.setAdapter(MainActivity.java:49)
at com.dev.alarmreminder.MainActivity.onResume(MainActivity.java:43)
I don't get it why it's called nullpointerexception. tried but it didn't get it.
DatabaseClass.java
#Database(entities = {EntityClass.class}, version = 1)
public abstract class DatabaseClass extends RoomDatabase
{
public abstract EventDao EventDao();
private static DatabaseClass INSTANCE;
static DatabaseClass getDatabase(final Context context)
{
if(INSTANCE == null)
{
synchronized (DatabaseClass.class)
{
if(INSTANCE == null)
{
INSTANCE = Room.databaseBuilder(context.getApplicationContext(), DatabaseClass.class, "product_database").build();
}
}
}
return INSTANCE;
}
}
EventDao.java
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
#Dao
public interface EventDao
{
#Insert
void insertAll(EntityClass entityClass);
#Query("SELECT * FROM myTable")
List<EntityClass> getAllData();
}
EntityClass.java
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "myTable")
public class EntityClass
{
#PrimaryKey(autoGenerate = true)
int id;
String eventname;
String eventdate;
String eventtime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEventname() {
return eventname;
}
public void setEventname(String eventname) {
this.eventname = eventname;
}
public String getEventdate() {
return eventdate;
}
public void setEventdate(String eventdate) {
this.eventdate = eventdate;
}
public String getEventtime() {
return eventtime;
}
public void setEventtime(String eventtime) {
this.eventtime = eventtime;
}
}
MainACtivity
package com.mahidev.alarmreminder;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.mahidev.alarmreminder.Adapter.EventAdapter;
import com.mahidev.alarmreminder.Database.DatabaseClass;
import com.mahidev.alarmreminder.Database.EntityClass;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
Button createEvent;
EventAdapter eventAdapter;
RecyclerView recyclerView;
DatabaseClass databaseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createEvent = findViewById(R.id.btn_createEvent);
recyclerView = findViewById(R.id.recyclerview);
createEvent.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
setAdapter();
}
private void setAdapter()
{
List<EntityClass> classList = databaseClass.EventDao().getAllData();
eventAdapter = new EventAdapter(getApplicationContext(), classList);
recyclerView.setAdapter(eventAdapter);
}
#Override
public void onClick(View view)
{
if(view == createEvent)
{
goToCreateEventActivity();
}
}
private void goToCreateEventActivity()
{
Intent intent = new Intent(getApplicationContext(), CreateEvent.class);
startActivity(intent);
}
}
issue here is the first line in setAdapter method.
You haven't instantiated databaseClass as such it is null and hence the exception.
You need to add a line (in the onCreate method, immediately after the setContentView call would be a suitable place)
databaseClass = Database.getDatabase(this);
I am making a simple alarm app that holds alarm data in a databased generated with Room, and uses a viewmodel to update the RecyclerView adapter's list. However, when I check/uncheck the switch on one item in the RecyclerView it sometimes causes another item's switch to check/uncheck itself, and I'm not sure why. Any help on what is wrong with my code is appreciated. Here is the java code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private List<Alarms> mainAlarmsList;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private AlarmsAdapter alarmsAdapter;
private AlarmsAdapter.alarmedInterface coolInterface;
private ImageButton imageButton, clearButton;
private AlarmsViewModel alarmsViewModel;
private AlarmManager epicAlarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
epicAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
imageButton = (ImageButton) findViewById(R.id.alarm_button);
clearButton = (ImageButton) findViewById(R.id.clear_alarms_button);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createTimePicker(MainActivity.this);
}
});
alarmsViewModel = ViewModelProviders.of(this).get(AlarmsViewModel.class);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alarmsViewModel.deleteAllAlarms();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
alarmsAdapter = new AlarmsAdapter(this);
//alarmsAdapter.setAlarms(alarmsViewModel.getAllAlarms().getValue());
coolInterface = new AlarmsAdapter.alarmedInterface() {
#Override
public void onSwitch(int position, boolean isChecked, CompoundButton compoundButton) {
Alarms currentAlarm = mainAlarmsList.get(position);
String concatenatedString;
if(isChecked){
currentAlarm.setOffOn(1);
concatenatedString = currentAlarm.getId() + " is on " + currentAlarm.getOffOn();
compoundButton.setChecked(true);
}
else {
currentAlarm.setOffOn(0);
concatenatedString = currentAlarm.getId() + " is off " + currentAlarm.getOffOn();
compoundButton.setChecked(false);
}
Toast.makeText(MainActivity.this,concatenatedString,Toast.LENGTH_LONG).show();
new updateAsync(alarmsViewModel).execute(currentAlarm);
}
};
recyclerView.setAdapter(alarmsAdapter);
alarmsViewModel.getAllAlarms().observe(this, new Observer<List<Alarms>>() {
#Override
public void onChanged(List<Alarms> alarms) {
alarmsAdapter.setAlarms(alarms);
alarmsAdapter.setAlarmInterfaceInstance(coolInterface);
alarmsAdapter.notifyDataSetChanged();
mainAlarmsList = alarms;
}
});
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
public void createTimePicker(Context context){
final Calendar calendar = Calendar.getInstance();
final int hrDay = Calendar.HOUR_OF_DAY;
final int min = Calendar.MINUTE;
TimePickerDialog dialog = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Alarms myAlarm = new Alarms(hourOfDay,minute);
myAlarm.setOffOn(1);
alarmsViewModel.insertAlarms(myAlarm);
alarmsAdapter.notifyDataSetChanged();
calendar.set(Calendar.HOUR_OF_DAY, myAlarm.getHour());
calendar.set(Calendar.MINUTE, myAlarm.getMin());
alarmTime(myAlarm,calendar);
}
}, hrDay,min,true);
dialog.show();
}
public void alarmTime(Alarms alarms,Calendar calendar){
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,
alarms.getId(),intent,0);
long hrlong = alarms.getHour();
long minlong = alarms.getMin();
epicAlarmManager.setExact(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() ,pendingIntent);
}
class updateAsync extends AsyncTask<Alarms,Void,Void>{
private AlarmsViewModel viewModel;
updateAsync(AlarmsViewModel alarmsViewModel1){
viewModel = alarmsViewModel1;
}
#Override
protected Void doInBackground(Alarms... alarms) {
viewModel.updateAlarms(alarms[0]);
return null;
}
}
}
Alarms.java
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "Alarms")
public class Alarms {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "hour")
private int hour;
#ColumnInfo(name = "min")
private int min;
#ColumnInfo(name = "offOn")
private int offOn;
public Alarms(int hour, int min){
this.hour = hour;
this.min = min;
offOn = 1;
}
public void setId(int id) {
this.id = id;
}
public void setMin(int min) {
this.min = min;
}
public void setHour(int hour) {
this.hour = hour;
}
public void setOffOn(int offOn) {
this.offOn = offOn;
}
public int getMin() {
return min;
}
public int getHour() {
return hour;
}
public int getOffOn() {
return offOn;
}
public int getId(){
return id;
}
}
AlarmsAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class AlarmsAdapter extends RecyclerView.Adapter<AlarmsAdapter.AlarmsViewHolder> {
private Context context;
private List<Alarms> alarms;
private alarmedInterface alarmInterfaceInstance;
interface alarmedInterface{
public void onSwitch(int position, boolean checked, CompoundButton compoundButton);
}
public AlarmsAdapter(Context context){
this.context = context;
}
public void setAlarmInterfaceInstance(alarmedInterface alarmInterfaceInstance) {
this.alarmInterfaceInstance = alarmInterfaceInstance;
}
public void setAlarms(List<Alarms> alarms) {
this.alarms = alarms;
}
#NonNull
#Override
public AlarmsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item,parent,false);
return new AlarmsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AlarmsAdapter.AlarmsViewHolder holder, final int position) {
if(alarms.isEmpty()){
holder.textView.setText("No alarms");
return;
}
else{
Alarms myAlarm = alarms.get(position);
if(myAlarm.getOffOn() == 1){
holder.aSwitch.setChecked(true);
}
else if(myAlarm.getOffOn() == 0){
holder.aSwitch.setChecked(false);
}
String x = alarms.get(position).getHour() + ":" + alarms.get(position).getMin();
holder.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
alarmInterfaceInstance.onSwitch(position, isChecked,buttonView);
}
});
holder.textView.setText(x);
}
}
#Override
public int getItemCount() {
if(alarms != null) {
return alarms.size();
}
else {
return 0;
}
}
public class AlarmsViewHolder extends RecyclerView.ViewHolder{
TextView textView;
SwitchCompat aSwitch;
public AlarmsViewHolder(View view){
super(view);
textView = view.findViewById(R.id.textView);
aSwitch = view.findViewById(R.id.switch1);
}
}
}
AlarmsViewModel.java
import android.app.Application;
import android.content.Context;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class AlarmsViewModel extends AndroidViewModel {
private AlarmsRepository repository;
private LiveData<List<Alarms>> allAlarms;
public AlarmsViewModel(Application application){
super(application);
repository = new AlarmsRepository(application.getApplicationContext());
allAlarms = repository.getAlarmsList();
}
public void deleteAllAlarms(){
repository.deleteAllAlarms();
}
public void updateAlarms(Alarms alarms){
repository.updateAlarm(alarms);
}
public void insertAlarms(Alarms alarms){
repository.insertAlarm(alarms);
}
public LiveData<List<Alarms>> getAllAlarms() {
return allAlarms;
}
}
AlarmdDao.java
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
#Dao
public interface AlarmDao {
#Query("Select * From Alarms")
public LiveData<List<Alarms>> getAllAlarms();
#Insert
public void insertAlarm(Alarms alarms);
#Update
public void updateAlarm(Alarms alarms);
#Delete
public void deleteAlarm(Alarms alarms);
#Query("Delete From Alarms")
public void deleteAllAlarms();
}
AlarmsDatabase
import android.app.Application;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
#Database(entities = {Alarms.class},version = 1,exportSchema = false)
public abstract class AlarmsDatabase extends RoomDatabase {
private static AlarmsDatabase alarmsDatabase;
private Context context;
public abstract AlarmDao alarmDao();
public static AlarmsDatabase AlarmsDatabaseBuilder(Context context){
if(alarmsDatabase == null){
synchronized (AlarmsDatabase.class){
if (alarmsDatabase == null){
alarmsDatabase = Room.databaseBuilder(context.getApplicationContext(),
AlarmsDatabase.class,"AlarmsDatabase").build();
}
}
}
return alarmsDatabase;
}
}
AlarmReceiver.java
package com.pbaileyapps.android.chatpal;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"You just recieved a toast!",Toast.LENGTH_LONG).show();
}
}
I have had similar issue with JSON objects, in my case a set of data is copied into two different JSON lists that both display differently in a recycle view. One of them displays the original data and the second has modified the data. However the modification appeared on both becuase the copies still linked to the original data behind the scences. I fixed this by making a 'deep copy'. It is possible that your alarm objects are not being deep copied into the list so two or more list elements have the same origin.
My package name was com.softmills.ogram and i have changed to com.ogram.sp and change applicationId in gradle file as well and clean the project and invalidate cash and restart it showed that error
D:\ogram\app\build\generated\source\navigation-args\debug\com\ogram\sp\ui\cancel\CancelFragmentArgs.java:8: error: package com.softmills.ogram.common.model does not exist
import com.softmills.ogram.common.model.Shift;
and here is android generated class
package com.ogram.sp.ui.cancel;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.NavArgs;
import com.softmills.ogram.common.model.Shift;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.lang.System;
import java.util.HashMap;
public class CancelFragmentArgs implements NavArgs {
private final HashMap arguments = new HashMap();
private CancelFragmentArgs() {
}
private CancelFragmentArgs(HashMap argumentsMap) {
this.arguments.putAll(argumentsMap);
}
#NonNull
#SuppressWarnings("unchecked")
public static CancelFragmentArgs fromBundle(#NonNull Bundle bundle) {
CancelFragmentArgs __result = new CancelFragmentArgs();
bundle.setClassLoader(CancelFragmentArgs.class.getClassLoader());
if (bundle.containsKey("shifts")) {
Shift[] shifts;
Parcelable[] __array = bundle.getParcelableArray("shifts");
if (__array != null) {
shifts = new Shift[__array.length];
System.arraycopy(__array, 0, shifts, 0, __array.length);
} else {
shifts = null;
}
__result.arguments.put("shifts", shifts);
}
return __result;
}
#SuppressWarnings("unchecked")
#Nullable
public Shift[] getShifts() {
return (Shift[]) arguments.get("shifts");
}
#SuppressWarnings("unchecked")
#NonNull
public Bundle toBundle() {
Bundle __result = new Bundle();
if (arguments.containsKey("shifts")) {
Shift[] shifts = (Shift[]) arguments.get("shifts");
__result.putParcelableArray("shifts", shifts);
}
return __result;
}
#Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
CancelFragmentArgs that = (CancelFragmentArgs) object;
if (arguments.containsKey("shifts") != that.arguments.containsKey("shifts")) {
return false;
}
if (getShifts() != null ? !getShifts().equals(that.getShifts()) : that.getShifts() != null) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result = 1;
result = 31 * result + java.util.Arrays.hashCode(getShifts());
return result;
}
#Override
public String toString() {
return "CancelFragmentArgs{"
+ "shifts=" + getShifts()
+ "}";
}
public static class Builder {
private final HashMap arguments = new HashMap();
public Builder(CancelFragmentArgs original) {
this.arguments.putAll(original.arguments);
}
public Builder() {
}
#NonNull
public CancelFragmentArgs build() {
CancelFragmentArgs result = new CancelFragmentArgs(arguments);
return result;
}
#NonNull
public Builder setShifts(#Nullable Shift[] shifts) {
this.arguments.put("shifts", shifts);
return this;
}
#SuppressWarnings("unchecked")
#Nullable
public Shift[] getShifts() {
return (Shift[]) arguments.get("shifts");
}
}
}
this line that caused the problem import com.softmills.ogram.common.model.Shift;
i don't know why it still see the old package name so i change it manually and rerun again but the same issue cause it's generated class
I have some JSON below.
{
"Table": [
{
"CMBL009001": "010001",
"NMBL009002": 0,
"CMBL009003": "",
"CMBL009004": "",
"CMBL009005": "",
"CMBL009006": "",
"NMBL009007": 0,
"BMBL009008": 0,
"NMBL009009": 0,
"CMBL009010": "ADMIN",
"CMBL009011": "",
"NMBL009012": 2,
"NMBL009013": 1
}
]
}
this is my model:
package com.example.showmyjsonapplicationuser;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("BMBL009008")
private Long mBMBL009008;
#SerializedName("CMBL009001")
private String mCMBL009001;
#SerializedName("CMBL009003")
private String mCMBL009003;
#SerializedName("CMBL009004")
private String mCMBL009004;
#SerializedName("CMBL009005")
private String mCMBL009005;
#SerializedName("CMBL009006")
private String mCMBL009006;
#SerializedName("CMBL009010")
private String mCMBL009010;
#SerializedName("CMBL009011")
private String mCMBL009011;
#SerializedName("NMBL009002")
private Long mNMBL009002;
#SerializedName("NMBL009007")
private Long mNMBL009007;
#SerializedName("NMBL009009")
private Long mNMBL009009;
#SerializedName("NMBL009012")
private Long mNMBL009012;
#SerializedName("NMBL009013")
private Long mNMBL009013;
public Long getBMBL009008() {
return mBMBL009008;
}
public void setBMBL009008(Long bMBL009008) {
mBMBL009008 = bMBL009008;
}
public String getCMBL009001() {
return mCMBL009001;
}
public void setCMBL009001(String cMBL009001) {
mCMBL009001 = cMBL009001;
}
public String getCMBL009003() {
return mCMBL009003;
}
public void setCMBL009003(String cMBL009003) {
mCMBL009003 = cMBL009003;
}
public String getCMBL009004() {
return mCMBL009004;
}
public void setCMBL009004(String cMBL009004) {
mCMBL009004 = cMBL009004;
}
public String getCMBL009005() {
return mCMBL009005;
}
public void setCMBL009005(String cMBL009005) {
mCMBL009005 = cMBL009005;
}
public String getCMBL009006() {
return mCMBL009006;
}
public void setCMBL009006(String cMBL009006) {
mCMBL009006 = cMBL009006;
}
public String getCMBL009010() {
return mCMBL009010;
}
public void setCMBL009010(String cMBL009010) {
mCMBL009010 = cMBL009010;
}
public String getCMBL009011() {
return mCMBL009011;
}
public void setCMBL009011(String cMBL009011) {
mCMBL009011 = cMBL009011;
}
public Long getNMBL009002() {
return mNMBL009002;
}
public void setNMBL009002(Long nMBL009002) {
mNMBL009002 = nMBL009002;
}
public Long getNMBL009007() {
return mNMBL009007;
}
public void setNMBL009007(Long nMBL009007) {
mNMBL009007 = nMBL009007;
}
public Long getNMBL009009() {
return mNMBL009009;
}
public void setNMBL009009(Long nMBL009009) {
mNMBL009009 = nMBL009009;
}
public Long getNMBL009012() {
return mNMBL009012;
}
public void setNMBL009012(Long nMBL009012) {
mNMBL009012 = nMBL009012;
}
public Long getNMBL009013() {
return mNMBL009013;
}
public void setNMBL009013(Long nMBL009013) {
mNMBL009013 = nMBL009013;
}
}
this is my retrofit class:
package com.example.showmyjsonapplicationuser;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitSingleton {
private static Retrofit retrofit;
public static Retrofit getInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.200.10:6139/api/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private RetrofitSingleton() {
}
}
this is provider class:
package com.example.showmyjsonapplicationuser.providers;
import com.example.showmyjsonapplicationuser.ApiService;
import com.example.showmyjsonapplicationuser.RetrofitSingleton;
public class ApiServiceProvider {
private static ApiService apiService;
public static ApiService provideApiService() {
if (apiService == null) {
apiService = RetrofitSingleton.getInstance().create(ApiService.class);
}
return apiService;
}
}
this is jsonUserResponse:
package com.example.showmyjsonapplicationuser;
public class JSONUserResponse {
private User[] Table;
public User[] getTable(){
return Table;
}
}
this is apiService:
package com.example.showmyjsonapplicationuser;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiService {
#GET("values?url=<NewDataSet><Table><ver>1_02.01.06</ver><proc>003TOTALSELECT</proc><P1>ADMIN</P1><P2>123456</P2><P3>MBLTYPEVISIT1</P3></Table></NewDataSet>")
Call<JSONUserResponse> getUsersJSON();
}
this is mainViewModel:
`package com.example.showmyjsonapplicationuser;
import com.example.showmyjsonapplicationuser.providers.ApiServiceProvider;
import retrofit2.Call;
public class MainViewModel {
private ApiService apiService = ApiServiceProvider.provideApiService();
Call<JSONUserResponse> callUser = apiService.getUsersJSON();
}
this in main activity:
package com.example.showmyjsonapplicationuser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private MainViewModel viewModel = new MainViewModel();
private ArrayList<User> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel.callUser.enqueue(new Callback<JSONUserResponse>() {
#Override
public void onResponse(Call<JSONUserResponse> call, Response<JSONUserResponse> response) {
JSONUserResponse jsonUserResponse = response.body();
assert jsonUserResponse != null;
data = new ArrayList<>(Arrays.asList(jsonUserResponse.getTable()));
Toast.makeText(MainActivity.this, "اطلاعات با موفقیت دریافت شد", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<JSONUserResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
the problem is that the response is null.
You need to create two model classes , one will be like below
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Table {
#SerializedName("CMBL009001")
#Expose
private String cMBL009001;
#SerializedName("NMBL009002")
#Expose
private Integer nMBL009002;
#SerializedName("CMBL009003")
#Expose
private String cMBL009003;
#SerializedName("CMBL009004")
#Expose
private String cMBL009004;
#SerializedName("CMBL009005")
#Expose
private String cMBL009005;
#SerializedName("CMBL009006")
#Expose
private String cMBL009006;
#SerializedName("NMBL009007")
//getters and setters
}
Another will be
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TestModel {
#SerializedName("Table")
#Expose
private List<Table> table = null;
public List<Table> getTable() {
return table;
}
public void setTable(List<Table> table) {
this.table = table;
}
}
And then you can use the TestModel in your call.
I want to integrate Greendao and Sqlcipher in android studio to have an encrypted db. I use sqlcipher-for-android
which I added these to my app/build.gradle
compile 'org.greenrobot:greendao:3.2.0'
compile 'org.greenrobot:greendao-generator:3.2.0'
compile 'net.zetetic:android-database-sqlcipher:3.5.6#aar'
I downloaded v3.5.6 from Here
in the second step I have to execute these commands
% unzip sqlcipher-for-android-v3.5.6.zip
% mkdir -p app/libs
% cp sqlcipher-for-android-v3.5.6/sqlcipher.jar app/libs
% cp -r sqlcipher-for-android-v3.5.6/armeabi \
sqlcipher-for-android-v3.5.6/armeabi-v7a \
sqlcipher-for-android-v3.5.6/x86
sqlcipher-for-android-v3.5.6/x86_64 \
sqlcipher-for-android-v3.5.6/arm64_v8a app/src/main/jniLibs/
but there is not any sqlcipher.jar, armeabi, armeabi-v7a, x86 and ... in the zip file
Am I missing something or doing wrong ?
please help
Comparing this with the example solved the issue
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
}
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
}
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
buildToolsVersion '25.0.2'
compileSdkVersion 25
defaultConfig {
applicationId "org.greenrobot.greendao.example"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "3"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
}
}
greendao {
schemaVersion 1000
}
dependencies {
compile 'org.greenrobot:greendao:3.2.2'
// This is only needed if you want to use encrypted databases
compile 'net.zetetic:android-database-sqlcipher:3.5.6'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
}
uploadArchives.enabled = falseapply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
buildToolsVersion '25.0.2'
compileSdkVersion 25
defaultConfig {
applicationId "org.greenrobot.greendao.example"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "3"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
}
}
greendao {
schemaVersion 1000
}
dependencies {
compile 'org.greenrobot:greendao:3.2.2'
// This is only needed if you want to use encrypted databases
compile 'net.zetetic:android-database-sqlcipher:3.5.6'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
}
uploadArchives.enabled = false
and the below code :
package org.greenrobot.greendao.example;
import android.app.Application;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.example.DaoMaster.DevOpenHelper;
public class App extends Application {
/** A flag to show how easily you can switch from standard SQLite to the
encrypted SQLCipher. */
public static final boolean ENCRYPTED = true;
private DaoSession daoSession;
#Override
public void onCreate() {
super.onCreate();
DevOpenHelper helper = new DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db");
Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
}
to read and modify data, I have a base Repository
first my entitties:
//Category.java
package Entities;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.NotNull;
import org.greenrobot.greendao.annotation.Generated;
#org.greenrobot.greendao.annotation.Entity(
nameInDb = "Categories"
)
public class Category {
#Id
public Long CategoryId;
#NotNull
public String Name;
public String Description;
#Generated(hash = 1903625692)
public Category(Long CategoryId, #NotNull String Name, String Description) {
this.CategoryId = CategoryId;
this.Name = Name;
this.Description = Description;
}
#Generated(hash = 1150634039)
public Category() {
}
public Long getCategoryId() {
return this.CategoryId;
}
public void setCategoryId(Long CategoryId) {
this.CategoryId = CategoryId;
}
public String getName() {
return this.Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getDescription() {
return this.Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
}
and User.java
package Entities;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.NotNull;
import org.greenrobot.greendao.annotation.Generated;
#org.greenrobot.greendao.annotation.Entity(
nameInDb = "Users"
)
public class User {
#Id
public Long UserId;
public String Username;
public String Mobile;
#NotNull
public String UserApiKey;
#NotNull
public String SecretKey;
public String FirstName;
public String LastName;
public boolean IsFirstLogin;
#Generated(hash = 1246565860)
public User(Long UserId, String Username, String Mobile,
#NotNull String UserApiKey, #NotNull String SecretKey, String FirstName,
String LastName, boolean IsFirstLogin) {
this.UserId = UserId;
this.Username = Username;
this.Mobile = Mobile;
this.UserApiKey = UserApiKey;
this.SecretKey = SecretKey;
this.FirstName = FirstName;
this.LastName = LastName;
this.IsFirstLogin = IsFirstLogin;
}
#Generated(hash = 586692638)
public User() {
}
public Long getUserId() {
return this.UserId;
}
public void setUserId(Long UserId) {
this.UserId = UserId;
}
public String getUsername() {
return this.Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public String getMobile() {
return this.Mobile;
}
public void setMobile(String Mobile) {
this.Mobile = Mobile;
}
public String getUserApiKey() {
return this.UserApiKey;
}
public void setUserApiKey(String UserApiKey) {
this.UserApiKey = UserApiKey;
}
public String getSecretKey() {
return this.SecretKey;
}
public void setSecretKey(String SecretKey) {
this.SecretKey = SecretKey;
}
public String getFirstName() {
return this.FirstName;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public String getLastName() {
return this.LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public boolean getIsFirstLogin() {
return this.IsFirstLogin;
}
public void setIsFirstLogin(boolean IsFirstLogin) {
this.IsFirstLogin = IsFirstLogin;
}
}
and BaseRepository.java
package services;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.query.DeleteQuery;
import org.greenrobot.greendao.query.WhereCondition;
import java.util.ArrayList;
import java.util.List;
import Entities.DaoSession;
import ir.swifttips.fidiboo.MainDbContext;
import Interfaces.IBaseRepository;
/**
* Created by macintosh on 1/20/18.
*/
public class BaseRepository<T> implements IBaseRepository<T> {
Class<T> type;
public AbstractDao<T, ?> dao;
public BaseRepository(Class<T> _type) {
type = _type;
DaoSession daoSession = MainDbContext.getDaoSession();
dao = (AbstractDao<T, ?>) daoSession.getDao(_type);
}
public Boolean Create(T entity)
{
dao.insert(entity);
return true;
}
public void Update(T entity)
{
dao.update(entity);
}
public boolean Delete(Long id)
{
DeleteQuery<T> deleteQuery= dao.queryBuilder()
.where(dao.getPkProperty().eq(id)).buildDelete();
deleteQuery.executeDeleteWithoutDetachingEntities();
MainDbContext.getDaoSession().clear();
return true;
}
public boolean DeleteAll()
{
dao.deleteAll();
return true;
}
public boolean Delete(WhereCondition cond)
{
DeleteQuery<T> deleteQuery= dao.queryBuilder()
.where(cond).buildDelete();
deleteQuery.executeDeleteWithoutDetachingEntities();
MainDbContext.getDaoSession().clear();
return true;
}
public T FirstOrDefault(Long id)
{
List<T> entities = dao.queryBuilder()
.where(dao.getPkProperty().eq(id)).limit(1).list();
if (entities.size() > 0)
return entities.get(0);
else
return null;
}
public boolean Exists(WhereCondition cond)
{
Long counts = dao.queryBuilder()
.where(cond).count();
if (counts > 0)
return true;
else
return false;
}
public Long Count(WhereCondition cond)
{
Long counts = dao.queryBuilder()
.where(cond).count();
return counts;
}
public T FirstOrDefault(WhereCondition... cond)
{
List<T> lst = new ArrayList<>();
if (cond.length == 1)
lst = dao.queryBuilder().where(cond[0]).limit(1).list();
else
if (cond.length == 2)
lst = dao.queryBuilder().where(cond[0],cond[1]).limit(1).list();
else
if (cond.length == 3)
lst = dao.queryBuilder().where(cond[0],cond[1],cond[2]).limit(1).list();
if (lst.size() > 0)
return lst.get(0);
return null;
}
public T LastOrDefault()
{
List<T> entities = dao.queryBuilder()
.orderDesc(dao.getPkProperty()).limit(1).list();
if (entities.size() > 0)
return entities.get(0);
else
return null;
}
public List<T> FetchMulti()
{
return (List<T>)dao.loadAll();
}
public List<T> FetchMulti(WhereCondition... cond)
{
if (cond.length == 1)
return dao.queryBuilder().where(cond[0]).list();
else
if (cond.length == 2)
return dao.queryBuilder().where(cond[0],cond[1]).list();
else
if (cond.length == 3)
return dao.queryBuilder().where(cond[0],cond[1],cond[2]).list();
else
return dao.loadAll();
}
}
and its interface
package Interfaces;
import org.greenrobot.greendao.query.DeleteQuery;
import org.greenrobot.greendao.query.WhereCondition;
import java.util.List;
/**
* Created by macintosh on 1/20/18.
*/
public interface IBaseRepository<T> {
Boolean Create(T entity);
void Update(T entity);
boolean Delete(Long id);
boolean DeleteAll();
boolean Delete(WhereCondition cond);
T FirstOrDefault(Long id);
boolean Exists(WhereCondition cond);
Long Count(WhereCondition cond);
T FirstOrDefault(WhereCondition... cond);
T LastOrDefault();
List<T> FetchMulti();
List<T> FetchMulti(WhereCondition... cond);
}
and then I have access to those methods in my services CategoryService.java
package services;
import android.content.Context;
import Common.VolleyCallback;
import Entities.Category;
import Entities.DaoSession;
import ir.swifttips.fidiboo.MainDbContext;
import Interfaces.ICategoryService;
import Interfaces.IProductService;
import iOC.ServiceFactory;
import restful.restfulApiInterfaces.IProductApi;
import restful.restfulResponse.ProductCategoryApiResponse;
import viewModels.ProductCategoryViewModel;
public class CategoryService extends BaseRepository<Category> implements ICategoryService {
Context context;
public CategoryService() {
super(Category.class);
context = MainDbContext.getAppContext();
}
}
and its interface
package Interfaces;
import Common.VolleyCallback;
import Entities.Category;
public interface ICategoryService extends IBaseRepository<Category> {
}
or userService.java
package services;
import android.content.Context;
import java.util.List;
import Entities.DaoSession;
import ir.swifttips.fidiboo.MainDbContext;
import Entities.User;
import Entities.UserDao;
import Interfaces.IUserService;
/**
* Created by macintosh on 12/30/17.
*/
public class UserService extends BaseRepository<User> implements IUserService {
Context context;
public UserService() {
super(User.class);
context = MainDbContext.getAppContext();
}
public User GetUserById_Query(Long id) {
List<User> users = dao.queryBuilder().where(UserDao.Properties.UserId.eq(id)).list();
if (users.size() > 0)
return users.get(0);
return null;
}
public User GetUserById(Long id) {
DaoSession daoSession = MainDbContext.getDaoSession();
User user = daoSession.getUserDao().load(id);
return user;
}
public boolean Exists(Long id) {
DaoSession daoSession = MainDbContext.getDaoSession();
User user = daoSession.getUserDao().load(id);
if (user == null)
return false;
else
return true;
}
}
and its interface
package Interfaces;
import Entities.User;
import Entities.DaoSession;
/**
* Created by macintosh on 1/3/18.
*/
public interface IUserService extends IBaseRepository<User> {
User LoggedinUser();
User GetUserById_Query(Long id);
User GetUserById(Long id) ;
boolean Exists(Long id) ;
}