Is it any way for me to get the next available ID for a table row (that would be automatically created when inserting a row in the table), so I would not be forced to insert that row at a given time, to get it?
To be more precise: I have an activity which contains a listview and each of those items are added using a second activity. When I finish adding the item details in the second activity, I pass that item through a parcelable object (I implemented Parcelable Interface to one of the holders class that DaoGenerator created). The id value of that object can not be null, to pass it with writeLong(id), and receive it with readLong() in my Parcelable methods, so I have to auto-generate the id value, by inserting the current item already in the database.
What I would like to do is: generate those IDs (without inserting the item in the database), pass that item to first activity, and when user decides to save all those items from the list, I would add all of them to database in a single transaction.
some sample code I have atm:
public class Question implements Parcelable {
private Long id;
private String questionContent;
// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END
public Question() {
}
public Question(Long id) {
this.id = id;
}
public Question(Long id,String questionContent) {
this.id = id;
this.questionContent = questionContent;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// KEEP METHODS - put your custom methods here
// begin Parcelable implementation
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(questionContent);
}
public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {
public Question createFromParcel(Parcel in) {
return new Question(in);
}
public Question[] newArray(int size) {
return new Question[size];
}
};
private Question(Parcel in) {
id = in.readLong();
questionContent = in.readString();
}
// end Parcelable implementation
// KEEP METHODS END
}
and this is how I create and send the item to list:
Question questionHolder = new Question(
null, etItemContent.getText().toString() .trim(),);
Log.d(LOG_TAG, "question id = "
+ questionHolder.getId());
// inserting it here, would auto-generate the ID I required,
// but I would like to do that to all of the items in the first Activity (containing the list of all of the items)
// questionDao.insert(questionHolder);
Log.d(LOG_TAG, "question id = "
+ questionHolder.getId());
// add item to intent
Bundle b = new Bundle();
b.putParcelable(IMPORTANCE_TAG, questionHolder);
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK, intent);
QuestionItemActivity.this.finish();
I would not suggest this as it create too much tight coupling.
a couple options that comes to my mind:
If a field is nullable, I would suggest adding another flag to parcelable to denote if that field is null or not.
so when writing
if(id == null) {
out.writeByte((byte)0);
} else {
out.writeByte((byte)1);
out.writeLong(id);
}
and when reading
boolean hasId = in.readByte() == 1;
if(hasId) {
id = in.readLong();
}
Another option, since db ids start from 1, you can set id to 0 and handle this logically. so when you receive the object in your first activity, you can check the id and set to null if it is 0.
Yes there's a mean to do that, if you're using an ORM, this would be easy as !##%.
All you have to do for example is:
Get the sequence name that generates the ID (there's always one even if you didn't create it manually).
Create an SQL query in your code for example :
session.createSQLQuery( "SELECT nextval( 'mySequenceName' )");
Then execute the query to retrieve the unique ID.
I hope this will help.
Cheers
Related
I have a Dictionary app where I want to assign existing synonyms to a word in the dictionary. To accomplish this I am using is using a M:N relationship between the word and synonym tables.
Entities:
#Entity(tableName = "word_table",
indices = #Index(value = "word", unique = true))
public class Word {
#PrimaryKey(autoGenerate = true)
private long id;
private String word;
#Ignore
public Word(String word) {
this.word = word;
}
public Word(long id, String word) {
this.id = id;
this.word = word;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
}
#Entity(tableName = "synonym_table")
public class Synonym {
#PrimaryKey(autoGenerate = true)
private long sid;
private String synonym;
#Ignore
public Synonym(String synonym) {
this.synonym = synonym;
}
public Synonym(long sid, String synonym) {
this.sid = sid;
this.synonym = synonym;
}
public long getSid() {
return sid;
}
public void setSid(long id) {
this.sid = sid;
}
public String getSynonym() {
return synonym;
}
public void setSynonym(String synonym) {
this.synonym = synonym;
}
}
#Entity(tableName = "word_synonym_join_table",
primaryKeys= {"word_id" , "synonym_id"},
foreignKeys = {#ForeignKey(entity = Word.class, parentColumns = "id", childColumns = "word_id"),
#ForeignKey(entity = Synonym.class, parentColumns = "sid", childColumns = "synonym_id")})
public class WordSynonymJoin {
#ColumnInfo(name = "word_id")
private long wordId;
#ColumnInfo(name = "synonym_id")
private long synonymId;
public WordSynonymJoin(long wordId, long synonymId) {
this.wordId = wordId;
this.synonymId = synonymId;
}
public long getWordId() {
return wordId;
}
public void setWordId(long wordId) {
this.wordId = wordId;
}
public long getSynonymId() {
return synonymId;
}
public void setSynonymId(long synonymId) {
this.synonymId = synonymId;
}
}
To retrieve the data for the Word and associated Synonyms, I created a POJO called WordWithSynonyms.
public class WordWithSynonyms {
#Embedded
public Word word;
#Embedded
public WordSynonymJoin wordSynonymJoin;
}
The Daos are as follows:
#Dao
public interface WordDao {
#Query("SELECT * FROM word_table")
public LiveData<List<Word>> getAllWords();
#Query("SELECT * FROM word_table WHERE id =:wordId")
public LiveData<List<Word>> getWordById(long wordId);
#Query("SELECT * from word_table WHERE word =:value")
public LiveData<List<Word>> getWordByValue(String value);
#Insert
public long insert(Word word);
#Delete
public void delete(Word word);
#Update
public void update(Word word);
#Query("DELETE FROM word_table")
public void deleteAll();
}
#Dao
public interface SynonymDao {
#Query("SELECT * FROM synonym_table")
public LiveData<List<Synonym>> getAllSynonyms();
#Query("SELECT * FROM synonym_table WHERE synonym =:value")
public LiveData<List<Synonym>> getSynonymByValue(String value);
#Insert
public void insert(Synonym synonym);
#Delete
public void delete(Synonym synonym);
#Query("DELETE FROM synonym_table")
public void deleteAll();
}
#Dao
public interface WordSynonymJoinDao {
#Query("SELECT * FROM word_table INNER JOIN word_synonym_join_table " +
"ON word_table.id = word_synonym_join_table.word_id " +
"WHERE word_synonym_join_table.synonym_id =:synonymId")
public LiveData<List<WordWithSynonyms>> getWordsBySynonym(long synonymId);
#Query("SELECT * FROM synonym_table INNER JOIN word_synonym_join_table " +
"ON synonym_table.sid = word_synonym_join_table.synonym_id " +
"WHERE word_synonym_join_table.word_id =:wordId")
public LiveData<List<SynonymWithWords>> getSynonymsByWord(long wordId);
#Query("SELECT * FROM synonym_table INNER JOIN word_synonym_join_table " +
"ON synonym_table.sid = word_synonym_join_table.synonym_id " +
"WHERE word_synonym_join_table.word_id !=:wordId")
public LiveData<List<SynonymWithWords>> getSynonymsByNotWord(long wordId);
#Insert
public void insert(WordSynonymJoin wordSynonymJoin);
#Delete
public void delete(WordSynonymJoin wordSynonymJoin);
#Query("DELETE FROM word_synonym_join_table")
public void deleteAll();
}
When I arrive on the Synonyms Activity, i pass the wordId to retrieve the current synonyms for that word through a ViewModel observer.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_synonym);
Intent intent = getIntent();
wordId = Long.parseLong(intent.getStringExtra(EXTRA_WORD_ID));
//SynonymViewModel synonymViewModel = ViewModelProviders.of(this).get(SynonymViewModel.class);
WordSynonymJoinViewModel wordSynonymJoinViewModel = ViewModelProviders.of(this).get(WordSynonymJoinViewModel.class);
//synonymAdapter = new SynonymListAdapter(this);
synonymAdapter = new SynonymWithWordListAdapter(this);
synonynRecyclerView = findViewById(R.id.recycler_view_syonym);
if (wordId != 0) {
wordSynonymJoinViewModel.getSynonymsByWord(wordId).observe(SynonymActivity.this, new Observer<List<SynonymWithWords>>() {
#Override
public void onChanged(#Nullable List<SynonymWithWords> synonymWithWords) {
synonymAdapter.setSynonyms(synonymWithWords);
synonymAdapter.notifyDataSetChanged();
}
});
}
synonynRecyclerView.setAdapter(synonymAdapter);
synonynRecyclerView.setLayoutManager(new LinearLayoutManager(SynonymActivity.this));
}
I then give the user the opportunity to associate an existing, unassigned synonym from the Synonym table to the Word table.
I retrieve the unused and available Synonyms through a separate ViewModel observer inside of an AlertDialog which uses a spinner to display them via the WordSynonymJoin table using another ViewModel observer.
Finally, inside of that ViewModel observer when the user clicks the OK button on the AlertDialog, a third VieModel observer is ran to do the actual insertion into the WordSynonymJoin table.
case R.id.synonym_assign_synonym:
final WordSynonymJoinViewModel wordSynonymJoinViewModel = ViewModelProviders.of(SynonymActivity.this).get(WordSynonymJoinViewModel.class);
wordSynonymJoinViewModel.getSynonymsByNotWord(wordId).observe(SynonymActivity.this, new Observer<List<SynonymWithWords>>() {
#Override
public void onChanged(#Nullable List<SynonymWithWords> synonymWithWords) {
List<String> synonymsNotAssignList = new ArrayList<>();
for (SynonymWithWords sww : synonymWithWords)
synonymsNotAssignList.add(sww.synonym.getSynonym());
AlertDialog.Builder assignSynonymDialog = new AlertDialog.Builder(SynonymActivity.this);
assignSynonymDialog.setTitle("Select New Category:");
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.alert_dialog_spinner_view, null);
final Spinner synonymSpinner = (Spinner) view.findViewById(R.id.alert_dialog_spinner);
final SynonymViewModel synonymViewModel = ViewModelProviders.of(SynonymActivity.this).get(SynonymViewModel.class);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter(SynonymActivity.this, android.R.layout.simple_spinner_dropdown_item, synonymsNotAssignList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
synonymSpinner.setAdapter(spinnerAdapter);
synonymSpinner.setSelection(synonymId);
assignSynonymDialog.setView(view);
assignSynonymDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String synonymValue = synonymSpinner.getSelectedItem().toString();
// get new synonym id
synonymViewModel.getSynonymByValue(synonymValue).observe(SynonymActivity.this, new Observer<List<Synonym>>() {
#Override
public void onChanged(#Nullable List<Synonym> synonyms) {
long id = 0;
if (!synonyms.get(0).getSynonym().equals(synonymValue)) {
if (synonyms.size() > 1)
Toast.makeText(SynonymActivity.this, "Query found " + synonyms.size() + " which is more than the one expected.", Toast.LENGTH_SHORT).show();
} else {
id = synonyms.get(0).getSid();
}
WordSynonymJoinViewModel wordSynonymJoinViewModel = ViewModelProviders.of(SynonymActivity.this).get(WordSynonymJoinViewModel.class);
wordSynonymJoinViewModel.insert(new WordSynonymJoin(wordId, id));
}
});
}
});
assignSynonymDialog.setNegativeButton("Cancel", null);
assignSynonymDialog.create();
assignSynonymDialog.show();
}
});
return true;
On the first pass, all seems to work well. However, on successive passes where the user continues to add new synonyms to the word, it takes that many clicks on the cancel button of the AlertDialog to exit after each synonym added. 2 synonyms added, 2 click on the cancel to get back to main Activity. 3 synonyms added, 3 clicks on the cancel to remove the AlertDialog.
I am very new to this whole concept of MVVM and Room persistence so I know there will be issues. Here is the code for the AlertDialog for adding existing, unassigned synonyms to the current word.
I don't like how much code is being used for this, but i have not been able to word my searches so that I can find ways around it.
My questions are:
Why is the code cycling +1 every time I enter associate new synonym to the word? Am I suppose to be clearing something out.
Is this coding even remotely right?
This seems like an awful lot of work to accomplish something so seemingly small. I think I have missed something. Have I made this abnormally complicated?
What am I missing that this code looks so cumbersome and unwieldy?
It seems a very cumbersome way to retrieve values and I don't really think i need to observe every query that I ran above. Maybe I am wrong.
Is there a direction of study that will help me understand this better?
Could this be where the Rx Java comes in?
I can certainly provide more code as needed.
Any help would be appreciated.
TRDL: Don't call .observe outside of ON_CREATE state.
You made a LiveData mistake... but you are not alone! That mistake is the most common LiveData mistake on StackOverflow: calling .observe outside of Activity#onCreate(). This includes calling .observe in a click listener, on onResume, broadcast receiver, etc.
The problem I see in most people who uses LivedData for the first time is that they treat LiveData just like a call back, when they are not. LiveData is a stream. LiveData does not notify just one time. The Observers attached to the LiveData will continue to be notified until they are unsubscribed. Also, It is meant to be subscribed at the beginning of the life-cycle, (e.g. Activity#onCreate or Fragment#onViewCreated) and unsubscribed at the end of the life-cycle. LiveData automatically handles the unsubscription part, so all you need to make sure is to subscribe in onCreate.
The fundamental reason you are keep getting +1 Dialog is that the previous observer is not dead and you are keep adding a new subscription to the database each time you repeat the same thing. Try rotating the phone and see if the number of dialog resets back to 1. That's because all of the previous observers are unsubscribed when you rotate the screen and activity is recreated.
Maybe you could call isShowing() and see if any dialog is open, as suggested in another answer. However, doing so is just a work around. What if it was a Toast or something else that you can't check? Besides, you are lucky that you could easily spot this bug. You might be having this duplicate observer bug some place else that is not visually noticeable.
So I think you already know how to use LiveData, but it is just that you need to know how to implement reactive pattern correctly. It would be too much to explain in one writing but let me give you a simple example:
Lets say you have a button that when you press, you fetch some data from DB. In a callback-like design you often call some function in ViewModel and pass a callback instance. For example you have this:
//ViewModel
void getSynonymsByNotWord(WordSynonymJoin word, Callback callback) { ... }
//Activity
void onClick(View v) {
wordSynonymJoinViewModel.changeCurrentSysnonymsByNotWord(wordId, callback);
}
You perform an action to ViewModel and you receive the response through callback. This is perfectly fine for callback. However, you can't do the same with LiveData. When using LiveData, View layer don't expect that there will be a response for each of the action. Instead, View layer should always blindly listen to the response, even before the button is clicked.
//ViewModel
private MutableLiveData wordQuery;
private Livedata synonymsByNotWord = Transformations.switchMap(wordQuery, word -> {
return repository.getSynonymsByWord(word);
});
LiveData getCurrentSynonymsByNotWord() {
return synonymsByNotWord;
}
void changeCurrentSynonymsByNotWord(WordSynonymJoin word) {
wordQuery.postValue(word);
}
//Activity
void onCreate() {
wordSynonymJoinViewModel.getCurrentSynonymsByNotWord().observe(...);
}
void onClick(View v) {
wordSynonymJoinViewModel.changeCurrentSynonymsByNotWord(wordId);
}
And also it is okay to, but you normally don't get ViewModel from ViewModelProviders every time you need a view model. You should just get one view model at onCreate, save it as an activity instance variable, and use the same instance in the rest of the activity.
Here:
wordSynonymJoinViewModel.getSynonymsByNotWord(wordId).observe(SynonymActivity.this, new Observer<List<SynonymWithWords>>() {
you are monitoring for synonyms, but inside of the observing, you show a dialog and allow more synonyms to be added. Everytime a new synonym is added, it creates a new AlertDialog.
So this is why you have to press cancel on each dialog.
To fix that, you can assign your AlertDialog to a field and use the isShowing() method to decide if you want to show another dialog (i.e. don't show another one if one is already showing.
https://developer.android.com/reference/android/app/Dialog.html#isShowing()
As for all your other questions, I'm sorry it's a bit too much for me to unpack.
I can share my thoughts on how I would do this though:
I want to assign existing synonyms to a word in the dictionary.
Perhaps forget the database to start with and create an in memory solution.
Then later you can change this to be persisted.
In memory the structure looks like a Hashtable of Dictionary words and Synonym lookups Map<String, List<String>>.
This Map would be in a class called Repository that exposes someway for you to observe and update it (RxJava Observable) or LiveData like you have already.
Your Fragment would observe this Map displaying it in a RecyclerView using MVVM or MVP whatever you want.
You have a clicklistener on each row of the RecyclerView to add a new synonym. On click opens the dialog (or a new activity/fragment). After the user types the synonym you will save this through the repository to your Map - and therefore the original observer will update the RecyclerView.
You should not get in a loop state of opening multiple dialogs :/
Hope that helps, tbh it sounds like you are on the right track and just need to work at it a bit more.
Ok been stuck on this for literally weeks, sorry for long question.
Using Parse, making a workout app for Android.
Database tables and columns that are relevant to my problem are:
Exercises
ID| name | description | Musclegroup
Workouts
ID| workoutName| userID
WorkoutExercises (basically a join table between the two)
ID| workoutID (pointer) | exerciseID (pointer)
So a user will be able to create a workout and add in the exercises they want.
So far I've already done:
User can go to category, browse the muscle group, view the exercises in that group
signup/login/logout, update profile
list the current workouts (not the exercises in them) -
I have just entered some exercises into a workout on the db as have gotten stuck on querying current exercises in that workout before worrying about inserting new ones.
The problem:
I'm trying to do a nested query to get the exercise name so once a user clicks Eg. Back Workout it should bring up a list Eg. Deadlift, Rows, Chin ups
So basically in SQL I want to:
Select name
from Exercises
where ID in (select exerciseID from workoutexercises where WorkoutID=xxxx)
Things i'm struggling on:
Making a nested query for a pointer, from what I have read on the net I need to use query.include("exerciseID"); which will tell Parse to include a full Exercise item that I can then use to query? Correct me if wrong? Code below - have I done it correctly?
I've learnt from and been using methods from: http://www.michaelevans.org/blog/2013/08/14/tutorial-building-an-android-to-do-list-app-using-parse/ where query data is put into a custom adapter that lists the data. It uses getters
and setters to save/retrieve String/int values, do I still use the getters for getting a string from within a pointer?
EG.
public String getName()
{
return getString("name");
}
As in once i'm "through" that pointer and in the Exercise table im assuming i'm still just getting the String name value as oppose to getting a ParseObject?
Now so far I have been able to get the custom adapter to put 2 horizontal bars across the screen that shows it knows i've put 3 items in workoutExercises but just not bringing up the text from Exercise name that I need from the nested query
Have a look at my screenshots to see what I mean.
Thank you very much for the help in advance.
Query so far:
public void getcurrentExercisesInWorkout() {
//set progress bar
setProgressBarIndeterminateVisibility(true);
ParseQuery<WorkoutExercises> query = ParseQuery.getQuery("WorkoutExercises");
query.include("exerciseId");
query.whereEqualTo("workoutId", mWorkoutId);
query.findInBackground(new FindCallback<WorkoutExercises>() {
#Override
public void done(List<WorkoutExercises> workoutExercises, ParseException error) {
if (workoutExercises != null) {
mWorkoutExercisesAdapter.clear();
mWorkoutExercisesAdapter.addAll(workoutExercises);
} else {
Log.d("error", error.getMessage());
}
}
});
//stop progress bar
setProgressBarIndeterminateVisibility(false);
}
Custom list Adapter:
//constructor - get current state of parsed object and list of objects retrieved from workout
public WorkoutExercisesAdapter(Context context, List<WorkoutExercises> objects) {
super(context, R.layout.row_item, objects);
this.mContext = context;
this.mWorkoutExercises = objects;
}
public View getView(int position, View convertView, ViewGroup parent)
{
//put each item into the listview
if(convertView == null)
{
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.row_item,null);
}
WorkoutExercises workoutExercises = mWorkoutExercises.get(position);
TextView nameView = (TextView) convertView.findViewById(R.id.row_name);
//this just calls a String getter - which isn't working - need it to get the Exercise name from within the pointer
nameView.setText(workoutExercises.getWorkoutExercise());
return convertView;
}
WorkoutExercises(stores the getters)
#ParseClassName("WorkoutExercises")
public class WorkoutExercises extends ParseObject {
public String exName;
public WorkoutExercises()
{
}
public String getWorkoutExercise()
{
return getString("name");
}
}
Running Android Studio in Debug mode I can literally see the data I am trying to put into the text field (see screenshot - how can I grab that value? See screenshot below
NOW WORKING - THE RESULT!
First, alter the WorkoutExercises object:
#ParseClassName("WorkoutExercises")
public class WorkoutExercises extends ParseObject {
//public String exName;
public static final String workoutID = "workoutID"
public static final String exerciseID = "exerciseID"
public Exercises getWorkoutExercise() {
return (Exercises)getParseObject(exerciseID);
}
public WorkoutExercises()
{
// not sure if it is allowed to define your own constructor?
// just a note
}
// WorkoutExercises does not have a 'name' col
//public String getWorkoutExercise()
//{
// return getString("name");
//}
}
I assume that Exercises at least contains something like:
#ParseClassName("Exercises")
public class Exercises extends ParseObject {
public static final String name = "name"
public String getName()
{
return getString(name);
}
}
Now, with the query on WorkoutExercises including workoutID, the Exercises object will be populated in the fetched query. This means you can do the following to get the name of the exercises object:
// workoutExercises returned from a query including workoutID
Exercises exercise = workoutExercises.getWorkoutExercise();
String name = exercise.getName();
// if Exercises has getters for description and Musclegroup
String description = exercise.getDescription();
String musclegroup= exercise.getMusclegroup();
Hope this sheds some light on the problem
I'm trying to setup an Android Service in my app that listens for new Childs in a Firebase Ref, and throws a Notification when that happens.
I'm having issues because addChildEventListener onChildAdded apparently is called one time for every existent record and only then actually listens for new childs..
In this answer #kato states that if addChildEventListener is called like ref.endAt().limit(1).addChildEventListener(...) it would get only the newly added records.
It actually only gets one record at a time (I suppose with limit(1)) but it still gets an existant record before listening for added records.
Here's some code:
Initializing the Listener in onCreate():
#Override
public void onCreate() {
super.onCreate();
this.handler = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
AllowedGroup ag = dataSnapshot.getValue(AllowedGroup.class);
postNotif("Group Added!", ag.getName());
}
...rest of needed overrides, not used...
I'm using the AllowedGroup.class to store the records, and postNotif to build and post the notification. This part is working as intended.
Then, onStartCommand():
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.f = new Firebase(FIREBASE_URL).child("users").child(this.currentUserUid).child("allowedGroups");
f.endAt().limit(1).addChildEventListener(handler);
return START_STICKY;
}
It still returns one existant record before actually listening for newly added childs.
I've also tried querying by timestamp, like so:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.f = new Firebase(FIREBASE_URL).child("users").child(this.currentUserUid).child("allowedGroups");
f.startAt(System.currentTimeMillis()).addChildEventListener(handler);
return START_STICKY;
}
Hoping that it would only get records set after the service was started. It doesn't get existant records, but doesn't even get newly added childs.
EDIT:
I've also thought of something like getting into memory first all of the existant records, and conditionally post a notification if the record brought by onChildAdded does not exist on the previously gathered list, but that seems a bit like overkill, and thought that could be an easier (more API-friendly) way of doing this, am I right ?
Can anyone provide me with some insight on this ? I can't really find anything on the official docs or in any StackOverflow question or tutorial.
Thanks.
If you have a field modifiedOn, you can index that and setup a query like:
Query byModified = firebaseEndpoint.orderByChild("modifiedOn").startAt(lastInAppTime);
For me the logic was is to have value -"status" for example- which needs to be validated before deciding whether it is really new or was an old record then I set the "status" to a different value so I don't get it next time:
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildKey) {
if(dataSnapshot.hasChildren()) {
String Id = (String) dataSnapshot.child("user_id").getValue();
String status = (String) dataSnapshot.child("status").getValue();
if (Id != null && Id.equals(storedId) && status != null && status.equals("created")) {
Log.d("INCOMING_REQUEST", "This is for you!");
sessionsRef.child(dataSnapshot.getKey()).child("status").setValue("received");
}
}
}
I overcome this problem by keeping items of firebase database reference node in a List; and whenever onChildAdded(...) method is triggered, check if the incoming datasnapshot is in your list or not; if not, then it's new data
In order to achieve this you must meet below conditions:
Have a unique value that must not repeated from item to item. (this can be easily achieved when you add items into Firebase using .push() method.
Override .equals() method of your model class in order to fulfill the comparison based on this unique value.
Here code snippets based on your inputs
Model class
public class AllowedGroup {
private String id;
public static List<AllowedGroup> sGroups;
// reset of fields ...
public AllowedGroup() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public boolean equals(#Nullable Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
// Check if o is an instance of AllowedGroup or not
if (!(o instanceof AllowedGroup)) {
return false;
}
// typecast o to AllowedGroup so that we can compare data members
AllowedGroup group = (AllowedGroup) o;
// Compare data based on the unique id
return (group.id).equals(id);
}
}
Listening to firebase added nodes
#Override
public void onCreate() {
super.onCreate();
this.handler = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
AllowedGroup group = dataSnapshot.getValue(AllowedGroup.class);
if (!AllowedGroup.sGroups.contains(group)) {
// Here you'll receive only the new added values
}
}
// ...rest of needed overrides, not used...
}
}
In my project have to populate the list view from local database.I have implemented it.When I click the row in list item I need to show all the details in list row in next activity.I implemented custom list adapter.I not yet started to code for detailed list row.How can I pass all details in single row to another activity.Can anyone help me?
You can set the information in tags of textviews of your custom list and pass them through intents.
one thing that you can do is just pass the id (PK) of the item . Then on next activity you can fetch it again from database.
another options is that you can create a class with all the data you want to forward as class'members and serialize the object and send it along with the intent.
here is a example
public class ActivityExtra implements Parcelable {
public Integer a=0;
public String b="";
private GameActivityExtra(Parcel in) {
this.a = in.readInt();
this.b = in.readString();
}
public GameActivityExtra() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(a);
dest.writeString(b);
}
public static final Parcelable.Creator<GameActivityExtra> CREATOR = new Parcelable.Creator<GameActivityExtra>() {
public GameActivityExtra createFromParcel(Parcel in) {
return new GameActivityExtra(in);
}
public GameActivityExtra[] newArray(int size) {
return new GameActivityExtra[size];
}
};
}
now create instance of this class in your activity . and use intent.putextra(...) to put it . and get the same object while receiving it.
Use #nitesh goel answer to make your object class parcelabe.
Then onitemclick use
intent.putExtra("object", object);
to send your object to other activity.
And in corresponding activity use
intent.getParcelableExtra("object");
to get your object. then you can get everything of that object.
I have been working on a e-commerce application for a while, and now I have a ListView that displays a list of products - Each products = 1 ImageView and some TextViews-.
I set an onItemClick listener on that ListView, the event that I want to occur when I click on one of that listView products is, Start the i new Activity, 'ProductDetails' that displays more informations on the product I have clicked on.
I have already asked this question somewhere else, but I didn't get a clear answer,
They said that I have to create a new 'list\details' project, but this can't happen now, as I've working on that project for like 20 days, and can't start all over again.
You can't send a TextView or an ImageView from Activity to Activity. what you can send instead is it's contents. so for example if you want to pass the information from the TextView you will need to pass the source String that is displayed there (Or extract the String from the TextView) you do that by passing a Bundle from the calling Activity to the invoked one or simply by putting it as an Extra:
intent.putExtra("string name", value);
and in the following Activity you get this data:
Intent intent = getIntent();
bundle = intent.getExtras();
bundle.getString("string name");
Then in the following Activity create a TextView with the passed String.
Same way is handled with the ImageView by passing the it's path.
Sorry I have posted an answer but was only a link to another site so it was deleted :-(
Here I come again with what could be the solution:
In your first activity, you need to use intent.putExtra(...) and retrieve the datas in your second activity with intent.getExtra(...).
Example activity 1:
i.putExtra("title01", yourDataCollection.get(position).get(KEY_TITLE01));
Activity 2 :
this.title01 = i.getStringExtra("title01");
There is a full project here : http://www.codeproject.com/Articles/507651/Customized-Android-ListView-with-Image-and-Text
Android uses intent to allow Activitys to interact. If you want to show a details of product, probably you have a Class that describe that product and with the information it holds you fill up your ListView. If you let the class Product implements Serializable you can use Intent.putExtra(String name, Serializable obj), to pass the Product description between Activitys. In ProductDetailsActivity you can use:
getIntent(). getSerializableExtra (String name)
to retrive the serializable you put inside the Intent you created to start ProductDetailsActivity
If you pass your model class around many times using Intent, perhaps it could implement the Parcelable interface for convenience. For example:
class ProductData implements Parcelable {
protected String name;
protected String someOtherData;
public static final Parcelable.Creator<ProductData> CREATOR = new Parcelable.Creator<ProductData>() {
#Override
public ProductData createFromParcel(Parcel source) {
return new ProductData(source);
}
#Override
public ProductData[] newArray(int size) {
return new ProductData[size];
}
};
public ProductData(){
}
public ProductData(Parcel source){
readFromParcel(source);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(someOtherData);
}
public void readFromParcel(Parcel source){
name = source.readString();
someOtherData = source.readString();
}
// Here goes the rest of your model code
}
Then you can easily pass the object to another Activity using an Intent:
intent.putExtra("product", productData);
and later get the data using
ProductData productData = intent.getParcelableExtra("product");