I have used ignition in my app to cache my composite object,let say mStudentObject. I have cached my data successfully, the issue is , when i retrieve my object after killing app from recently running apps button(from currently running tasks button) ,i haven't fount any data against key(cached clear automatically).When i re-launch app (with out killing app from recent tasks) object retrieved properly.
i don't know what is wrong with code.I want to cache my object permanently for 2 days. when ever i launch my app,app should get data from cached object either i kill app from currently running tasks or not. Any idea,please share.Here is my complete code:
public class MainActivity extends Activity {
Button[] buttons = null;
// ObjectLRUCache objectLRUCache = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons = new Button[2];
buttons[0] = (Button) findViewById(R.id.button1);// to save data
buttons[1] = (Button) findViewById(R.id.button2); // to get data
// final Student s = new Student("imran", 23, 16);
buttons[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (IgnetionHelper.getInstance()!= null) {
Log.d("test", "key contains, updating");
Student s = new Student("imran", 23, 16);
IgnetionHelper.getInstance().putData(s);
} else{
Log.d(""test),"instance is null..");
}
});
buttons[1].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
IgnetionHelper ddd = IgnetionHelper.getInstance();
if (IgnetionHelper.getInstance().getData()!= null) {
Student s = (Student) IgnetionHelper.getInstance().getData();
Log.d("test", "key contains, age is: " + s.age);
} else {
Log.d("test", "data is null...");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and My Person class is as:
public abstract class Person extends CachedModel implements Serializable{
public String name = "";
public int age = 0;
public Person(){};
public Person (String name,int age) {
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Student class is as:
public class Student extends Person{
public String name = "";
public int age = 0;
public int rollNo = 0;
public Student(){
}
public Student(String name, int age, int rollno) {
this.rollNo = rollno;
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
#Override
public boolean reloadFromCachedModel(ModelCache modelCache,
CachedModel cachedModel) {
Student student = (Student) cachedModel;
name = student.name;
age = student.age;
rollNo = student.rollNo;
return false;
}
#Override
public String createKey(String id) {
// TODO Auto-generated method stub
return id;
}
}
And finally, ignition helper class is as:
public class IgnetionHelper {
private static final String KEY_FOR_MYOBJECT = "MY_TEST_KEY";
private static ModelCache cache;
private final static int initialCapacity = 1000;
private final static int maxConcurrentThreads = 3;
private final static long expirationInMinutes = 60 * 24 * 2;
private static IgnetionHelper mIgnetionHelper = null;
public static IgnetionHelper getInstance() {
if (cache == null)
cache = new ModelCache(initialCapacity, expirationInMinutes,
maxConcurrentThreads);
if (mIgnetionHelper == null)
mIgnetionHelper = new IgnetionHelper();
return mIgnetionHelper;
}
public boolean putData(CachedModel model) {
model.setId(KEY_FOR_MYOBJECT);
if (model.save(cache)) {
Log.d("IgnetionHelper", "saved.....");
return true;
} else {
Log.d("IgnetionHelper", "saved.....");
return false;
}
// CachedModel model = Feed.find(cache, key, Feed.class);
// if (model != null) {
// Log.d("test", "key contains, updating");
// Feed s = (Feed) model;
// return s.save(cache);
// }
}
public CachedModel getData() {
return Student.find(cache, KEY_FOR_MYOBJECT, Student.class);
}
}
i have found solution of my problem.
Let say you have student object
Student s = new Student("imran",16,23);
and then implement these methods in your ignetionhelper calss:
public static boolean putData(Object object, Context context,String key) {
return GenericStore.saveObject(GenericStore.TYPE_MEMDISKCACHE,key, (Serializable) object, context.getApplicationContext());
}
public static Object getData(Context context,String key) {
return GenericStore.getObject(GenericStore.TYPE_MEMDISKCACHE,key, context.getApplicationContext());
}
https://github.com/wareninja/generic-store-for-android
import library given hare and then use above methods as:
IgnetionHelper.putData(s, context, IgnetionHelper.YOUR_KAY);
Student s=(Student)IgnetionHelper.getData(context,IgnetionHelper.YOUR_KAY);
You will need to use a cache that is stored to disk, when the app is killed the cache you are using appears to be cleared.
There is some information from Google about cache storage here http://developer.android.com/guide/topics/data/data-storage.html and check out this existing SO answer on some options for data caching within your app Best Way to Cache Data in Android
Related
I have an ArrayList and I need to send it to another fragment. I tried to use Parcelable, but to send the data I need the "startIntent" method which starts the fragment. I don't want the fragment to be started.
I need send data array list object to another fragment without going to this other fragment. I only need to send the data. The user is free to chose when to change between activities/fragments. And the data sent earlier should already be there.
Example using Parcelable:
Class that must be to sent:
import android.os.Parcel;
import android.os.Parcelable;
public class Doenca implements Parcelable {
private String nome;
private String causa;
private String efeito;
private String cuidados;
private String prevencao;
private String categoria;
public Doenca(String nome, String causa, String efeito, String cuidados, String prevencao, String categoria) {
this.nome = nome;
this.causa = causa;
this.efeito = efeito;
this.cuidados = cuidados;
this.prevencao = prevencao;
this.categoria = categoria;
}
protected Doenca(Parcel in) {
nome = in.readString();
causa = in.readString();
efeito = in.readString();
cuidados = in.readString();
prevencao = in.readString();
categoria = in.readString();
}
public static final Creator<Doenca> CREATOR = new Creator<Doenca>() {
#Override
public Doenca createFromParcel(Parcel in) {
return new Doenca(in);
}
#Override
public Doenca[] newArray(int size) {
return new Doenca[size];
}
};
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCausa() {
return causa;
}
public void setCausa(String causa) {
this.causa = causa;
}
public String getEfeito() {
return efeito;
}
public void setEfeito(String efeito) {
this.efeito = efeito;
}
public String getCuidados() {
return cuidados;
}
public void setCuidados(String cuidados) {
this.cuidados = cuidados;
}
public String getPrevencao() {
return prevencao;
}
public void setPrevencao(String prevencao) {
this.prevencao = prevencao;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(nome);
dest.writeString(causa);
dest.writeString(efeito);
dest.writeString(cuidados);
dest.writeString(prevencao);
dest.writeString(categoria);
}
}
import android.os.Parcel;
import android.os.Parcelable;
public class Doenca implements Parcelable {
private String nome;
private String causa;
private String efeito;
private String cuidados;
private String prevencao;
private String categoria;
public Doenca(String nome, String causa, String efeito, String cuidados, String prevencao, String categoria) {
this.nome = nome;
this.causa = causa;
this.efeito = efeito;
this.cuidados = cuidados;
this.prevencao = prevencao;
this.categoria = categoria;
}
protected Doenca(Parcel in) {
nome = in.readString();
causa = in.readString();
efeito = in.readString();
cuidados = in.readString();
prevencao = in.readString();
categoria = in.readString();
}
public static final Creator<Doenca> CREATOR = new Creator<Doenca>() {
#Override
public Doenca createFromParcel(Parcel in) {
return new Doenca(in);
}
#Override
public Doenca[] newArray(int size) {
return new Doenca[size];
}
};
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCausa() {
return causa;
}
public void setCausa(String causa) {
this.causa = causa;
}
public String getEfeito() {
return efeito;
}
public void setEfeito(String efeito) {
this.efeito = efeito;
}
public String getCuidados() {
return cuidados;
}
public void setCuidados(String cuidados) {
this.cuidados = cuidados;
}
public String getPrevencao() {
return prevencao;
}
public void setPrevencao(String prevencao) {
this.prevencao = prevencao;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(nome);
dest.writeString(causa);
dest.writeString(efeito);
dest.writeString(cuidados);
dest.writeString(prevencao);
dest.writeString(categoria);
}
}
There are multiple ways with different complexity for the implementation.
Use a database to store what you need there
Store the data in the host activity containing the tabs. As soon as you switch the fragment, all you need to do is read the data from the place where you have stored it.
Use LiveData. LiveData would be my personal preference. There you can easily store any data you need and the second fragment simply observes the livedata and can easily react to changes. So you could even switch in both directions as often as you want to.
Try Using EventBus.
To use EventBus, you need to first add it to in the app module build.gradle file
implementation 'org.greenrobot:eventbus:3.1.1'
and then sync your project.
An Event Subscriber
A subscriber simply subscribes to an event by registering in the event bus and can also unregister that event. To be a subscriber, you have to do three main things:
Register the subscriber in the event bus with register(). This informs the event bus that you want to begin receiving events. In an activity, this is in the onStart() method, while in a fragment put this in the onAttact(Activity activity) method.
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
Unregister the subscriber, which means tell the event bus to stop sending me events. In an activity, this is in the onStop() method, while in a fragment put this in the onDetach() method.
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Implement the onEvent() to indicate the type of event you want to receive and action to take when you receive the event. Notice the #Subscribe annotation at the top of this method.
#Subscribe
public void onEvent(MessageEvent event) {
Toast.makeText(this, "Hey, my message" + event.getMessage(),
Toast.LENGTH_SHORT).show();.
}
Defining Event Messages
The events in greenrobot EventBus are just objects that you define. You can have different event classes if you want. They do not inherit any base class or interface—they're just POJO (Plain Old Java Objects).
public class MessageEvent {
public final List<SomeItem> items;
public MessageEvent(List<SomeItem> items) {
this.items= items;
}
}
Post Event
EventBus.getDefault().post(new MessageEvent("Hey event subscriber!"));
This question already has answers here:
How to save users score in firebase and retrieve it in real-time in Android studio
(3 answers)
Closed 3 years ago.
I'm beginner for developing.
I'm using Android studio, I've created App that retrieve data from Firebase Realtime database.
I know how to add operation for the click counter but it is not save
EX:"when i click on the button the TextView change to ++1, but if i closed the application and reopen it again it's show me 0 as I didn't any thing before, or even if I moved to other activity".
what I want to do is "count the click ++1 and store in firebase at the same time its update for all users who are using the application ((Retrieve data)).
So: my question is how to make the Click counter Store and Retrieve in a TextView?.
Here's the Image of what i want:
https://vigor-ads.com/wp-content/uploads/2018/11/TEST.png
And RealTimeDataBase:
https://vigor-ads.com/wp-content/uploads/2018/11/FireBase-RealTime.png
PharPolice.java
public class PharPolice extends Fragment {
private int ClicksCounter = 0;
private TextView counter;
DatabaseReference clicksref;
ListView listView;
FirebaseDatabase database;
DatabaseReference myRef;
ArrayList<String> list;
PolicePharmacies policePharmacies ;
FirebaseListAdapter adapter;
public PharPolice() {
// Required empty public constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phar_police, container, false);
}
//---------------------F I R E B A S E------------------------
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Query query = FirebaseDatabase.getInstance().getReference("PharmaciesDB").child("PolicePharmacies");
FirebaseListOptions<PolicePharmacies> options = new FirebaseListOptions.Builder<PolicePharmacies>()
.setLayout(R.layout.pharinfo)
.setQuery(query, PolicePharmacies.class)
.build();
clicksref = FirebaseDatabase.getInstance().getReference("PharmaciesDB").child("PolicePharmacies");
policePharmacies = new PolicePharmacies();
listView = view.findViewById(R.id.pharpoliceListView);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("PolicePharmacies");
list = new ArrayList<>();
adapter = new FirebaseListAdapter(options) {
#Override
protected void populateView(View v, final Object model, int position) {
CardView cv = v.findViewById(R.id.pharcard);
counter = v.findViewById(R.id.SACounter);
TextView Name = v.findViewById(R.id.SAName);
TextView Address = v.findViewById(R.id.SAAddress);
Name.setText(((PolicePharmacies) model).getName());
Address.setText(((PolicePharmacies) model).getAddress());
counter.setText(((PolicePharmacies) model).getClickCounter());
cv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visits();
Intent intent = new Intent(getActivity(), PharPoliceScreen.class);
intent.putExtra("Name", ((PolicePharmacies) model).getName());
intent.putExtra("Address", ((PolicePharmacies) model).getAddress());
intent.putExtra("Phone1", ((PolicePharmacies)model).getPhone1());
intent.putExtra("Phone2", ((PolicePharmacies)model).getPhone2());
intent.putExtra("Phone3", ((PolicePharmacies)model).getPhone3());
intent.putExtra("Offer", ((PolicePharmacies)model).getOffer());
intent.putExtra("Facebook", ((PolicePharmacies)model).getFacebook());
startActivity(intent);
}
});
}
};
listView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
private void Visits ()
{
ClicksCounter ++;
counter.setText(Integer.toString(ClicksCounter));
String clickCounter = counter.getText().toString().trim();
PolicePharmacies saveData = new PolicePharmacies(clickCounter);
clicksref.push().setValue(saveData);
}
//---------------------F I R E B A S E------------------------
PolicePharmacies.class
public class PolicePharmacies {
private String Name;
private String Address;
private String Phone1;
private String Phone2;
private String Phone3;
private String Offer;
private String Facebook;
private String ClickCounter;
public PolicePharmacies() {
}
public PolicePharmacies(String name, String address, String phone1, String phone2, String phone3, String offer, String facebook) {
Name = name;
Address = address;
Phone1 = phone1;
Phone2 = phone2;
Phone3 = phone3;
Offer = offer;
Facebook = facebook;
}
public PolicePharmacies(String clickCounter) {
ClickCounter = clickCounter;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getPhone1() {
return Phone1;
}
public void setPhone1(String phone1) {
Phone1 = phone1;
}
public String getPhone2() {
return Phone2;
}
public void setPhone2(String phone2) {
Phone2 = phone2;
}
public String getPhone3() {
return Phone3;
}
public void setPhone3(String phone3) {
Phone3 = phone3;
}
public String getOffer() {
return Offer;
}
public void setOffer(String offer) {
Offer = offer;
}
public String getFacebook() {
return Facebook;
}
public void setFacebook(String facebook) {
Facebook = facebook;
}
public String getClickCounter() {
return ClickCounter;
}
public void setClickCounter(String clickCounter) {
ClickCounter = clickCounter;
}
The problem is not in the code. The problem is in the logic. Try to imagine that there are two separate parts in this process. First step increase the number Second step show the result. So first step you can easy implement after reading this article about WRITING into firebase https://firebase.google.com/docs/database/admin/save-data
Now about second step how to show the result. First what you have to understand that TextView is not saving any data it just showing it. So to show the data you suppose to read it from firebase which you saved it on first step. The same article also showed how to read data. So when it is saved and when you received it ONLY after that you could show it in TextView.
Hope it helps
Hi guys I am trying to save objects with relations in Backendless via API. I have two classes namely Task and Reminder. A task can be associated with many reminders hence I want a 1:N relationship between the Task table and Reminder table in Backendless. My Task class is as follows:
public class Task {
public Date created;
public Date updated;
private List<Reminder> reminders = null;
private String ownerId;
#PrimaryKey
#NonNull
private String objectId;
#NonNull
private String taskTitle;
#NonNull
private Date deadline;
#NonNull
private int isCompleted = 0;
#NonNull
private int isExpired = 0;
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
#NonNull
public String getObjectId() {
return objectId;
}
public void setObjectId(#NonNull String objectId) {
this.objectId = objectId;
}
public List<Reminder> getReminders() {
return reminders;
}
public void setReminders(List<Reminder> reminders) {
this.reminders = reminders;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
#NonNull
public int getIsCompleted() {
return isCompleted;
}
public void setIsCompleted(#NonNull int isCompleted) {
this.isCompleted = isCompleted;
}
#NonNull
public int getIsExpired() {
return isExpired;
}
public void setIsExpired(#NonNull int isExpired) {
this.isExpired = isExpired;
}
public String getTaskTitle() {
return taskTitle;
}
public void setTaskTitle(String taskTitle) {
this.taskTitle = taskTitle;
}
public Date getDeadline() {
return deadline;
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
}
Reminder Class:
public class Reminder {
private String title;
private Date time;
private String objectId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
}
I am saving the objects and setting up the relation as below:
public void saveTaskToServer(final Task task) {
List<Reminder> remindersList = new ArrayList<>();
remindersList = task.getReminders();
final List<Reminder> savedReminders = new ArrayList<>();
if(remindersList!=null && remindersList.size()!=0) {
for
(Reminder reminder : remindersList) {
reminder.setTitle(task.getTaskTitle());
Backendless.Persistence.save(reminder, new AsyncCallback<Reminder>() {
#Override
public void handleResponse(Reminder response) {
savedReminders.add(response);
}
#Override
public void handleFault(BackendlessFault fault) {
Log.i("error saving remidners", fault.toString());
}
});
}
}
Backendless.Persistence.save(task, new AsyncCallback<Task>() {
#Override
public void handleResponse(Task response) {
newTask = response;
Log.i("id is ", newTask.getObjectId());
insertTask(response);
snackbarMessage.postValue("Task Created Successfully.");
}
#Override
public void handleFault(BackendlessFault fault) {
Log.i("error", fault.getMessage());
}
});
Backendless.Persistence.of(Task.class).addRelation(task, "reminders", savedReminders, new AsyncCallback<Integer>() {
#Override
public void handleResponse(Integer response) {
Log.i("response", "added" + response);
newTask.setReminders(savedReminders);
}
#Override
public void handleFault(BackendlessFault fault) {
Log.i("response", "error" + fault.toString());
}
});
}
I have tried saving the relation using the tablename:Class:n instead of the parentColumnName. Also tried saving the objectids of the reminders instead of the reminder objects themselves.The task and reminder objects get saved properly in the backendless console in their respective tables but the reminder column in the Task table still remains empty and no relations get added. Relations count in the backendless call in Android Studio also returns 0. Any advice is really appreciated. I have been following this example.
My relations were not getting saved because I was using the async callbacks in backendless!! I dont know why I didnt see that before. Since the save calls were being made before the async callbacks could finish I was ending up with null values. Fixed it by making the calls synchronous and wrapping them in an async task.
I have 2 class one is login_class second is student_class which is showing details of student.
What i have to do is when i login. In response i get the students details like
student_name,student_srno,student_father_name,student_mother_name etc.
This is my bean(Getter Setter) class
package com.smartschoolapp;
public class Bean {
String username, password, srno, studentname, classname, sec, contact,
father_name, mother_name, dob;
public Bean(String username,String password,String srno,String studentname,String classname,String sec,String contact,String father_name,String mother_name,String dob) {
this.username=username;
this.password= password;
this.srno=srno;
this.studentname=studentname;
this.classname=classname;
this.sec=sec;
this.contact=contact;
this.father_name=father_name;
this.mother_name=mother_name;
this.dob =dob;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSrno() {
return srno;
}
public void setSrno(String srno) {
this.srno = srno;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getSec() {
return sec;
}
public void setSec(String sec) {
this.sec = sec;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getFather_name() {
return father_name;
}
public void setFather_name(String father_name) {
this.father_name = father_name;
}
public String getMother_name() {
return mother_name;
}
public void setMother_name(String mother_name) {
this.mother_name = mother_name;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public Bean() {
}
}
And this is my login_class where i add data of the student in list.
class login_class extends activity{
Bean beanobj;
List student_detail_list;
.....
{
String name = getting data from response;
......... so on
beanobj = new Bean();
beanobj.studentname(name);
beanobj.student_parent_name(parentname);
.............so on
}
order_list.add(beanobj); // the details to list
}
Now the next activity student_class where i want to show the student in listview
public class student_class extends Activity {
ListView student_listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
student_listview = (ListView) findViewById(R.id.student_listview);
}
}
*==>> in login_class i have created List student_detail_list how can i get it in my student_class class and retrieve data .
Thanks
There are a lot a ways to do that. 1.Recommended Solution : How to pass an object from one activity to another on Android you can serialize your objects and put it into the intent. This is the recommended solution but there are some problems here. If your data contains a lot of memory, it might crash your application in runtime.
2. You can save your array into the file, send file path to other activity as with URL. In the second activity read the file and create the array in second activity as well.
3. My favourite solution is create a singleton class for student array, reach the class in any activity you want. But you should be careful because singleton pattern has some issues by design also it will stay in memory all the time
Realize the "class Bean implements Parcelable". When go to "student_class" from "login_class", just put the "student bean data" inside the Intent. After going to student_class, you can get the "student bean data" from the intent, here the sample code:
Intent intent = new Intent(login_class.this, student_class.class)
intent.putParcelableArrayListExtra("content", student_detail_list);
startActivity(intent);
In "student_class":
student_detail_list = getIntent().getParcelableArrayListExtra("content");
I am saving data to a RealmObject then adding it to my Realm. After leaving the activity and returning the RealmObject is retrieved and the EditText are loaded with the appropriate data. All the EditText but one, Company Address, are loading correctly and I can't figure out why when all save and loading information is the same. Any ideas?
Activity
public class NewLocation extends ActionBarActivity {
public EditText editCoName;
public EditText editCoAddress;
public EditText editCoContact;
public EditText editSqFt;
public EditText editTaxed;
public EditText editConcerns;
private Realm realm;
public CompanyInfo companyInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_location);
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveInfo();
Intent i = new Intent(NewLocation.this, RoomList.class);
startActivity(i);
}
});
editCoName = (EditText) findViewById(R.id.CoName);
editCoAddress = (EditText) findViewById(R.id.CoAddress);
editCoContact = (EditText) findViewById(R.id.CoContact);
editSqFt = (EditText) findViewById(R.id.SqFt);
editTaxed = (EditText) findViewById(R.id.Taxed);
editConcerns = (EditText) findViewById(R.id.Concerns);
//initialize realm and make CompanyInfo object if there is not already one
realm = Realm.getInstance(this);
CompanyInfo result = realm.where(CompanyInfo.class).findFirst();
if (result == null){
realm.beginTransaction();
companyInfo = realm.createObject(CompanyInfo.class);
companyInfo.setName(editCoName.getText().toString());
companyInfo.setAddress(editCoAddress.getText().toString());
companyInfo.setContact(editCoContact.getText().toString());
companyInfo.setTaxed(editTaxed.getText().toString());
companyInfo.setSqFt(editSqFt.getText().toString());
companyInfo.setConcerns(editConcerns.getText().toString());
realm.commitTransaction();
}
else {
editCoName.setText(result.getName());
editCoAddress.setText(result.getAddress());
editCoContact.setText(result.getContact());
editTaxed.setText(result.getTaxed());
editSqFt.setText(result.getSqFt());
editConcerns.setText(result.getConcerns());
}
}
#Override
protected void onResume() {
super.onResume();
LoadInfo();
}
#Override
protected void onPause() {
super.onPause();
SaveInfo();
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
public void SaveInfo() {
//save all info from the page
companyInfo = realm.where(CompanyInfo.class).findFirst();
realm.beginTransaction();
companyInfo.setName(editCoName.getText().toString());
companyInfo.setAddress(editCoAddress.getText().toString());
companyInfo.setContact(editCoContact.getText().toString());
companyInfo.setTaxed(editTaxed.getText().toString());
companyInfo.setSqFt(editSqFt.getText().toString());
companyInfo.setConcerns(editConcerns.getText().toString());
realm.copyToRealmOrUpdate(companyInfo);
realm.commitTransaction();
}
public void LoadInfo() {
//load info fom the CompanyInfo and put it into EditTexts
companyInfo = realm.where(CompanyInfo.class).findFirst();
if (companyInfo != null) {
editCoName.setText(companyInfo.getName());
editCoAddress.setText(companyInfo.getAddress());
editCoContact.setText(companyInfo.getContact());
editTaxed.setText(companyInfo.getTaxed());
editSqFt.setText(companyInfo.getSqFt());
editConcerns.setText(companyInfo.getConcerns());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(item.getItemId())
{
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
CompanyInfo class
public class CompanyInfo extends RealmObject{
#PrimaryKey
private String Name;
#Ignore
private String Address;
private String Contact;
private String sqFt;
private String taxed;
private String concerns;
private RealmList<Rooms> rooms = new RealmList<>();
public RealmList<Rooms> getRooms() {
return rooms;
}
public void setRooms(RealmList<Rooms> rooms) {
this.rooms = rooms;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public String getContact() {
return Contact;
}
public String getSqFt() {
return sqFt;
}
public String getTaxed() {
return taxed;
}
public String getConcerns() {
return concerns;
}
public void setName(String coName) {
this.Name = coName;
}
public void setAddress(String coAddress) {
this.Address = coAddress;
}
public void setContact(String coContact) {
this.Contact = coContact;
}
public void setSqFt(String sqFt) {
this.sqFt = sqFt;
}
public void setTaxed(String taxed) {
this.taxed = taxed;
}
public void setConcerns(String concerns) {
this.concerns = concerns;
}
}
You have an #Ignore annotation on CompanyInfo#Adresse, remove it and Realm will save the adress.