Checking if a value is null - android

In my app, the registered user adds successfully comments on articles.
For example see this screenshot.
Now I want to read and display those comments in a recyclerview. Before that I want to check if the particular article has comments. If not then I should make a texview visible saying that there are no comments for that specific article. The news( which I get from Google News Api) don't have ids, so instead I using the newsTitle as shown in figure.
I wrote this code.
public class DisplayComments extends AppCompatActivity {
ArrayList<Comment> commentArrayList;
Toolbar mToolbar;
private DatabaseReference mDatabase;
private Intent i;
private String newsTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_comments);
mToolbar = (Toolbar) findViewById(R.id.display_comments_app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Display Comments");
mDatabase = FirebaseDatabase.getInstance().getReference();
commentArrayList = new ArrayList<>();
i = getIntent();
newsTitle = i.getStringExtra("newsTitle");
mDatabase = FirebaseDatabase.getInstance().getReference();
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("comments").child("newsTitle").equalTo(newsTitle);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
Toast.makeText(DisplayComments.this,"There are comments posted",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(DisplayComments.this,"There are no comments posted",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
However, I always get There are no comments posted even for the articles with comments. How can make a good query that checks if the there are comments or not?
Thanks,
Theo.

You need orderByChild('newsTitle') of the article in your query. Fix it like this:
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
The above code will match the newsTitle filed with your given value.
Your code was trying to make a query but not defining the criteria.

Related

Value not displaying Correctly in Spinner Android

I have a Spinner in which I want value from Firebase Database. I try what I Know since I am new to Android but the value in Spinner is not coming as i want it is coming like this.
When i am passing String Array directly it is coming Properly but it is doing problem when the String Array fill with the Firebase data.Here is also my Database.
final String[] batcht = {"1903f","343","33323"};
XML
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/stubatch"
/>
JAVA
public class Student extends AppCompatActivity {
DatabaseReference ref;
Spinner spinner;
List<String> store;
String[] batchlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
spinner = findViewById(R.id.stubatch);
store =new ArrayList<>();
Student_ID =getIntent().getStringExtra("Student_Id");
ref = FirebaseDatabase.getInstance().getReference("Batch");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot batches : dataSnapshot.getChildren()){
String a= batches.getValue().toString();
store.add(a);
}
batchlist = new String[store.size()];
for(int i=0;i<batchlist.length;i++){
batchlist[i]=store.get(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item,batchlist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}
I don't know what I am doing wrong.
When you are fetching data you are doing some mistake. You are not fetching according to ur insertion technique try this
In for loop of datasnapshot use this code:
String a = batches.child("1710f").getValue().toString()
By doing this only data with the 1710f key will be picked for other values you have listed out all the keys.
Hopefully, this will workout
Actually the problem was that I was Storing the Data in the Firebase the wrong way.
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String batchdata = edit.getText().toString();
ref = FirebaseDatabase.getInstance().getReference("Batch").child(User_Id);
ref.child(batchdata).setValue(batchdata);
Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),Faculty.class);
i.putExtra("User_Id",User_Id);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
I Just have to remove the .child(User_Id);.
Now it is working Fine.

Get ListView of messages in parent app. Error: Attempt to read from field 'java.lang.String on a null object reference

This code motive is to get firebase records and display them in a listview , but there occurs exception .
images shows my firebase database.
class MainActivity extends AppCompatActivity {
List<MessageResults> CallList;
ListView listView;
AdapterMessage adapterMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CallList = new ArrayList<>();
listView = findViewById(R.id.lv);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef =
database.getReference("callreciver").child("History").child("Messsages");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
MessageResults Results=dataSnapshot.getValue(MessageResults.class);
CallList.add(Results);
adapterMessage=new AdapterMessage(getApplicationContext(),CallList);
listView.setAdapter(adapterMessage);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "Unable to display data",
Toast.LENGTH_SHORT).show();
}
});
myadapter class
.
adapter class for adding view . i am getting error in line number 31, attempting to read null object.
Is the error bcz i am trying to get data in a wrong way.or some another issue?

Android fetching values from Firebase Database

Hello so I've been strugging for awhile now. I want to consult someone about my code. I want to apply
a coloring function to my app.
When the person presses the button when it's at its:
GREEN state it updates the value on the database to BEING HOUSEKEPT
YELLOW state when pressed sends READY FOR INSPECTION RoomStatus
RED state when pressed sends READY FOR HOUSEKEEPING RoomStatus
It was working earlier but when I tried to restrict the users that users who are Housekeepers can't access the RED STATE which are for House Keepers, I inserted somewhere in my code where I want to implement it.
I'm going over loops here can somebody tell me where I did wrong?
Here's my code:
Button room1;
private DatabaseReference mFirebaseDatabase, mFirebaseDatabase1, mFirebaseDatabase1room;
private FirebaseDatabase mFirebaseInstance;
private DatabaseReference referenceroom1;
private String roomStat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi_to_scan2);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
mFirebaseDatabase = mFirebaseInstance.getReference("Users");
mFirebaseDatabase1room = mFirebaseInstance.getReference("Rooms").child("Room1");
referenceroom1 = mFirebaseDatabase1.child("Room1").child("RoomStatus");
room1 = (Button) findViewById(R.id.rm1Btn);
mFirebaseDatabase1.child("Room1").addValueEventListener(new ValueEventListener() { //attach listener
#Override
public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
String location = locationSnapshot.getValue().toString();
if (location.equals("READY FOR HOUSEKEEPING")) {
room1.setBackgroundColor(Color.GREEN);
roomStat = "Green";
} else if (location.equals("BEING HOUSEKEPT")) {
room1.setBackgroundColor(Color.YELLOW);
roomStat = "Yellow";
} else {
room1.setBackgroundColor(Color.RED);
roomStat = "Red";
}
if (roomStat.equals("Green")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "BEING HOUSEKEPT";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity3.class);
startActivity(next1);
}
});
} else if (roomStat.equals("Yellow")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR INSPECTION";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity2.class);
startActivity(next1);
}
});
} else {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR HOUSEKEEPING";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity.class);
startActivity(next1);
//I ALSO WANT TO PUT A CONDITION HERE FETCHING userType from Structure
// mFirebaseDatabase = mFirebaseInstance.getReference("Users").child("userKey");
//but doing this would mean that I would have to put a listener inside, would that be okay? I tried when this
//was working at first but it didin't and now the whole thing is not working
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.
}
});
}
Here's my structure:
Can you help me identify what's the problem with how i implemented this?
I see nothing wrong, try debugging. Android is buggy nowadays, especially when you're connecting to a cloud database. In the left side of the run button the bug shaped one. Debug.
Or maybe you could try to show your location which is your string, to check if you pulled the right info from your database. You can use logs. A guide can be found here
https://developer.android.com/studio/debug/am-logcat.html

Android Firebase Auth and setValue [duplicate]

My Firebase database structure is:
I want to retrieve the full name of some user, when I have its key.
My code:
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth firebaseAuth;
private TextView textView;
private Button logbutton,wantToDeliverButton,lookForButton;
private String userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Firebase.setAndroidContext(this);textView = (TextView)findViewById(R.id.textView2);
Firebase usersRef = new Firebase("https://myfirstfirebaseauth.firebaseio.com");
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
Firebase ref = usersRef.child("User").child(user.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(User.class).getFullName();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
textView.setText("welcome "+userName);
}
}
But it set the textView to null. I try to put Toast inside the onDataChange() method, but it doesn't work. It seems it doesn't even get inside the method.
The line FirebaseUser user = firebaseAuth.getCurrentUser(); is correct because if i'm writing textView.setText("welcome "+ user.getEmail()); - I really get the correct email.
How to solve this? Am I using the correct listener? I don't want to change anything in the database, just retrieve.
Edit: it goes to onCancelled().
You're mixing capabilities from the legacy 2.5.X Firebase SDK (Example: Firebase.setAndroidContext()) and the new 9.X.X SDK (Example: FirebaseAuth.getInstance()). That is almost certainly a recipe for failure. Rework your code to use only the new SDK. The Setup Guide is here.

Android - can't retrieve data from firebase with a given uid

My Firebase database structure is:
I want to retrieve the full name of some user, when I have its key.
My code:
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth firebaseAuth;
private TextView textView;
private Button logbutton,wantToDeliverButton,lookForButton;
private String userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Firebase.setAndroidContext(this);textView = (TextView)findViewById(R.id.textView2);
Firebase usersRef = new Firebase("https://myfirstfirebaseauth.firebaseio.com");
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
Firebase ref = usersRef.child("User").child(user.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(User.class).getFullName();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
textView.setText("welcome "+userName);
}
}
But it set the textView to null. I try to put Toast inside the onDataChange() method, but it doesn't work. It seems it doesn't even get inside the method.
The line FirebaseUser user = firebaseAuth.getCurrentUser(); is correct because if i'm writing textView.setText("welcome "+ user.getEmail()); - I really get the correct email.
How to solve this? Am I using the correct listener? I don't want to change anything in the database, just retrieve.
Edit: it goes to onCancelled().
You're mixing capabilities from the legacy 2.5.X Firebase SDK (Example: Firebase.setAndroidContext()) and the new 9.X.X SDK (Example: FirebaseAuth.getInstance()). That is almost certainly a recipe for failure. Rework your code to use only the new SDK. The Setup Guide is here.

Categories

Resources