Asked  7 Months ago    Answers:  5   Viewed   41 times

I am creating an app in which points increases on button click and those points should be saved to firebase. I managed to save those data to firebase. But when I destroy my app and open it again the points value is showing same but after clicking button. It again starts from 0.

For example: every time on button click the points value increases to 10 points. Now when I completely destroy the app and open it again, the points value shows same, but when button clicked it again starts from initial condition.

Here is my code

    int amount = 0;

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

button_claim.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            amount = amount + 100;


            textView_points.setText(String.valueOf(amount));
            databaseReference.setValue(textView_points.getText().toString());

        }
    });


}


@Override
    protected void onStart() {
    super.onStart();
    if (mAuth.getCurrentUser() == null) {
        finish();
        Intent main = new Intent(this,MainActivity.class);
        main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(main);
    }

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            textView_points.setText(dataSnapshot.getValue(String.class));
            databaseReference.setValue(textView_points.getText().toString());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            Toast.makeText(Main2Activity.this,"error",Toast.LENGTH_LONG).show();
        }
    });



    }

Before destroying the app see the image please, points increasing on button click before destroying the app and uploading to database please see image 1

Opened app again(after closing) it is showing the same updated point please see image 2

Now when i click claim it returns back to 100 please see image number 3

please help me on this problem, and i am a newbie Thanks

 Answers

85

Edit: 29th, June 2020

Now it's also possible to solve this problem without the use of a transaction. We can simply increment a value using:

rootRef.child("score").setValue(ServerValue.increment(1));

And for decremenet, the following line of code is required:

rootRef.child("score").setValue(ServerValue.increment(-1));

This is how you set a value in your Firebase database:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("score").setValue(1);

Assuming that the your score field is of type Integer, to solve this, please use the following method:

public static void setScore(String operation) {
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference scoreRef = rootRef.child("score");
    scoreRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer score = mutableData.getValue(Integer.class);
            if (score == null) {
                return Transaction.success(mutableData);
            }

            if (operation.equals("increaseScore")) {
                mutableData.setValue(score + 1);
            } else if (operation.equals("decreaseScore")){
                mutableData.setValue(score - 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {}
    });
}

For this, I recommend you definitely use transactions. You will avoid wrong results if users are trying to increase/decrease the score in the same time. So as a conclusion, call this method accordingly to your increase/decrease operation.

This is how you can read it:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Integer score = ds.getValue(Integer.class);
        Log.d("TAG", score + "");
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
Tuesday, June 1, 2021
 
mcography
answered 7 Months ago
96

The latest version (3.x) of FirebaseUI implements a different method of initializing a FirebaseRecyclerAdapter than previous versions. From the using the FirebaseRecyclerAdapter documentation:

First, configure the adapter by building FirebaseRecyclerOptions. In this case we will continue with our chat example:

 FirebaseRecyclerOptions<Chat> options =
                new FirebaseRecyclerOptions.Builder<Chat>()
                        .setQuery(query, Chat.class)
                        .build();

Next create the FirebaseRecyclerAdapter object. You should already have a ViewHolder subclass for displaying each item.

So, for your example, you'll need to do something similar to:

FirebaseRecyclerOptions<image_details> options =
        new FirebaseRecyclerOptions.Builder<image_details>()
                .setQuery(myRef, image_details.class)
                .build();

FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<image_details, BlogViewHolder>(options) {
    @Override
    public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.individual_row, parent, false);

        return new BlogViewHolder(view);
    }

    @Override
    protected void onBindViewHolder(BlogViewHolder holder, int position, image_details model) {
        // Bind the image_details object to the BlogViewHolder
        // ...
    }
};

Finally, the FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call adapter.startListening() and adapter.stopListening() to stop the listener. It's recommended to call these in onStart() and onStop() respectively. Further details on this are available in the FirebaseRecyclerAdapter lifecycle documentation.

Tuesday, June 1, 2021
 
msg
answered 7 Months ago
msg
77

Create DataBase helper class like this..

On Capturing the image insert the image by converting into bytes:

Imagehelper help=new Imagehelper(this);

    if (requestCode == CAMERA_REQUEST) {  
                        Bitmap photo = (Bitmap) data.getExtras().get("data");   
                        imageView.setImageBitmap(photo);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        byte[] byteArray = stream.toByteArray();

                        help.insert(byteArray);
    }

To retrieve Form the Database:

Imagehelper help=new Imagehelper(this);

       Cursor c= help.getAll();
       int i=0;
       if(c.getCount()>0)
       {  
           Bitmap[]  array=new Bitmap[c.getCount()];
           c.moveToFirst();
           while(c.isAfterLast()==false)
           {

               byte[] bytes=c.getBlob(c.getColumnIndex("imageblob"));

            array[i]=BitmapFactory.decodeByteArray(bytes, 0, 0);
            c.moveToNext();
            i++;
            }
           Log.e("Bitmap length",""+array.length);
       }

Pass this Bitmap array to ListView

Thursday, June 24, 2021
 
Deyson
answered 6 Months ago
43

The problem is that you are creating the property "mobile_phone" as a String and on Firebase it is a Long type.

Change:

private String mobile_phone;

To:

private Long mobile_phone;
Thursday, June 24, 2021
 
NaeiKinDus
answered 6 Months ago
76

Unable to see the log since i got to take the device out to test.since this app needs a moving location

Perhaps you forgot to call requestLocationUpdates() ?

Unable to see the log

You have not put any Logs . Use Logs.D("YOURTAG", "Logs statements");

  Location l2 = new Location("");
  l2.setLatitude(loc.getLatitude());
  l2.setLongitude(loc.getLongitude());

^ This is not required

 float door = l1.distanceTo(loc);

You have to wait for a few minutes till the GPS Icon stops animating. This means that a fix has been attained. So check if loc is null

Wednesday, November 24, 2021
 
bshacklett
answered 1 Week ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share