here is the samplae code what I want to do is, get json object or string out of this data databaseReference.addValueEventListener(new ValueEventListener()
thing and use it anywhere I want not only inside this database thing
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
Button photo;
public String da;
public String fx;
Object databaseValues;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
photo = findViewById(R.id.light);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
@RequiresApi(api = Build.VERSION_CODES.S)
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
databaseValues = snapshot.getValue(Object.class);
String value = new Gson().toJson(databaseValues);
JSONObject jsonObj;
try {
jsonObj = new JSONObject(value);
da = jsonObj.getString("test");
Log.i("databaseValue inside: ", da);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "Fail to get data.", Toast.LENGTH_SHORT).show();
}
});
try {
String value = new Gson().toJson(databaseValues);
JSONObject jsonObj;
jsonObj = new JSONObject(value);
fx = jsonObj.getString("test");
} catch (JSONException e) {
e.printStackTrace();
}
if (Objects.equals(da, "found")) {
photo.setBackgroundColor(getResources().getColor(R.color.white));
}
if (da == null){
Log.i("databaseValue: ", "null");
} else {
Log.i("databaseValue: ", da);
}
if (fx == null){
Log.i("fx: ", "null");
} else {
Log.i("fx: ", fx);
}
}
}
I'm getting databaseValue null and fx null but databaseVale inside is found, i want this data to be outside.