I'm trying to retrieve a information from a parse object but the strings I store them in keep equaling null.
Here is how I saved the object
// get current user
ParseObject studentClasses = new ParseObject("StudentClasses");
// register their periods into database
studentClasses.put("student_id", ParseUser.getCurrentUser());
studentClasses.put("first_period", ClassSelected_Period[PERIOD1]);
studentClasses.put("second_period", ClassSelected_Period[PERIOD2]);
studentClasses.put("third_period", ClassSelected_Period[PERIOD3]);
studentClasses.put("fourth_period", ClassSelected_Period[PERIOD4]);
studentClasses.put("fifth_period", ClassSelected_Period[PERIOD5]);
studentClasses.put("sixth_period", ClassSelected_Period[PERIOD6]);
studentClasses.put("seventh_period", ClassSelected_Period[PERIOD7]);
// save the information into database
studentClasses.saveInBackground();
It saves it perfectly fine my database. The student_id is a pointer to the user and the rest of the columns are strings.
I want to retrieve all those strings and put them in an array when I query parse for them it doesn't work
Here is my query
// check if a user is not cached
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null)
{
// prompt user to Register screen
// create intent to start activity
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// start new activity
startActivity(intent);
// stop current activity
finish();
}
// query database for user's classes
ParseQuery<ParseObject> query = ParseQuery.getQuery("StudentClasses");
query.whereEqualTo("student_id", ParseUser.getCurrentUser());
query.getFirstInBackground(new GetCallback<ParseObject>()
{
#Override
public void done (ParseObject parseObject, ParseException e)
{
if (e == null)
{
// retrieved the object
userClasses[PERIOD1] = parseObject.getString("first_period");
userClasses[PERIOD2] = parseObject.getString("second_period");
userClasses[PERIOD3] = parseObject.getString("third_period");
userClasses[PERIOD4] = parseObject.getString("fourth_period");
userClasses[PERIOD5] = parseObject.getString("fifth_period");
userClasses[PERIOD6] = parseObject.getString("sixth_period");
userClasses[PERIOD7] = parseObject.getString("seventh_period");
}
else
{
// failed lookup. Do something here
Toast.makeText(getApplicationContext(),"Exception Thrown" ,Toast.LENGTH_SHORT).show();
}
}
});
I looked at the parse docs and it looks like it should work but it doesn't save the strings
Any help or comments is appreciated thanks!
EDIT: I showed more of my code for the query part to show there is a current user
Here i am assuming that, there is data stored in your parse database.. and it works fine.. so to retrieve it try following..
ParseQuery<ParseObject> query = ParseQuery.getQuery("StudentClasses");
query.whereEqualTo("student_id", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<ParseObject>()
{
#Override
public void done (List<ParseObject> list, ParseException e)
{
if (e == null)
{
for(int i=0; i < list.size(); i++) {
userClasses[PERIOD1] = list.get(i).getString("first_period");
userClasses[PERIOD2] = list.get(i).getString("second_period");
userClasses[PERIOD3] = list.get(i).getString("third_period");
userClasses[PERIOD4] = list.get(i).getString("fourth_period");
userClasses[PERIOD5] = list.get(i).getString("fifth_period");
userClasses[PERIOD6] = list.get(i).getString("sixth_period");
userClasses[PERIOD7] = list.get(i).getString("seventh_period");
}
}
else
{
Toast.makeText(getApplicationContext(),"Exception Thrown" ,Toast.LENGTH_SHORT).show();
}
}
});
hope it helps!
Well try when getting content to use the function
parseObject.get("the_name_of_the_column")
Which actually should work and works fine for me
Here what you need to understand is in your code studentClasses.saveInBackground(); is async call and you need to query inside SaveCallback. Then you can assure that the saved data is in the database when your query runs.
You got null data because you query before the data is saved in parse.
ParseObject studentClasses = new ParseObject("StudentClasses");
// register their periods into database
studentClasses.put("student_id", ParseUser.getCurrentUser());
studentClasses.put("first_period", ClassSelected_Period[PERIOD1]);
studentClasses.put("second_period", ClassSelected_Period[PERIOD2]);
studentClasses.put("third_period", ClassSelected_Period[PERIOD3]);
studentClasses.put("fourth_period", ClassSelected_Period[PERIOD4]);
studentClasses.put("fifth_period", ClassSelected_Period[PERIOD5]);
studentClasses.put("sixth_period", ClassSelected_Period[PERIOD6]);
studentClasses.put("seventh_period", ClassSelected_Period[PERIOD7]);
// save the information into database
studentClasses.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("StudentClasses");
query.whereEqualTo("student_id", ParseUser.getCurrentUser());
query.getFirstInBackground(new GetCallback<ParseObject>()
{
#Override
public void done (ParseObject parseObject, ParseException e)
{
if (e == null)
{
// retrieved the object
userClasses[PERIOD1] = parseObject.getString("first_period");
userClasses[PERIOD2] = parseObject.getString("second_period");
userClasses[PERIOD3] = parseObject.getString("third_period");
userClasses[PERIOD4] = parseObject.getString("fourth_period");
userClasses[PERIOD5] = parseObject.getString("fifth_period");
userClasses[PERIOD6] = parseObject.getString("sixth_period");
userClasses[PERIOD7] = parseObject.getString("seventh_period");
}
else
{
// failed lookup. Do something here
Toast.makeText(getApplicationContext(),"Exception Thrown" ,Toast.LENGTH_SHORT).show();
}
}
});
} else {
// myObjectSaveDidNotSucceed();
}
}
});
Hope this helps
After getting some sleep then doing more research and tinkering I found the problem. The problem isn't in my code; it's in my network... well not entirely. You see my code runs ... at well run-time (As fast as my phone can process it); however, the method
query.findInBackground(new FindCallback<ParseObject>()
runs asynchronously meaning that it does not run at the speed of my other code. Which makes sense if you think about it because it has to send and wait for a response from a database. That's why when I made a toast inside it, the data was there in the string but when I tried to make a toast a few lines later, outside of the method, the data was not there. It was null.
Here's an example. I make a toast at the end of on create with this code
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialise and set toolbar as actionbar
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// initialize nav bars
initNavBars();
// initialize drawer layout
NavigationView navView = (NavigationView) findViewById(R.id.navigation_view);
// initialize nav drawer
navDrawer = (DrawerLayout) findViewById(R.id.drawer);
initNavDrawer(navDrawer);
// initialize layout manager for recycler view
RecyclerView.LayoutManager mainLayoutManager = new LinearLayoutManager(this);
// initialize data for all classes before setting adapter
initClassData(); // <---- MY PARSE QUERY IS IN THIS METHOD
// set the adapter for recycler view
RecyclerView.Adapter mainAdapter = new MainRecyclerAdapter(classrooms);
// initialize recycler view elements
RecyclerView mainRecyclerView = (RecyclerView) findViewById(R.id.main_recycler_view);
// add layout manager to recycler view
mainRecyclerView.setLayoutManager(mainLayoutManager);
// add adapter to recycler view
mainRecyclerView.setAdapter(mainAdapter);
Toast.makeText(getApplicationContext(), userClasses[PERIOD1], Toast.LENGTH_SHORT).show(); // <----- HERE IS MY TOAST
}
When I run it, the toast is empty because the string is still null, but if I run it with this code
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialise and set toolbar as actionbar
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// initialize nav bars
initNavBars();
// initialize drawer layout
NavigationView navView = (NavigationView) findViewById(R.id.navigation_view);
// initialize nav drawer
navDrawer = (DrawerLayout) findViewById(R.id.drawer);
initNavDrawer(navDrawer);
// initialize layout manager for recycler view
RecyclerView.LayoutManager mainLayoutManager = new LinearLayoutManager(this);
// initialize data for all classes before setting adapter
initClassData(); // <---- PARSE QUERY IS STILL IN THIS METHOD
// set the adapter for recycler view
RecyclerView.Adapter mainAdapter = new MainRecyclerAdapter(classrooms);
// initialize recycler view elements
RecyclerView mainRecyclerView = (RecyclerView) findViewById(R.id.main_recycler_view);
// add layout manager to recycler view
mainRecyclerView.setLayoutManager(mainLayoutManager);
// add adapter to recycler view
mainRecyclerView.setAdapter(mainAdapter);
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
// Do something after 5s = 5000ms
Toast.makeText(getApplicationContext(), userClasses[PERIOD1], Toast.LENGTH_SHORT).show();
}
}, 5000);
}
In this example I forced the toast to wait five seconds to allow
query.getFirstInBackground(new GetCallback<ParseObject>()
to finish querying the database and when I run it, the toast displays the string correctly.
So if your program relies on a parse query to get important data, you have to structure your code in a way to allow for a second or two to pass to let the parse query return.
Or you could alternatively store the data locally and then you can use the database as a backup for the data and check to make sure it is the same every time the user wants to switch it or somethings.
Thank you Ajay and Rasika I would still be trying to figure why it was not working if it weren't you.
Related
I tried to get a array from an adapter from my code
here is the array that i wanted to get from my adapter, named MakananAdapter :
private int[] JumlahPesan = {0,0,0,0};
The array is changing constantly since user will be deciding the amount that they want, here is the onBindViewHolder code:
public void onBindViewHolder(#NonNull viewHolder holder, final int position) {
ImageView ivMakanan = holder.ivMakanan;
TextView tvNamaHarga = holder.tvNamaMakanan;
TextView tvKetersediaan = holder.tvKetersediaan;
TextView tvHarga = holder.tvHargaMakanan;
final TextView tvPesanan = holder.tvJumlahPesanan;
Button btnTambah = holder.btnTambah;
Button btnKurang = holder.btnKurang;
ivMakanan.setImageResource(makanans.get(position).getGambarMakanan());
tvNamaHarga.setText(makanans.get(position).getNamaMakanan());
tvKetersediaan.setText("Stok : " + makanans.get(position).getStatusMakanan());
tvHarga.setText("Harga : " + makanans.get(position).getHargaMakanan());
btnTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumlahPesan[position]++;
tvPesanan.setText(String.valueOf(JumlahPesan[position]));
}
});
btnKurang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumlahPesan[position]--;
tvPesanan.setText(String.valueOf(JumlahPesan[position]));
}
});
}
as you can see i make a button that increase and decrease the data of the array
and i tried to get the array data to my activity, but i still get error.
my activity named PilihMakananActivity.class
here is the array to save the data from the adapter
private int[] Pesanan = {0,0,0,0};
and i tried to get the data in onResume
protected void onResume() {
super.onResume();
com.example.iotforcanteen.adapter.MakananAdapter coba = null;
for (int i = 0; i<4 ; i++) {
Pesanan [i]= coba.AmbilJumlahPesanan(i);
}
}
and i tried to show it in a snackbar like this
btnKonfirmasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, Pesanan[0] + Pesanan[1] + Pesanan[2] + Pesanan[3],Snackbar.LENGTH_SHORT).show();
}
});
Im so sorry if the code is so messy, because im new to android development.so is there any way to fix this error?
It has error because you set to your adapter null value in onResume .
But in general I assume you use RecyclerView in code so the steps for using RecyclerView is important, first you must set LayoutManager for RecyclerView. Then make an adapter and set it to RecyclerView and I recommend you to do this steps in onCreate not onResume.
Here is a little example
RecyclerView recyclerView = findViewById(R.id.rec);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, list);
recyclerView.setAdapter(adapter);
Also make your array in adapter public or write getter for it. After calling setAdapter for RecyclerView, you can get your data in adapter. For example you can define a Button and in OnClickListener get the desired array(here is JumlahPesan) in adapter
you aren't initiating this adapter (null) and few lines below trying to access data from it, this is NullPointerException
com.example.iotforcanteen.adapter.MakananAdapter coba = null;
for (int i = 0; i<4 ; i++) {
Pesanan [i]= coba.AmbilJumlahPesanan(i);
}
make reference to already exitsting adapter atached to your ListView or RecyclerView, not freshly created and not initialised at all
note that onResume is called once at the beggining, thus your Pesanan won't have current data, only copy from start of Activity
maybe just get your values straightly when button pressed, without a copy of array in Activity:
btnKonfirmasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(coordinatorLayout,
adapterAttachedToView.AmbilJumlahPesanan(0) + " " +
adapterAttachedToView.AmbilJumlahPesanan(1) + " " +
adapterAttachedToView.AmbilJumlahPesanan(2) + " " +
adapterAttachedToView.AmbilJumlahPesanan(3),
Snackbar.LENGTH_SHORT).show();
}
});
note that Snackbar.make( should take View, in which Snackbar will appear, not clicked Button (you are passing v to Snackbar.make)
My app displays a customed list of videos with the option to download using IntentService. The custom list is displayed on the UI using a recyclerView system. Below is a pic of the list
When a video is clicked and downloaded, the download icon turns blue as seen in the first child of the list shown in the picture above and when it has not been downloaded it shows the default black download icon. I have strung up some codes to make it work, the challenge is, when the app is restarted, The download icon revert to its default color even when it was previously downloaded. How do I update and save changes made to the color of the download icon so it will reflect when the app is restarted? I understand the SharedPreference class can be used to save changes made to the App, but I don't know how to achieve this. Would appreciate any assist that can be lent to achieve this
Below is my onCreate mtd
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecture);
setUpRecyclerView();
And below is where I created the setUpRecyclerView()
private void setUpRecyclerView() {
Query query = lectureRef.orderBy("position", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<LectureClasses> options = new FirestoreRecyclerOptions.Builder<LectureClasses>()
.setQuery(query, LectureClasses.class).build();
adapter = new LectureClassesAdapter(options);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
Below is my call of the onViewItemclick #overide method setup in my adapter class
#Override
public void onViewItemClick(DocumentSnapshot snapshot, int position, View itemView) {
//init variables
CircularProgressBar progressBarCir = itemView.findViewById(R.id.progress_circular);
progressBarCir.setProgressMax(100f);
ImageView downloadImage = itemView.findViewById(R.id.download);
PopupMenu popupMenu = new PopupMenu(LectureActivity.this,downloadImage);
LectureClasses lectureClasses = snapshot.toObject(LectureClasses.class);
lectureClasses = adapter.getItem(position);
String titleNow = lectureClasses.getTitle();
String urlNow = lectureClasses.getUrl();
class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == TichaDownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
progressBarCir.setProgress(progress);
downloadImage.setVisibility(View.GONE);
progressBarCir.setVisibility(View.VISIBLE);
Log.i("STATUS","DOWNLOADING>>>");
if (progress == 100) {
progressBarCir.setVisibility(View.GONE);
downloadImage.setImageDrawable(getDrawable(R.drawable.download_blue));
downloadImage.setVisibility(View.VISIBLE);
}
}else {
Log.i("STATUS"," NOT DOWNLOADING,BOSS");
}
}
}
}
you are can to check the file with below code
File videoFile = new File("patch_video_file");
if (videoFile.exists()){
// visible button blue
}else {
// visible button default
}
Before I asked this question I really looked at different answers on StackOwerflow for days, but I couldn't find an answer.
This is my what I am doing - I have an app that has UserProfileActivity, which I want to be able to open from 2 different activities - from myContactsListActivity and from messageActivity. Data I want sent in my UserProfileActivity contains userId, userName, profilePhooto, and aboutUser.
In the first case I want to pass this data via intent from myContactsListActivity, and in the second I want to pass only userId from myContactsListActivity and make a call to get data from the server.
This is how I do it right now. When it is open from myContactsListActivity, I use intents to pass the data to UserProfileActivity, and pass only userId from messageActivity, and use if else to determine what intent is called.
In short: Activity A can be opened from activity B and C. I need two different behaviors. If it is opened form B everything is passed via intent, and if it is opened from C only userId is passed and there is a call to server. How would I determine from which activity was opened, and what is the best way to set different behaviors.
Here is my code, IT WORKS, but I am not happy with it, and I am looking for a better solution:
TextView textViewUserName, textViewAbout;
ImageView imageView;
Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_profile);
Intent intent = getIntent();
final String userId = intent.getStringExtra("userId");
String userName = intent.getStringExtra("userName");
String about = intent.getStringExtra("about");
String image = intent.getStringExtra("image");
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
textViewUserName = (TextView) findViewById(R.id.contactUsername);
textViewAbout = (TextView) findViewById(R.id.aboutMe);
ColorGenerator generator = ColorGenerator.MATERIAL;
final int color = generator.getColor(userId);
TextDrawable.IBuilder builder = TextDrawable.builder()
.beginConfig()
.withBorder(1)
.endConfig()
.rect();
if (userName != null) {
String firstLetter = intent.getStringExtra("userName").substring(0, 1);
TextDrawable textDrawable = TextDrawable.builder().buildRect(firstLetter, color);
imageView = (ImageView) findViewById(R.id.profile_image);
imageView.setImageDrawable(textDrawable);
Picasso.with(this)
.load("http://192.168.0.13/mynewapp/profilephotos/" + image)
.placeholder(textDrawable)
.error(textDrawable)
.centerCrop()
.fit()
.into(imageView);
getSupportActionBar().setTitle(userName);
Intent commentDescriptionIntent = new Intent(this, AboutFragment.class);
commentDescriptionIntent.putExtra("userId", userId);
commentDescriptionIntent.putExtra("userName", userName);
commentDescriptionIntent.putExtra("about", about);
setIntent(commentDescriptionIntent);
} else {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<ContactResponse> call = apiService.userExists(userId);
call.enqueue(new Callback<ContactResponse>() {
#Override
public void onResponse(Call<ContactResponse> call, retrofit2.Response<ContactResponse> response) {
Contact contact = response.body().getResults();
String firstLetter = contact.getUserName().substring(0, 1);
TextDrawable textDrawable = TextDrawable.builder().buildRect(firstLetter, color);
imageView = (ImageView) findViewById(R.id.profile_image);
imageView.setImageDrawable(textDrawable);
Picasso.with(getApplicationContext())
.load("http://localhost/mynewapp/profilephotos/" + contact.getThumbnailUrl())
.placeholder(textDrawable)
.error(textDrawable)
.centerCrop()
.fit()
.into(imageView);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
String userName = contact.getUserName();
collapsingToolbarLayout.setTitle(userName);
}
#Override
public void onFailure(Call<ContactResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
Try using an another extra value with your Intent.
For example:
From ActivityB:
Intent intent = new Intent(ActivityB.this, ActivityA.class);
intent.putExtra("FROM_ACTIVITY", "B");
// Others extra values
startActivity(intent);
From ActivityC:
Intent intent = new Intent(ActivityC.this, ActivityA.class);
intent.putExtra("FROM_ACTIVITY", "C");
// Others extra values
startActivity(intent);
Do this in your ActivityA:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_profile);
String fromActivity = getIntent().getStringExtra("FROM_ACTIVITY");
if(fromActivity.equals("B")) {
// Do something
} else if(fromActivity.equals("C")) {
// Do something
}
}
Hope this will help~
This is how I would go on doing this, We can use fragments to load on activities, depending on the different state of the activity,
So you can have 2 different fragments. Will probably load the same UI/xml view, But behave differently, One just set the values coming from the intent. and Other loading stuff from an external api.
Note:
Try to use a loader to load stuff from an external api. that has its own call backs that you can use to load data after they are being received.
This is more of a high level idea, Let me know if you have any further questions
AskFirebase How to get the previous item values(POJO) in firebase recycler adapter without using database query.
// Set up FirebaseRecyclerAdapter with the Query
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
final DatabaseReference postRef = getRef(position);
Log.e(TAG, "populateViewHolder: " + position);
// Set click listener for the whole post view
final String postKey = postRef.getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Launch PostDetailActivity
Intent intent = new Intent(getActivity(), PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
startActivity(intent);
}
});
// Determine if the current user has liked this post and set UI accordingly
if (model.stars.containsKey(getUid())) {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
} else {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
#Override
public void onClick(View starView) {
// Need to write to both places the post is stored
Log.e(TAG, "new: ");
DatabaseReference globalPostRef = mDatabase.child("posts").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("user-posts").child(model.uid).child(postRef.getKey());
// Run two transactions
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
Suppose their are five cell list whenever i am facing second cell in the list that time i want to put a condition based on first cell value. So how i can fatch the value of first cell?
I already try to using arraylist to store the POJO of Post . But the problem is whenever some item is deleted from firebase table that item onDataChange call but populateViewHolder doesn't call. Their is also a way to get previous data using database query that is
DatabaseReference ref = getRef(position-1);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.e(TAG, "CHild exist: ");
} else {
Log.e(TAG, "no CHild exist: ");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But i don't want to use this database query is their any other way?
The Design Firebase data structure for topic Answer and Comment its like your problem.
gdtdg6765rf and hjgdhs567hd are unique key get by firebase
hjgdhs567hd is answer
gdtdg6765rf is comment to answer hjgdhs567hd
created is -1*UNIX Timestamp for ordering
date, time and toanswer was saved in comments by answer belong to
if to delete answer set all flags "deleted=1" where child "toanswer=deleted answer key" to populate again
#eurosecom above image is my layout where their is a recycler view which populate through FirebaseRecyclerAdapter . Now those green cell is my single cell. you see a red circle which denote the date. in case of position==0 I just simple visible the layout, and in case of position>0 i want to put the condition based on previous item date.
Now in my FirebaseRecyclerAdapter i have to put the condition so i have to fetch the previous position date. So as i am already doing a network oparetion using Query to fetch the msg list i don't want to put addListenerForSingleValueEvent in the populateview again as because it will again fetch the val from database. So is their any other way to get the previous item?
I am trying to use parse to set comments for a specific post , I already have a Post class and a Comment class in the parse.com Data , anyway I tried to set a comment inside a column in the class and then get it , but the problem is , I can only get 1 comment per post , how to do that , is my question , I tried one to many relations , but it didn't work , I tried a pointer row in the Meal class that points to the Comment class , but I didn't know what to do then , here is some sample code :
public void addTheComment() {
// Create the Post object
ParseObject post = new ParseObject("Post");
post.put("textContent", txtComment.getText().toString());
// Create an author relationship with the current user
post.put("comment", getCurrentMeal());
// Save the post and return
post.saveInBackground(new SaveCallback () {
#Override
public void done(ParseException e) {
if (e == null) {
setResult(RESULT_OK);
finish();
} else {
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}
});
this adds a comment from edit text through out a button when pressed
and here is the list that shows the comments :
private void updateComments() {
ParseQueryAdapter<ParseObject> adapter =
new ParseQueryAdapter<ParseObject>(this, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
// Here we can configure a ParseQuery to our heart's desire.
ParseQuery query = new ParseQuery("Post");
query.whereEqualTo("comment", getCurrentMeal());
return query;
}
});
adapter.setTextKey("comment");
adapter.setImageKey("photo");
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
}
and :
public Meal getCurrentMeal() {
return meal;
}
private void updateComments() {
ParseQueryAdapter<ParseObject> adapter =
new ParseQueryAdapter<ParseObject>(this, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
// Here we can configure a ParseQuery to our heart's desire.
ParseQuery query = new ParseQuery("Comment");
query.whereContainedIn("parent", Arrays.asList(mealId));
return query;
}
});
adapter.setTextKey("content");
// adapter.setImageKey("photo");
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
}
and when pressing the button (activate the method addTheComment) it adds the text from the edit text (txtComment)to insert it into the Comment section where you make a relation to the Post class.
public void addTheComment() {
// Create the comment
ParseObject myComment = new ParseObject("Comment");
myComment.put("content", txtComment.getText().toString());
// Add a relation between the Post with objectId "1zEcyElZ80" and the comment
myComment.put("parent", ParseObject.createWithoutData("Meal", mealId));
// This will save both myPost and myComment
myComment.saveInBackground();
}