This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have code that ought to make my ListView clickable and bring my user to another activity. But I'm getting an error saying
Attempt to invoke virtual method 'void android.widget.ListView.setClickable(boolean)' on a null object reference
But I've no idea how it's a null object reference if the ListView is working. Here is my feed code:
public void populateList() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference allBooksRef = rootRef.child("All_Books");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Book> bookModelList = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Book book = ds.getValue(Book.class);
bookModelList.add(book);
}
ListView list = (ListView) findViewById(R.id.listView);
CustomListAdapter adapter = new CustomListAdapter(AdminFeed.this, bookModelList);
list.setAdapter(adapter);
list.setClickable(true);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
allBooksRef.addListenerForSingleValueEvent(valueEventListener);
list.setClickable(true);
list.setOnItemClickListener((AdapterView.OnItemClickListener) this);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(AdminFeed.this, BookIndexed.class);
i.putExtra("ValueKey", modelList.get(position).getTitle());
i.putExtra("ValueKey2", modelList.get(position).getAuthor());
startActivity(i);
title = bookModelList.get(position).getTitle();
}
Why is this throwing up such an error?
Move findViewById outside ValueEventListener() like below code
Try this
public void populateList() {
ListView list = (ListView) findViewById(R.id.listView);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference allBooksRef = rootRef.child("All_Books");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Book> bookModelList = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Book book = ds.getValue(Book.class);
bookModelList.add(book);
}
CustomListAdapter adapter = new CustomListAdapter(AdminFeed.this, bookModelList);
list.setAdapter(adapter);
list.setClickable(true);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
allBooksRef.addListenerForSingleValueEvent(valueEventListener);
list.setClickable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent i = new Intent(AdminFeed.this, BookIndexed.class);
i.putExtra("ValueKey", modelList.get(position).getTitle());
i.putExtra("ValueKey2", modelList.get(position).getAuthor());
startActivity(i);
title = bookModelList.get(position).getTitle();
}
});
}
Related
After populating the Listview with the list of diaries, upon clicking a particular diary, the corresponding pictures have to be displayed in another activity.
For this, I'm passing the position of clicked item in the intent. But, the app crashes upon execution
This is the history fragment code
public class HistoryFragment extends Fragment
{
ListView lv;
Context context;
public HistoryFragment()
{
//default constructor
}
//The following method will get the context from the activity to which the fragment is attached
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.scrolllist, container, false);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("image").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//List<String> cities = new ArrayList<>();
//cities = new ArrayList<>();
final ArrayList<Word> cities = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String cityName = ds.getKey();
cities.add(new Word(cityName));
}
lv = (ListView)view.findViewById(R.id.list_of_ds);
ContentAdapter arrayAdapter = new ContentAdapter(context,cities);
lv.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
//Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//String diary_name=title.get(position).toString();
Intent myIntent = new Intent(view.getContext(), DiaryViewActivity.class);
myIntent.putExtra("diaryname", lv.getItemAtPosition(position).toString());
startActivity(myIntent);
}
});
return view;
}
}
This is the activity to which intent is passed
//DiaryViewActivity.java
public class DiaryViewActivity extends AppCompatActivity implements IFirebaseLoadDone
{
ViewPager viewPager;
MAdapter adapter;
DatabaseReference diaries;
IFirebaseLoadDone iFirebaseLoadDone;
FirebaseAuth mAuth=FirebaseAuth.getInstance();
//final ArrayList<Word> word = new ArrayList<Word>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diary_view);
Bundle bd = getIntent().getExtras();
String myVal = bd.getString("diaryname");
String currentUser;
currentUser = mAuth.getCurrentUser().getUid();
diaries = FirebaseDatabase.getInstance().getReference().child("image").child(currentUser)
.child(myVal);
iFirebaseLoadDone = this;
loadDairy();
viewPager = (ViewPager)findViewById(R.id.view_pager);
viewPager.setPageTransformer(true,new DepthPageTransformer());
}
private void loadDairy() {
diaries.addListenerForSingleValueEvent(new ValueEventListener() {
List<Display> diaryList = new ArrayList<>();
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data:dataSnapshot.getChildren()) {
Display d = data.getValue(Display.class);
//word.add(new Word(d.dname));
diaryList.add(d);
}
iFirebaseLoadDone.onFirebaseLoadSuccess(diaryList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
iFirebaseLoadDone.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<Display> diaryList) {
adapter = new MAdapter(this,diaryList);
viewPager.setAdapter(adapter);
}
#Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this,"error! "+message,Toast.LENGTH_SHORT).show();
}
}
The following error occurs -
Attempt to invoke virtual method 'void android.widget.listview.setonitemclicklistener(android.widget.adapterview$onitemclicklistener)' on a null object reference
At the time that you call lv#setOnItemClickListener, your ListView (lv) hasn't been instantiated yet and won't be until the callback to ValueEventListener#onDataChange happens.
I'm trying to upload some data to my firebase realtime database, but everytime I start the app, the data resets and my database is empty. Why is this?
This is all done within a fragment.
I've also created a POJO Months class and a MonthList class for the listView/
Below is all of the code concerning firebase.
DatabaseReference databaseReference;
EditText editText;
public void addMonth(){
String id = databaseReference.getKey();
String name = editText.getText().toString();
boolean ifPaid = true;
Months months = new Months(name, id, ifPaid);
databaseReference.push().setValue(months);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_to_do,container,false);
setHasOptionsMenu(true);
final ListView listView = v.findViewById(R.id.listView);
databaseReference = FirebaseDatabase.getInstance().getReference("month");
editText = v.findViewById(R.id.editText);
monthsList = new ArrayList<>();
//button that triggers addMonth() method.
Button upload = v.findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addMonth();
}
});
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
monthsList.clear();
for (DataSnapshot monthsSnapshot : dataSnapshot.getChildren()){
Months months = monthsSnapshot.getValue(Months.class);
monthsList.add(months);
}
MonthList adapter = new MonthList(getActivity(), monthsList);
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return v;
}
I've problem storing data into ListView from database on Firebase, I'm using the method below it runs when I click on button,
here is the method I use
private void retrieveMyDataMethod(){
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child(uid).child("name").getValue(String.class);
String address = dataSnapshot.child(uid).child("address").getValue(String.class);
String[] data = new String[]{
name, address
};
List<String> data_list = new ArrayList<String>(Arrays.asList(data));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data_list);
listViewRe.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
To solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.orderByChild("name");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
list.add(name);
}
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output in your ListView will be:
cmon
here
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> al = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String rId = ds.child("Phone_Number").getValue(String.class);
String name = ds.child("Name").getValue(String.class);
al.add(name);
al.add(rId);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, al);
ListView listView = rootView.findViewById(R.id.usersList);
listView.setAdapter(adapter);
mProgressDialogue.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
};
usersRef.addListenerForSingleValueEvent(eventListener);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//This cannot be done in this way
Intent intent = new Intent(getActivity(), Chat.class);
String rId = (String)parent.getItemAtPosition(position);
String name = (String)parent.getItemAtPosition(position);
intent.putExtra("Recievers_Id", rId);
intent.putExtra("Recievers_Name", name);
startActivity(intent);
}
});
return rootView;
It's like. In the listview... Of the same user userid and name is shown... Ik y that is shown. Its because I hav added al.add (name) and also id... That's becuase... In onclicklistener I want to fetch id of the user but the listview should contain names... I'm not able to do that... Like if I click on the name of the user it fetches name and if I click on id of the user it fetches id... I want it to work like... IF I CLICK ON NAME OF THE USER IT SHOULD FETCH ID
Database
I have tried using orderByChild and nested for loops, but i am not sure how which method to use or how to use it. The purpose is to display cards of various strings in JOBOVERVIEW. Do you fellow stackoverflowrians have an answer, I have been stuck for a while and dont know where to proceed form here.
cheers and please dont hate.
package com.example.sherwin.todo;
import java.util.ArrayList;
public class JobList extends Fragment {
public JobList() {
}
public static JobList newInstance() {
JobList fragment = new JobList();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_job_list, container, false);
final RecyclerView recyclerView = (RecyclerView)rootView.findViewById(R.id.job_list_recycler_view);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(llm);
final ArrayList<JobClass> joblistclass = new ArrayList<>();
final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("USERS/04950F4AE53F80/JOBS");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data:dataSnapshot.getChildren()
) {
if (data.getChildren().equals("JOBOVERVIEW")){
JobClass jblst = data.getValue(JobClass.class);
joblistclass.add(jblst);
}
}
final JobListRecyclerAdapter adapterb = new JobListRecyclerAdapter(joblistclass);
recyclerView.setAdapter(adapterb);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG:", "Failed to read value.", error.toException());
}
});
return rootView;
}
}
To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference jobsRef = rootRef
.child("USERS")
.child("04950F4AE53F80")
.child("JOBS");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String jobDate = ds.child("JOBOVERVIEW").child("jobDate").getValue(String.class);
Log.d("TAG", jobDate);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
jobsRef.addListenerForSingleValueEvent(eventListener);
And the output will be:
29/09
2/2
//and so on