2 Key Questions in Firebase - java

I am using Firebase.
1. Question:
I create a Key with:
final String CHATS_CHILD = "chats/" + mFirebaseDatabaseReference.push().getKey();
mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue("and so on...");
The result you see in the picture. Now I created a key with childrens in Firebase but how to I get the key into my android app? (I mean the first key, after Chats)
2. Qestion is similar
You see the databe in my Picture. How can I get the first key after chats, when I search after the text? So for example I want the key which has as child the Text "Test1"
How to do that?
Thanks in advance.

I think you should flatten your data in order to get message key and chat key using just message text. You can keep actual messages in a separate path (like "messages") and keep only message keys inside related chat's path, as shown in the following structure:
Create Chat class:
public class Chat {
private Map<String, Boolean> messageKeys;
public Chat() {
// Default constructor required for calls to DataSnapshot.getValue(Chat.class)
}
public Chat(Map<String, Boolean> messageKeys) {
this.messageKeys = messageKeys;
}
public Map<String, Boolean> getMessageKeys() {
return messageKeys;
}
public void setMessageKeys(Map<String, Boolean> messageKeys) {
this.messageKeys = messageKeys;
}
}
..and Message class:
public class Message {
private String chatKey;
private String text;
private long time;
public Message() {
// Default constructor required for calls to DataSnapshot.getValue(Message.class)
}
public Message(String chatKey, String text, long time) {
this.chatKey = chatKey;
this.text = text;
this.time = time;
}
public String getChatKey() {
return chatKey;
}
public void setChatKey(String chatKey) {
this.chatKey = chatKey;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
Then query messages and find those whose text field is equal to the term you are searching, for example "Test1":
DatabaseReference chatsRef = FirebaseDatabase.getInstance().getReference("chats");
DatabaseReference messagesRef = FirebaseDatabase.getInstance().getReference("messages");
messagesRef.orderByChild("text").equalTo("Test1").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String messageKey = child.getKey();
Message message = child.getValue(Message.class);
String chatKey = message.getChatKey();
// Now you have both the chatKey and the messageKey...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Creating a new chat and its first message would look like below in this case (can be considered as answer to your first question):
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String chatKey = rootRef.push().getKey();
String messageKey = rootRef.push().getKey();
Message newMessage = new Message(chatKey, "My message trial", Calendar.getInstance().getTimeInMillis());
Map<String, Boolean> messageKeys = new LinkedHashMap<>();
messageKeys.put(messageKey, true);
Chat newChat = new Chat(messageKeys);
rootRef.child("messages").child(messageKey).setValue(newMessage);
rootRef.child("chats").child(chatKey).setValue(newChat);
Retrieving all messages that belongs to a chat whose key is known:
String chatKey = "chatKey1"; // Get it somehow
DatabaseReference messagesRef = FirebaseDatabase.getInstance().getReference("messages");
messagesRef.orderByChild("chatKey").equalTo(chatKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Message> messageList = new ArrayList<>();
for (DataSnapshot child : dataSnapshot.getChildren()) {
String messageKey = child.getKey();
Message message = child.getValue(Message.class);
messageList.add(message);
}
// Now you have all messages in messageList...
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

in additional to answer of Mehmed: Firebase DB supports not only setting/retrieving single fields, but also whole the objects of some class.
In the example below I define class MyChat, create few objects of it and put them into Firebase DB. Then I retrieve all of them (as objects, not just strings) and put them into ArrayList.
FirebaseDatabase frDb = FirebaseDatabase.getInstance();
DatabaseReference mFirebaseDatabaseReference = frDb.getReference();
final String CHATS_CHILD = "chats/theChat" ; //+ mFirebaseDatabaseReference.push().getKey();
// Create 3 objects of class MyChat
MyChat chat1 = new MyChat("Test1", "21-Sep-2017");
MyChat chat2 = new MyChat("Test21", "26-Sep-2017");
MyChat chat3 = new MyChat("TestB", "28-Sep-2010");
//Add all the chats to Firebase DB
mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue(chat1);
mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue(chat2);
mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue(chat3);
// Here we will retrieve all the chats and put them to array
// Declare array to keep results
final ArrayList<MyChat> arr1 = new ArrayList<MyChat>();
//Listener
ChildEventListener chEvLst = mFirebaseDatabaseReference.child("chats").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot ds1 : dataSnapshot.getChildren()) {
MyChat chatRes = ds1.getValue(MyChat.class);
Log.i("Next chat text:",chatRes.getmText());
Log.i("Next chat date:",chatRes.getmText());
arr1.add(chatRes); // retrieve and save chats to array
}
}
#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) {
}
});
And this is class MyChat
public class MyChat {
String mText = "Test1"; // default values...
String mDate = "26-Sep-2017";
// *** MUST TO HAVE EMPTY CONSTUCTOR FOR FIREBASE !!! ***
public MyChat() {
}
// Second constructor
public MyChat(String mText, String mDate) {
this.mText = mText;
this.mDate = mDate;
}
// *** MUST TO HAVE ALL GETTERS/SETTERS FOR FIREBASE!!! ***
// Getters/setters
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
}
And this is resulting DB structure :
Best regards!

Related

can't migrate the dates from firebase to my class (No setter/field warning)

I try to save of my SQLite database some records from the Firebase database.
My code to access the firebase and to store the information's in an ArrayList is:
private List<PoIs> LocoList;
LocoList = new ArrayList<>();
FirebaseApp.initializeApp(this);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
ref = FirebaseDatabase.getInstance().getReference("DATABASE");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
LocoList.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
PoIs loco = dataSnapshot.getValue(PoIs.class);
LocoList.add(loco);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);
The PoIs class looks like this:
public class PoIs {
private Integer _location_id;
private String _location_name;
private String _location_address;
private String _location_description;
private String _location_county;
public PoIs(){}
public PoIs(Integer _location_id, String _location_name, String _location_address,String _location_description, String _location_county) {
this._location_id = _location_id;
this._location_name = _location_name;
this._location_address = _location_address;
this._location_description = _location_description;
this._location_county = _location_county;
}
#PropertyName("_location_description")
public String get_location_description() {
return _location_description;
}
#PropertyName("_location_description")
public void set_location_description(String _location_description) {
this._location_description = _location_description;
}
My firebase structure look like this:
{
"DATABASE": {
"PoI_100": {
"_location_address": "Comuna Sâmbăta ",
"_location_county": "BRASOV",
"_location_description": "N/A",
"_location_id": 100,
"_location_name": "Mănăstirea Sâmbăta (Brâncoveanu)",
},
"PoI_1000": {
"_location_address": "Costinești ",
"_location_county": "CONSTANTA",
"_location_description": "N/A",
"_location_id": 1000,
"_location_name": "Teatrul de Vară",
},
"PoI_1001": {
"_location_address": "Olimp",
"_location_county": "CONSTANTA",
"_location_description": "N/A",
"_location_id": 1001,
"_location_image": "-",
"_location_name": "Plaja Olimp",
},
...
All are in a child node named "database".
Unfortunately, I get a warning like no setter/field exists for my class. Any idea?
You're getting the following warning:
No setter/field warning
Because the names of the fields in your class are different than the ones in the database. For example, in your class, you have a field called location_address while in the database is called _location_address. See the _ (underscore) with which the field starts? That's the reason why you get that warning. To solve this, you either modify the names of the fields in the class to match the ones in the database, or you use an annotation in front of the public getter slike this:
#PropertyName("_location_address") //👈
public String getLocation_address() {
return location_address;
}
Problem was here:
if (dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
///// HERE: I used dataSnapshot instead ds
PoIs loco = dataSnapshot.getValue(PoIs.class);
/////
LocoList.add(loco);
}
}
Was enough to replace with
PoIs loco = ds.getValue(PoIs.class);

Java, Android / Stored values in an arraylist, but list is empty

I stored datas from the database to an arrayList called nameList.
Within the function 'get_spinner_info', the values are successfully stored within the nameList.
However, there is no value for nameList outside of this function.
The error code is
" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 ".
I really need your help.
public class my_Item {
private Context context;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference datebaseReference = firebaseDatabase.getReference();
ArrayList<String> nameList = new ArrayList<String>();
// Get the value from the database and put them in the 'nameList'.
//In this code, I can successfully check the value within the 'nameList'.
public void get_spinner_info(String brand, String item, String prod_key){
datebaseReference.child(brand).child(item).child(prod_key).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.child("myValue").getChildren()) {
String prod_name = ds.getValue().toString();
nameList.add(prod_name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// But the nameList is empty in this part.
public void callFunction(final String brand, final String item, final String product_name, final String product_key, final int product_Num) {
get_spinner_info(brand, item, product_key);
Log.d("Spinner namelist : ", nameList.get(0));
}
}
get_spinner_info method starts and ASYNCHRONOUS data loading (registers lsitener), thus onDataChange will get called after Log.d("Spinner nameList : ", nameList.get(0));
your data will be available only after onDataChange call, which may take some time. get_spinner_info just starts loading your data, doesn't means that all data will be available just after method call ends
put this on the end of onDataChange (after current for loop) to check your items available/present in array
for (String name : nameList) Log.d("Spinner", "name: " + name);
Synchronization problem cause this kind of error
if you already have data do this
create interface class
public interface DataCallback {
public void reciveData(ArrayList<String> nameList ,boolean isOk);
}
In your class my_Item call the interface like this
public void get_spinner_info(String brand,String item,String prod_key,DataCallback callback){
datebaseReference.child(brand).child(item).child(prod_key).addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot){
for(DataSnapshot ds:dataSnapshot.child("myValue").getChildren()){
String prod_name=ds.getValue().toString();
nameList.add(prod_name);
}
// here you should check if the result available or NOT to prevent null exceptions
if(nameList.size()>0){
callback.reciveData(nameList,true);// true and false used to check data if available or null
}
else{
callback.reciveData(nameList,false);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError){
}
});
}
Now when you call get_spinner_info you need the callback Like this
get_spinner_info(brand, item, product_key,new DataCallback() {
#Override
public void callback(ArrayList<String> nameList, boolean isOk) {
if (isOk){
/// you have all data recived
Log.d("Spinner namelist : ", nameList.get(0));
}else {
// no data available
Log.i("TAG", "callback: No Data Available");
}
}
}););

Reading an object from a Firebase database in android studio

Using Android Studio and Firebase, i'm trying to write and read some data.
I have a Pub Class which contains the folowing:
package com.example.jef.pubbuddy.Database;
import java.util.ArrayList;
public class Pub {
private String name;
private float longitude;
private float lattitude;
private ArrayList<Pub> Pubs = new ArrayList<>();
public Pub() {}
public void setName(String name)
{this.name = name;}
public void setLongitude(float longitude)
{this.longitude = longitude;}
public void setLatitude(float lattitude)
{this.lattitude = lattitude;}
public String getName()
{return name;}
public float getLatitude()
{return lattitude;}
public float getLongitude()
{return longitude;}
I write my Pub object to the database using the .push() method. Below is how i write it to the database. It appears just fine in the Firebase console, so I believe the problem doesn't lie here:
Pub p1 = new Pub();
p1.setName("The name of the pub");
p1.setLatitude((float) 4.699545);
p1.setLongitude((float) 50.878267);
myRef.child("PUSH_TEST").push().setValue(p1);
Afterwards I try to read it using the following code. Please note the message method is just used to append some information to a TextView, so i'm able to debug on my physical device. However, none of the listener events get triggered.
Does anyone knows what i'm doing wrong here? Already followed the official firebase documentation and the "Firebase in a weekend" training videos. Also looked up countless answers here on Stackoverflow, but I can't seem to make it work.
Thanks in advance.
public class Database extends AppCompatActivity {
private TextView tv;
int messages;
private ArrayList<Pub> pubList = new ArrayList();
private FirebaseDatabase database;
private DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
init();
writeData();
message("creating and attaching the listener");
ChildEventListener myListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{
message("The childEvent triggered");
Pub p = dataSnapshot.getValue(Pub.class);
message("The name of this pub = " + p.getName());
pubList.add(p);
}
#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) {}
};
myRef.child("PUSHTEST").addChildEventListener(myListener);
}
Everything is correct, except this:
Here you set the value:
myRef.child("PUSH_TEST").push().setValue(p1);
and here you retrieve the value:
myRef.child("PUSHTEST").addChildEventListener(myListener);
the child that you wrote is wrong as it is not in your database. So just change it into this:
myRef.child("PUSH_TEST").addChildEventListener(myListener);
the name inside child(..) needs to be the same as in your database
You write data to "PUSH_TEST" child and trying to read from "PUSHTEST". Make it same.
For not getting similar errors in future, create a class called "Constants.java" and add constant strings inside it. Like,
public class Constants {
public static final String CHILD_NODE="PUSH_TEST";
}
So that , you can use this constant, where ever u need. Just call Constants.CHILD_NODE. So there will not be such errors.

How to reuse a method from a different class

I have an authenticateID method which searches in the database to find a match and does something. I guess it will take long to explain so here is my code:
public boolean authenticateStudentID() {
boolean success = true;
final String studentID = etStudentID.getText().toString().trim();
final String module = etModule.getText().toString().trim();
final String degree = etDegree.getText().toString().trim();
final String room = etRoom.getText().toString().trim();
final String email = etEmail.getText().toString().trim();
final String fullname = etfullname.getText().toString().trim();
final String loginID = etLoginID.getText().toString().trim();
if (success) {
databaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // wtf is this advanecd for loop
//map string string because our key is a string and value is a string, map has a key and value object
Map<String, String> map = (Map) snapshot.getValue();
if (map != null) { //if the values and keys are not null
String studentIDMatch = map.get("studentID");
// Log.v("E_VALUE", "students ID entered : " + studentIDMatch);
// Log.v("E_VALUE", "students ID from db: " + studentID);
if (studentID.equals(studentIDMatch)) {
String uniqueKey = databaseRef.push().getKey();
NewStudentAccounts sam = new NewStudentAccounts
(studentID, loginID, email, fullname, module, degree, room);
databaseRef.child(uniqueKey).setValue(sam);
Toast.makeText(getApplicationContext(), "Your account registration has been successful!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Invalid Student Credentials Entered!!", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
return success;
I want to know how I can reuse this method for another class instead of copy and pasting code. Please guide me, I really appreciate it.
private void addNewStudent() {
findViewById(R.id.buttonAddStudent).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View addStudentActivityDialog = LayoutInflater.from(LecturerAccount.this).inflate(R.layout.activity_add_student,null);
etStudentName = addStudentActivityDialog.findViewById(R.id.editTextStudentName);
etStudentUserID = addStudentActivityDialog.findViewById(R.id.editTextStudentUserID);
AlertDialog.Builder addStudentBuilder = new AlertDialog.Builder(LecturerAccount.this);
addStudentBuilder.setMessage("STAR").setView(addStudentActivityDialog).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String studentName = etStudentName.getText().toString();
String studentID = etStudentUserID.getText().toString();
registerActivity = new RegisterActivity(); //calling the instance of the class here
if (registerActivity.authenticateStudentID() == true){
studentarray.add(studentName);
}
}
}).setNegativeButton("cancel", null).setCancelable(false);
AlertDialog newStudentDialog = addStudentBuilder.create();
newStudentDialog.show();
}
});
}
My if statement here calling the function, I am totally clueless here.
Since onDataChange(DataSnapshot dataSnapshot) is an asynchronous callback event from firebase you must implement your own callback method to get notified of the result.
One approach would be to use interfaces.
create a separate class Auth
public class Auth {
public static void authenticateStudentID(final String studentID, final AuthListener listener) {
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("your reference");
databaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // wtf is this advanecd for loop
//map string string because our key is a string and value is a string, map has a key and value object
Map<String, String> map = (Map) snapshot.getValue();
if (map != null) { //if the values and keys are not null
String studentIDMatch = map.get("studentID");
if (studentID.equals(studentIDMatch)) {
if (listener != null)
listener.onAuthSuccess();
} else {
if (listener != null)
listener.onAuthFailure();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
if (listener != null)
listener.onAuthFailure();
}
});
}
public interface AuthListener {
void onAuthSuccess();
void onAuthFailure();
}
}
And then call it by
Auth.authenticateStudentID(studentId, new Auth.AuthListener() {
#Override
public void onAuthSuccess() {
}
#Override
public void onAuthFailure() {
}
});
wherever required
As the method you want to reuse should be "public" first of all. It simply means that it can be publically accessed among other classes of that project. And after making it public you can simply refer it using the class name.
Here is an example of this :
Class2 instance = new Class2();
instance.publicMehtodToBeAcessedInThisClass(any parameters);
But in your case, you will have to copy and paste the code to another class file only.
Reason: Because you are fetching data from the layout file of your Java file and this will crash the app. Either you should further modularize your code and handle this by making a separate function for fetching all this data. Otherwise, copy pasting only a method from one class to another will not make your application run into any performance issue or lags.
Access modifier is incorrect. Good old java doc will explain better than me:
access modifiers
In order to access it, you have to create an instance like so:
YourClass yourClass = new YourClass();
yourCLass.authenticateStudentID();
The YourClass is usually the name of the file where this code you pasted located in.
From what you've shown, there are two issues you need to deal with:
As noted, having it private doesn't do you much good when it comes to reuse.
It looks like the databaseRef object is a class property. So you'll need to pass this in, rather than rely on the class property for that class, since you want to use it from another class. (Or you can put this method, and the databaseRef property, in a superclass and have your two classes inherit from it.)
In general - think about what your method needs to do, and then what it needs to do that. Those should shape how you make the method more usable from other parts of your code.

Robospice + Retrofit + ORMLite

I'm using Robospice with Retrofit ans ORMLite modules. Retrofit part working good. I have City model for Retrofit:
City.java:
public class City {
public int city_id;
public String name;
#SuppressWarnings("serial")
public static class List extends ArrayList<City> {
}
}
I'm taking this model from server by GET-request:
MyApi.java
public interface MyAPI {
#GET("/cities")
City.List getCities();
}
This part works fine by calling this method:
getSpiceManager().execute(mRequestCity, "city", DurationInMillis.ONE_MINUTE, new ListCityRequestListener());
and listener:
public final class ListCityRequestListener implements RequestListener<City.List> {
#Override
public void onRequestFailure(SpiceException spiceException) {
Toast.makeText(RegisterActivity.this, "failure", Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestSuccess(final City.List result) {
Toast.makeText(RegisterActivity.this, "success", Toast.LENGTH_SHORT).show();
updateCities(result);
}
}
At this time i want to download city list once from server and store this list into sqlitedb by ORMLite module. I've created ORMLite model:
City.java
#DatabaseTable(tableName = "city")
public class City {
public final static String DB_CITY_ID_FIELD_NAME = "id";
public final static String DB_CITY_NAME_FIELD_NAME = "name";
#DatabaseField(canBeNull = false, dataType = DataType.INTEGER, columnName = DB_CITY_ID_FIELD_NAME)
int id;
#DatabaseField(canBeNull = false, dataType = DataType.STRING, columnName = DB_CITY_NAME_FIELD_NAME)
private String name;
public City() {
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("id = ").append(id);
sb.append(", ").append("name = ").append(name);
return sb.toString();
}
}
My RetrofitSpiceService.java looks like this:
public class RetrofitSpiceService extends RetrofitGsonSpiceService {
private final static String BASE_URL = "http://example.com/api/v1";
private final static UserFunctions userFunctions = new UserFunctions();
#Override
public CacheManager createCacheManager(Application application) throws CacheCreationException {
CacheManager cacheManager = new CacheManager();
List< Class< ? >> classCollection = new ArrayList< Class< ? >>();
// add persisted classes to class collection
classCollection.add( City.class );
// init
RoboSpiceDatabaseHelper databaseHelper = new RoboSpiceDatabaseHelper( application, "sample_database.db", 1 );
InDatabaseObjectPersisterFactory inDatabaseObjectPersisterFactory = new InDatabaseObjectPersisterFactory( application, databaseHelper, classCollection );
cacheManager.addPersister( inDatabaseObjectPersisterFactory );
return cacheManager;
}
#Override
protected Builder createRestAdapterBuilder() {
Builder mBuilder = super.createRestAdapterBuilder();
mBuilder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
if (userFunctions.isUserLoggedIn()) {
request.addHeader("Authorization", userFunctions.getToken());
}
}
});
return mBuilder;
}
#Override
public void onCreate() {
super.onCreate();
addRetrofitInterface(MyAPI.class);
}
#Override
protected String getServerUrl() {
return BASE_URL;
}
}
I can't understand how can i store and read data from my City database? How do i need to change RetrofitSpiceService? I want download data by Retrofit and store it to database by ORMLite. My CacheManager is correct, i.e. will work properly? Maybe I misunderstand how the module Robospice-ORMLite works?
Thanks a lot!
When you make execute() call with cache key and duration Robospice will store your response into database.
getSpiceManager().execute(mRequestCity, "city", DurationInMillis.ONE_MINUTE, new ListCityRequestListener());
All following requests during one minute will get data from this cache, and then it makes network call. If you want to get data only from cache take a look on getSpiceManager().getFromCache() method. I think it's what you are looking for.

Categories

Resources