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) ;
}
Related
Please I don't understand the error.java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 28 path $.message retrofit android studio Please I need your help
package com.sensei.linkrestaurant;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.sensei.linkrestaurant.Adapter.MyRestaurantAdapter;
import com.sensei.linkrestaurant.Adapter.RestaurantSliderAdapter;
import com.sensei.linkrestaurant.Common.Common;
import com.sensei.linkrestaurant.Model.EventBus.RestaurantLoadEvent;
import com.sensei.linkrestaurant.Model.Restaurant;
import com.sensei.linkrestaurant.Retrofit.ILinkRestaurantAPI;
import com.sensei.linkrestaurant.Retrofit.RetrofitClient;
import com.sensei.linkrestaurant.Service.PicassoImageLoadingService;
import com.sensei.linkrestaurant.databinding.ActivityHomeBinding;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import dmax.dialog.SpotsDialog;
import io.paperdb.Paper;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import ss.com.bannerslider.Slider;
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "HomeActivity";
private AppBarConfiguration mAppBarConfiguration;
private ActivityHomeBinding binding;
TextView txt_user_name, txt_user_phone;
#BindView(R.id.banner_slider)
Slider banner_slider;
#BindView(R.id.recycler_restaurant)
RecyclerView recyclerView;
private ILinkRestaurantAPI iLinkRestaurantAPI;
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
private AlertDialog dialog;
#Override
protected void onDestroy() {
compositeDisposable.clear();
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityHomeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarHome.toolbar);
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_link_main2);
NavigationUI.setupActionBarWithNavController(this, navController,
mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
txt_user_name = headerView.findViewById(R.id.txt_user_name);
txt_user_phone = headerView.findViewById(R.id.txt_user_phone);
txt_user_name.setText(Common.currentUser.getName());
txt_user_phone.setText(Common.currentUser.getUserPhone());
navigationView.setNavigationItemSelectedListener(this);
init();
initView();
loadRestaurant();
}
private void init() {
dialog = new SpotsDialog.Builder().setContext(this).setCancelable(false).build();
iLinkRestaurantAPI = RetrofitClient
.getInstance(Common.API_RESTAURANT_ENDPOINT).create(ILinkRestaurantAPI.class);
Slider.init(new PicassoImageLoadingService());
}
private void initView() {
ButterKnife.bind(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,
layoutManager.getOrientation()));
}
private void loadRestaurant() {
dialog.show();
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Common.buildJWT(Common.API_KEY));
compositeDisposable.add(
iLinkRestaurantAPI.getRestaurant(headers)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(restaurantModel -> {
//Event bus to send local even to set adapter and slider
EventBus.getDefault().post(new RestaurantLoadEvent(true,
restaurantModel.getResult()));
dialog.dismiss();
},
throwable ->{
dialog.dismiss();
EventBus.getDefault().post(new RestaurantLoadEvent(false,
throwable.getMessage()));
Toast.makeText(this, "[GET RESTAURANT]"+throwable.getMessage(),
Toast.LENGTH_SHORT).show();
})
);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_link_main2);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_log_out){
signOut();
} else if (id == R.id.nav_nearby){
startActivity(new Intent(HomeActivity.this, NearbyRestaurantActivity.class));
} else if(id == R.id.order_history){
startActivity(new Intent(HomeActivity.this, ViewOrderActivity.class));
} else if(id == R.id.update_information){
startActivity(new Intent(HomeActivity.this, UpdateInfoActivity.class));
}else if (id == R.id.nav_fav){
startActivity(new Intent(HomeActivity.this, FavoriteActivity.class));
}
return true;
}
private void signOut() {
AlertDialog confirmExit = new AlertDialog.Builder(this)
.setTitle("Sign Out")
.setMessage("Do you really want to Sign Out")
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Common.currentUser = null;
Common.currentRestaurant = null;
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(HomeActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}).create();
confirmExit.show();
}
//Register Event Bus
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
//Listen Event Bus
#Subscribe(threadMode = ThreadMode.MAIN)
public void processRestaurantLoadEvent(RestaurantLoadEvent event) {
if (event.isSuccess()){
displayBanner(event.getRestaurantList());
displayRestaurant(event.getRestaurantList());
}else{
Toast.makeText(this, "[RESTAURANT LOAD]" + event.getMessage(),
Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
private void displayRestaurant(List<Restaurant> restaurantList) {
MyRestaurantAdapter adapter = new MyRestaurantAdapter(this, restaurantList);
recyclerView.setAdapter(adapter);
}
private void displayBanner(List<Restaurant> restaurantList) {
banner_slider.setAdapter(new RestaurantSliderAdapter(restaurantList));
}
}
This is the Handles the loadEvent
package com.sensei.linkrestaurant.Model.EventBus;
import com.sensei.linkrestaurant.Model.Restaurant;
import java.util.List;
public class RestaurantLoadEvent {
private boolean success;
private String message;
private List<Restaurant> restaurantList;
public RestaurantLoadEvent() {
}
public RestaurantLoadEvent(boolean success, String message) {
this.success = success;
this.message = message;
}
public RestaurantLoadEvent(boolean success, List<Restaurant> restaurantList) {
this.success = success;
this.restaurantList = restaurantList;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Restaurant> getRestaurantList() {
return restaurantList;
}
public void setRestaurantList(List<Restaurant> restaurantList) {
this.restaurantList = restaurantList;
}
}
This is the Restaurant Class
package com.sensei.linkrestaurant.Model;
public class Restaurant {
//Remember all variable names has to be exactly as Json property return from API
//That will help Gson to parse it correctly
private int id;
private String name;
private String address;
private String phone;
private Float lat;
private Float lng;
private int userOwner;
private String image;
private String paymentUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Float getLat() {
return lat;
}
public void setLat(Float lat) {
this.lat = lat;
}
public Float getLng() {
return lng;
}
public void setLng(Float lng) {
this.lng = lng;
}
public int getUserOwner() {
return userOwner;
}
public void setUserOwner(int userOwner) {
this.userOwner = userOwner;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPaymentUrl() {
return paymentUrl;
}
public void setPaymentUrl(String paymentUrl) {
this.paymentUrl = paymentUrl;
}
}
This is the Retrofit client for the ILinkRestaurantAPI
#GET("restaurant")
Observable<RestaurantModel> getRestaurant(#HeaderMap Map<String, String> headers);
This is the Restaurant model
package com.sensei.linkrestaurant.Model;
import java.util.List;
public class RestaurantModel {
private boolean success;
private String message;
private List<Restaurant> result;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Restaurant> getResult() {
return result;
}
public void setResult(List<Restaurant> result) {
this.result = result;
}
}
I think you must change Observable to Observable<RestaurantModel[]>
or in anather place you have strign but API give array, check API response and compare with your model (use for example tool Postman)
try and give response if help
[EDIT]
try private String message[];
[EDIT2]
in API message it's not String it's Array of object
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 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?
I am making a chat app using Firebase. I have created a class called Chat Activity where the user can send or receive messages. Along with this, I am creating Notifications. For the initial stage, I am building the notification as soon as the ChatActivity is being created.
The content of the body is the last message that was sent. But when I sent the title of the notification to the name of the user, it does not display the title. I am obtaining the name of the user using a new function called "getNameFromRoll()". But this also returns null.
When a user signs up in the app, not only it is registered in the firebase users list, but also in a child in the database called "students" in an inner child called "profiles". getNameFromRoll() reads data from this child.
Here's the code:
ChatActivity:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NotificationCompat;
import android.support.v4.graphics.BitmapCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ForwardingListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by shubham on 03/02/17.
*/
public class ChatActivity extends AppCompatActivity {
public String chatName;
public String chatRoll;
public String messageText;
public String time;
public String name;
public String senderRoll;
public String mId;
public List<Messages> mMessages;
public List<Chats> mChats;
public RecyclerView mMessagesListView;
public MessageAdapter mMessageAdapter;
public EditText mMessageEditText;
public FloatingActionButton mSendFAB;
public FirebaseDatabase mDatabase;
public DatabaseReference mSenderDatabaseReference;
public DatabaseReference mRecieverDatabaseReference;
public DatabaseReference mRecieverChatsDatabaseReference;
public DatabaseReference mUsersDatabaseReference;
public ChildEventListener mChildEventListener;
public ChildEventListener mChatsChildEventListener;
public ChildEventListener mUserChildEventListener;
public Intent mServiceIntent;
public String IS_NAME_KEY = "com.app.shubhamjhunjhunwala.heritagecompanion_students.IS_NAMEKEY";
public String IS_MESSAGE_KEY = "com.app.shubhamjhunjhunwala.heritagecompanion_students.IS_MESSAGEKEY";
public ChatActivity() {
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final Intent intent = getIntent();
Bundle extras = intent.getExtras();
chatName = intent.getStringExtra(ChatsActivity.EXTRA_NAME);
chatRoll = intent.getStringExtra(ChatsActivity.EXTRA_ROLL);
setTitle(chatName);
SharedPreferences sharedPreferences = getSharedPreferences("HCS", 0);
senderRoll = sharedPreferences.getString(AuthenticationActivity.ROLL_SHARED_PREFERENCE_KEY, "");
mDatabase = FirebaseDatabase.getInstance();
mSenderDatabaseReference = mDatabase.getReference().child("chats").child(senderRoll).child("messages").child(chatRoll);
mRecieverDatabaseReference = mDatabase.getReference().child("chats").child(chatRoll).child("messages").child(senderRoll);
mRecieverChatsDatabaseReference = mDatabase.getReference().child("chats").child(chatRoll);
mUsersDatabaseReference = mDatabase.getReference().child("students").child("profiles");
mMessageEditText = (EditText) findViewById(R.id.message_edit_text);
mSendFAB = (FloatingActionButton) findViewById(R.id.send_fab);
mMessages = new ArrayList<>();
mChats = new ArrayList<>();
mMessagesListView = (RecyclerView) findViewById(R.id.messages_list_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mMessagesListView.setLayoutManager(layoutManager);
mMessageAdapter = new MessageAdapter(mMessages, senderRoll, chatRoll);
mMessagesListView.setAdapter(mMessageAdapter);
mSendFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messageText = mMessageEditText.getText().toString().trim();
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
time = df.format(c.getTime());
if (messageText != "") {
Messages message = new Messages(messageText, time, senderRoll, chatRoll, mId);
mSenderDatabaseReference.push().setValue(message);
mRecieverDatabaseReference.push().setValue(message);
}
mMessageEditText.setText("");
}
});
message();
}
public void message() {
mChildEventListener = new ChildEventListener() {
int n;
Chats chat;
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
Messages messages = dataSnapshot.getValue(Messages.class);
mMessages.add(messages);
mMessagesListView.scrollToPosition(mMessages.size() - 1);
mMessageAdapter.notifyItemInserted(mMessages.size() - 1);
notificationBuilder(ChatActivity.this, messages.getSender(), messages.getMessage());
n = setNewChatHeader();
if (n == 1) {
chat = new Chats(chatName, chatRoll);
mRecieverChatsDatabaseReference.setValue(chat);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mSenderDatabaseReference.addChildEventListener(mChildEventListener);
}
public int setNewChatHeader() {
mChatsChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
Chats chats = dataSnapshot.getValue(Chats.class);
if (chats.getName() != null) {
mChats.add(chats);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRecieverChatsDatabaseReference.addChildEventListener(mChatsChildEventListener);
if (mChats.size() != 0) {
for (int i = 0; i < mChats.size(); i++) {
Chats chat = mChats.get(i);
String name = chat.getName();
if (name.equals(chatName)) {
return 1;
}
}
}
return 0;
}
public String getSenderRoll() {
return senderRoll;
}
public void notificationBuilder(Context context, String name, String message) {
getNameFromRollNumber(name);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_message_notification_icon)
.setLargeIcon(largeIcon(context))
.setContentTitle(this.name)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mBuilder.setPriority(Notification.PRIORITY_HIGH);
}
Intent resultIntent = new Intent(this, ChatActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = 001;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public Bitmap largeIcon(Context context) {
Resources res = context.getResources();
Bitmap largeIcon = BitmapFactory.decodeResource(res, R.mipmap.ic_launcher);
return largeIcon;
}
public void getNameFromRollNumber (String roll) {
mUsersDatabaseReference = mUsersDatabaseReference.child(roll);
mUserChildEventListener = new ChildEventListener() {
ChatActivity chatActivity = new ChatActivity();
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserDetails userDetails = dataSnapshot.getValue(UserDetails.class);
chatActivity.setName(userDetails.getName());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mUsersDatabaseReference.addChildEventListener(mUserChildEventListener);
Toast.makeText(ChatActivity.this, name, Toast.LENGTH_SHORT).show();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserDetails.class:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by shubham on 23/01/17.
*/
public class UserDetails {
UserDetails() {}
public String name;
public String email;
public String password;
public String phone;
public String roll;
public String sharingKey;
public String department;
public String year;
public String section;
public UserDetails(String name, String email, String password, String phone, String roll, String sharingKey, String department, String year, String section) {
this.name = name;
this.email = email;
this.password = password;
this.phone = phone;
this.roll = roll;
this.sharingKey = sharingKey;
this.department = department;
this.year = year;
this.section = section;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getSharingKey() {
return sharingKey;
}
public void setSharingKey(String sharingKey) {
this.sharingKey = sharingKey;
}
}
The sample of the database Structure:
heritage-companion-students
chats
students
-Kcgc88CAieCWCWPvA8D
-KcgcNrZj2Saueyaejw5
-Kcgce-x43DaaYiHjTpK
-Kcgcqh1uJ8E_KgKDcq0
-Kcgd36xoBcdsJriqMjS
-KcgdHY9CxaoCQ9poEna
profiles
1657099
1657102
1657103
1657108
-Kcgc87aRCL_D1KXJypP
department:
email:
name:
password:
phone:
roll:
sharingKey:
1657113
1657120
I am using kinvey as my backend where I have a collection and would like to fetch data using appData.get. I have tried using the code below but it doesnt work. Could someone please tell me whats wrong with it.
package com.example.kinvey;
import com.kinvey.android.AsyncAppData;
import com.kinvey.android.callback.KinveyListCallback;
import com.kinvey.java.core.KinveyClientCallback;
import android.app.Activity;
import android.content.Entity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class ActionData extends Activity{
//protected static final String TAG = "LOG:";
public static final String TAG = "ActionData";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
public void onLoadClick(View view) {
AsyncAppData<Entity> myevents = MainActivity.mKinveyClient.appData("events",Entity.class);
myevents.get(new KinveyListCallback<Entity>() {
#Override
public void onSuccess(Entity[] result) {
Log.v(TAG, "received "+ result.length + " events");
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to fetch all", error);
}
});
}
And this is my Entity class.
package com.example.kinvey;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.kinvey.java.model.KinveyMetaData;
public class Entity extends GenericJson{
#Key("_id")
private String id;
#Key("_class")
private String _class;
#Key("author")
private String author;
#Key("relatedObj")
private String relatedObj;
#Key("relatedObjName")
private String relatedObjName;
#Key("type")
private String type;
#Key("_kmd")
private KinveyMetaData meta;
#Key("_acl")
private KinveyMetaData.AccessControlList acl;
public Entity(){}
public String getActionId() {
return id;
}
public void setActionId(String id) {
this.id = id;
}
public String getclass() {
return _class;
}
public void setclass(String _class) {
this._class = _class;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getRelatedObj() {
return relatedObj;
}
public void setRelatedObj(String relatedObj) {
this.relatedObj = relatedObj;
}
public String getRelatedObjName() {
return relatedObjName;
}
public void setRelatedObjName(String relatedObjName) {
this.relatedObjName = relatedObjName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}