Here's the situation:
I am trying to remove a users information from an ArrayList(populated via Firebase Database) on a Card View.
This Card View is populated in the Recycler View. When the user clicks on a Card in the Recycler view, they are brought to a detail activity via an Intent.
In the intent, there is more user data as well as the option to approve or reject the user.
I want to be able to reject the user and then remove their card from the Recycler View.
I keep running into a null pointer error and I am not sure where else to go.
Stack trace is at the end.
Thank you very much for your time and assistance in this matter.
Relevant code below:
Fragment:
package org.codefordenver.encorelink;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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 java.util.ArrayList;
import java.util.Objects;
public class OrganizerDashboardPendingTab extends Fragment {
private String userId;
//Arraylist to hold our list of volunteer musicians
public static ArrayList<String> volunteerSmallView = new ArrayList<>();
public static ArrayList<String> volunteerDetail = new ArrayList<>();
public static ArrayList<String> volunteerLink = new ArrayList<>();
//private String field members to hold temp String data
private String tempFirst;
private String tempTalent;
private String tempLastName;
private String tempPhoneNumber;
private String tempStreetAddress;
private String tempCity;
private String tempZipcode;
public static String tempVideoLink;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
final RecyclerView musicianInfoRecycler = (RecyclerView) inflater.inflate(R.layout.tab1, container, false);
//Checking to make sure user is logged in and is not null
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
userId = user.getUid();
}
//setting DatabaseReference variable so we can search through the correct node in our DB
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child(CreateMusicianProfile.MUSICIAN_PROFILE);
//Instantiating and declaring our Adapter object for our Recycler View
final PendingMusicianInfoAdapter adapter = new PendingMusicianInfoAdapter(volunteerSmallView);
//this clear is a must so we aren't getting duplicated data in the cardview
volunteerSmallView.clear();
//Adding child event listener to our database object
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//iterate through each dataSnapshot inside mDatabase
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
//if we get a first name, add it to temp string
if (dataSnapshot1.getKey().equals("firstName")) {
tempFirst = Objects.requireNonNull(dataSnapshot1.getValue(String.class));
}
if (dataSnapshot1.getKey().equals("lastName")) {
tempLastName = Objects.requireNonNull(dataSnapshot1.getValue(String.class));
}
//if we get a musical talent, save it also into a temp string
if (dataSnapshot1.getKey().equals("musicalTalent")) {
tempTalent = Objects.requireNonNull("\nTalent: " + dataSnapshot1.getValue(String.class));
//in order to display all the string data together in one card,
//we have to add each temp string to the array list.
volunteerSmallView.add(tempFirst + " " + tempLastName + tempTalent);
}
if (dataSnapshot1.getKey().equals("phoneNumber")) {
tempPhoneNumber = Objects.requireNonNull( dataSnapshot1.getValue(String.class));
}
if (dataSnapshot1.getKey().equals("streetAddress")) {
tempStreetAddress = Objects.requireNonNull(dataSnapshot1.getValue(String.class));
}
if (dataSnapshot1.getKey().equals("city")) {
tempCity = Objects.requireNonNull(dataSnapshot1.getValue(String.class));
}
if (dataSnapshot1.getKey().equals("zipcode")) {
tempZipcode = Objects.requireNonNull("Zipcode: " + dataSnapshot1.getValue(String.class));
}
if (dataSnapshot1.getKey().equals("videoLink")) {
tempVideoLink = Objects.requireNonNull(dataSnapshot1.getValue(String.class));
volunteerLink.add(tempVideoLink);
volunteerDetail.add(tempFirst + " " + tempLastName +
"\n" + tempPhoneNumber +
"\n" + tempStreetAddress +
"\n" + tempCity + ", " + tempZipcode + "\n" + tempTalent + "\n");
}
}
//set adapater equal to our adapater object
musicianInfoRecycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
adapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
musicianInfoRecycler.setLayoutManager(linearLayoutManager);
adapter.setListener(new PendingMusicianInfoAdapter.Listener() {
#Override
public void onClick(int position) {
Intent intent = new Intent(getActivity(), MusicianDetails.class);
intent.putExtra(MusicianDetails.EXTRA_NUMBER, position);
getActivity().startActivity(intent);
}
});
return musicianInfoRecycler;
}
}
RecyclerView Adapter:
This class contains the rejectionButton and the onClickListener but it is always pointing to null.
package org.codefordenver.encorelink;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class PendingMusicianInfoAdapter extends RecyclerView.Adapter<PendingMusicianInfoAdapter.ViewHolder> {
private ArrayList<String> musicianInfo;
private Listener listener;
public interface Listener {
void onClick(int position);
}
public void setListener(Listener listener) {
this.listener = listener;
}
class ViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
Button rejectionButton;
public ViewHolder(CardView view) {
super(view);
cardView = view;
rejectionButton = view.findViewById(R.id.musician_rejection);
rejectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
removeAt(getAdapterPosition());
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
void bind(final int position) {
TextView textView = cardView.findViewById(R.id.pending_musician_info);
textView.setText(musicianInfo.get(position));
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
listener.onClick(position);
}
}
});
}
void removeAt(int position) {
musicianInfo.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, musicianInfo.size());
}
}
public PendingMusicianInfoAdapter(ArrayList<String> musicianInfo) {
this.musicianInfo = musicianInfo;
}
//called when recyclerview instantiates new viewholder instance
//creates the views
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.card_musician_info, parent, false);
return new ViewHolder(cv);
}
//called when recycler view wants to populate data from model for the user to see
//after each view holder is created, recycler view calls onBindViewHolder to populate item
//with data
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(position);
}
//returns number of items in data source
#Override
public int getItemCount() {
return musicianInfo.size();
}
}
Musician Details class that is triggered from the OrganizerDashboardPendingTab class.
package org.codefordenver.encorelink;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.Objects;
import java.util.regex.Matcher;
public class MusicianDetails extends AppCompatActivity {
public static final String EXTRA_NUMBER = "number";
//
// public static ArrayList<String> approvedMusicians = new ArrayList<>();
private TextView closeButton;
public static int cardNumber;
private String talentURL;
private TextView musicalTalentLink;
private Button approvalButton;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
private String userId;
public static boolean approved;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_musician_details);
closeButton = findViewById(R.id.x_button);
TextView textView = findViewById(R.id.musician_details);
musicalTalentLink = findViewById(R.id.musical_talent_link);
approvalButton = findViewById(R.id.musician_approval);
databaseReference = FirebaseDatabase.getInstance().getReference();
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
userId = user.getUid();
}
cardNumber = (int) Objects.requireNonNull(getIntent().getExtras()).get(EXTRA_NUMBER);
String musicianDetails = OrganizerDashboardPendingTab.volunteerDetail.get(cardNumber);
findURL(OrganizerDashboardPendingTab.volunteerLink);
musicalTalentLink.setText(talentURL);
textView.setText(musicianDetails);
musicalTalentLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(talentURL));
startActivity(intent);
} catch (ActivityNotFoundException e){
Toast.makeText(MusicianDetails.this, "Bad URL!", Toast.LENGTH_SHORT).show();
}
}
});
approvalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// approvedMusicians.add(OrganizerDashboardPendingTab.volunteerDetail.get(cardNumber));
databaseReference.child(CreateOrganizerProfile.ORGANIZER_PROFILE).child(userId).child("approved_musicians").child(String.valueOf(cardNumber)).
setValue(OrganizerDashboardPendingTab.volunteerDetail.get(cardNumber));
Toast.makeText(MusicianDetails.this, "Musician approved!", Toast.LENGTH_SHORT - 3).show();
Toast.makeText(MusicianDetails.this, "Moving musician to In Progress...", Toast.LENGTH_SHORT).show();
approved = true;
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
public void findURL(ArrayList<String> data) {
Matcher m = Patterns.WEB_URL.matcher(data.get (cardNumber));
while (m.find()) {
String url = m.group();
talentURL = url;
}
}
}
card_musician_info.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/musician_info_cardview"
card_view:cardElevation="3.5sp"
android:layout_margin="8dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/pending_musician_info"
android:textSize="25dp"
android:paddingLeft="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
Stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.codefordenver.encorelink, PID: 12123
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at org.codefordenver.encorelink.PendingMusicianInfoAdapter$ViewHolder.<init>(PendingMusicianInfoAdapter.java:41)
at org.codefordenver.encorelink.PendingMusicianInfoAdapter.onCreateViewHolder(PendingMusicianInfoAdapter.java:94)
at org.codefordenver.encorelink.PendingMusicianInfoAdapter.onCreateViewHolder(PendingMusicianInfoAdapter.java:16)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6493)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5680)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3962)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1767)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:132)
at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1361)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:869)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:761)
at android.view.View.layout(View.java:19659)
at android.view.ViewGroup.layout(ViewGroup.java:6075)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2496)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2212)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1392)
E/AndroidRuntime: at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6752)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:658)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
In your PendingMusicianInfoAdapter you are using:-
rejectionButton = view.findViewById(R.id.musician_rejection); //here is your null pointer
Reason:-
In you card_musician_info.xml
you don't have any Button "musician_rejection"
NOTE:- Every time you face any null pointer issue it is most commonly due to wrong initialization/ id mismatch / or no reference in correct XML.
In this case, you may have "musician_rejection" earlier which was registered in your "R" class but later you may have removed it but in your "R" class it somehow stays. Or it can be quite possible that you may have "musician_rejection" in some other XML. Android Studio is not that smart enough to understand that use parent XML file for all its id references in JAVA file.
Use http://jakewharton.github.io/butterknife/ which eliminates all such issues.
Use debugger step by step, For better understanding.
I think in this situation you need to use EventBus.
Try https://github.com/greenrobot/EventBus
Related
This is my error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.blogapp, PID: 20085
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.together.adapter.PetchingBunyangAdapter$2.onDataChange(PetchingBunyangAdapter.java:152)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##17.0.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##17.0.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##17.0.0:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I know what meaning of null but in this case i can not under stand
i try to using recycler in my fragment
This is my adapater that can't find widget
package com.example.together.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.together.R;
import com.example.together.activities.petching.PetchingBunyangDetailInfo;
import com.example.together.common.Common;
import com.example.together.model.PetchingBunyang;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 java.util.List;
public class PetchingBunyangAdapter extends RecyclerView.Adapter<PetchingBunyangAdapter.MyViewHolder> {
private static final String TAG = "PetchingBunyangAdapter";
FirebaseUser firebaseUser;
DatabaseReference reference;
Context mContext;
List<PetchingBunyang> mPetchingBunyang;
public PetchingBunyangAdapter(Context mContext, List<PetchingBunyang> mPetchingBunyang) {
this.mContext = mContext;
this.mPetchingBunyang = mPetchingBunyang;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_petching_bunyang_pet_list, parent, false);
return new PetchingBunyangAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder viewHolder, int position)
{
Common common = new Common();
final PetchingBunyang petchingBunyang = mPetchingBunyang.get(position);
petchingBunyang.getPetBunyangId();
Log.d(TAG, "AAAAAA"+mPetchingBunyang.get(0).getPetBunyangId());
Log.d(TAG, "TTTT "+petchingBunyang.getPetBunyangId());
Log.d(TAG, "onBindViewHolder: "+Log.d(TAG, "onBindViewHolder: "));
Log.d(TAG, "onBindViewHolder: 초코우유"+mPetchingBunyang.get(0).getPetBunyangId());
Log.d(TAG, "딸기우유: "+mPetchingBunyang.get(position).getPetBunyangId());
getPetInfo(mPetchingBunyang.get(position).getPetBunyangId(), viewHolder.img_pet, viewHolder.petName, viewHolder.petAge, viewHolder.petBreed, viewHolder.gender_m, viewHolder.gender_w);
viewHolder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(mContext, PetchingBunyangDetailInfo.class);
// 디테일 정보 전달....
intent.putExtra("petname", mPetchingBunyang.get(position).getPetName());
intent.putExtra("intro", mPetchingBunyang.get(position).getPetAge());
intent.putExtra("Thumbnail", mPetchingBunyang.get(position).getPetBreed());
// start the activity
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount()
{
return mPetchingBunyang.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
public TextView petName, petBreed, petAge;
public ImageView gender_m, gender_w, bunyangpet_detail, img_pet;
public MyViewHolder(View itemView)
{
super(itemView);
//펫 프로필
petName = itemView.findViewById(R.id.petName);
petBreed = itemView.findViewById(R.id.petBreed);
petAge = itemView.findViewById(R.id.petAge);
img_pet = itemView.findViewById(R.id.img_pet);
//이미지들
img_pet = itemView.findViewById(R.id.img_pet);
gender_m = itemView.findViewById(R.id.gender_m);
gender_w = itemView.findViewById(R.id.gender_w);
//상세보기 넘어가는 icon
bunyangpet_detail = itemView.findViewById(R.id.bunyangpet_detail);
}
}
// 펫 정보 이름, 나이, 견종, 성별,
private void getPetInfo(String petbunyangid, final ImageView imageView, final TextView petAge, final TextView petName, final TextView petBreed, final ImageView gender_m, final ImageView gender_w)
{
Log.d(TAG, "펫분양: "+petbunyangid);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("PetchingBunyang").child(petbunyangid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
PetchingBunyang petchingBunyang = dataSnapshot.getValue(PetchingBunyang.class);
Log.d(TAG, "펫정보 가져오는지 보자: "+petchingBunyang.getPetName());
Glide.with(mContext).load(petchingBunyang.getPetImg()).into(imageView);
petName.setText(petchingBunyang.getPetName());
petBreed.setText(petchingBunyang.getPetBreed());
petAge.setText(petchingBunyang.getPetAge());
//성별표시
if (petchingBunyang.getPetGender().equals("Female"))
{
gender_w.setVisibility(View.VISIBLE);
}else
{
gender_m.setVisibility(View.VISIBLE);
}
//
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
but i already get the widget as u see from here
From here i already added widget
public class MyViewHolder extends RecyclerView.ViewHolder{}
I don't understand what makes it null? eventhough it already exist
Try debugging these value , as one of the value might be coming null .
petchingBunyang.getPetName();
petchingBunyang.getPetBreed();
petchingBunyang.getPetAge()
and do check if Pet Age is String or not .
I am creating an app using swipecards. It is supposed to pull through data from the Bookmakers Firebase table however when I launch it it crashes the app.
The code for the 3 referenced Java filed is below but there is no bugs and I can't spot the reason why it crashes.
BETSWIPE.java
package com.example.swoddz.swoddz;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import java.util.List;
public class BetSwipe extends AppCompatActivity {
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
private FirebaseAuth mAuth;
List<cards2> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
//add the view via xml or programmatically
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bet_swipe);
al = new ArrayList<>();
al.add("php");
arrayAdapter = new ArrayAdapter<>(this, R.layout.item2, R.id.helloText, al );
rowItems = new ArrayList<cards2>();
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowItems.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(BetSwipe.this, "Left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(BetSwipe.this, "Right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(BetSwipe.this, "clicked!", Toast.LENGTH_SHORT).show();
}
});
}
public void checkBookmakers() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference BookmakerDB = FirebaseDatabase.getInstance().getReference().child("Football-Bets");
BookmakerDB.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()){
al.add(dataSnapshot.child("Bookmaker").getValue().toString());
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
ArryayApadpter2.JAVA
package com.example.swoddz.swoddz;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by manel on 9/5/2017.
*/
public class arrayAdapter2 extends ArrayAdapter<cards>{
Context context;
public arrayAdapter2(Context context, int resourceId, List<cards> items){
super(context, resourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent){
cards card_item = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
TextView Bookmaker = (TextView) convertView.findViewById(R.id.name);
ImageView image = (ImageView) convertView.findViewById(R.id.image);
Bookmaker.setText(card_item.getName());
// image.setImageResource(R.mipmap.ic_launcher);
return convertView;
}
}
CARDS2.Java
package com.example.swoddz.swoddz;
public class cards2 {
private String userId;
private String Bookmaker;
public cards2(String userId, String name){
this.userId = userId;
this.Bookmaker = Bookmaker;
}
public String getUserId(){
return userId;
}
public void setUserID(String userID){
this.userId = userId;
}
public String getBookmaker(){
return Bookmaker;
}
public void setBookmaker(String Bookmaker){
this.Bookmaker = Bookmaker;
}
}
Stack Trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.swoddz.swoddz, PID: 371
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.remove(ArrayList.java:477)
at com.example.swoddz.swoddz.BetSwipe$1.removeFirstObjectInAdapter(BetSwipe.java:63)
at com.lorentzos.flingswipe.SwipeFlingAdapterView$1.onCardExited(SwipeFlingAdapterView.java:223)
at com.lorentzos.flingswipe.FlingCardListener$1.onAnimationEnd(FlingCardListener.java:256)
at android.view.ViewPropertyAnimator$AnimatorEventListener.onAnimationEnd(ViewPropertyAnimator.java:1121)
at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1149)
at android.animation.ValueAnimator.doAnimationFrame(ValueAnimator.java:1309)
at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
at android.animation.AnimationHandler.-wrap2(AnimationHandler.java)
at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
at android.view.Choreographer.doCallbacks(Choreographer.java:702)
at android.view.Choreographer.doFrame(Choreographer.java:635)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
Database Structure
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
In my chat App FriendsFragment is shwoing blank. If I want to reflect that then, I have run the app, open the Friends tab in my app and after Instant run in Android studio and it will reflect. If it will not, then I have to add Log statement anywhere in my FriendsFragment, and run Instant run with exctly the open tab of friendsfragmet.
Why I'm telling you to add Log statement is necessary because I found this bug that whenever I change something on my Friends Fragment and then run Instant run, then only it will show the Fragment part. And I have to do this every time, otherwise it won't show. Add Log statement and remove second time, or change tag or change message, do something that makes the changes, and must run Instant run (that Yellow symbol like booster).
NOTE: I'm still doing this thing, I observe this problem by myself and I also don't know why I have to change something every time to show this Fragment? I also built the similar fragment in this same app, but for that there is no problem!
FriendFragment
package com.jimmytrivedi.lapitchat;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class FriendsFragment extends Fragment {
private RecyclerView FriendRecyclerView;
private DatabaseReference databaseReference, UsersDatabaseReference;
private FirebaseAuth mAuth;
private String currentUID;
private View MainView;
public FriendsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainView = inflater.inflate(R.layout.fragment_friend, container, false);
FriendRecyclerView = MainView.findViewById(R.id.FriendRecyclerView);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
currentUID = mAuth.getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Friends").child(currentUID);
databaseReference.keepSynced(true);
UsersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
UsersDatabaseReference.keepSynced(true);
}
FriendRecyclerView.setHasFixedSize(true);
FriendRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
Log.d("wihddiewd", "Is it going?");
return MainView;
}
#Override
public void onStart() {
super.onStart();
Query query = FirebaseDatabase. getInstance()
.getReference()
.child("Friends")
.limitToLast(50);
FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>()
.setQuery(query, Friends.class)
.build();
final FirebaseRecyclerAdapter<Friends, FriendsViewHolder> FriendsRecyclerViewAdapter = new
FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final FriendsViewHolder holder, int position, #NonNull Friends model) {
holder.setDate(model.getDate());
final String listUID = getRef(position).getKey();
UsersDatabaseReference.child(listUID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("Name").getValue().toString();
String thumbImage = dataSnapshot.child("thumbImage").getValue().toString();
String userOnline = dataSnapshot.child("Online").getValue().toString();
holder.setName(userName);
holder.setThumbImage(thumbImage, getContext());
holder.setUserOnline(userOnline);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]{"Open profile", "Send message"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(getContext(), ProfileActivity.class);
intent.putExtra("userID", listUID);
startActivity(intent);
}
if (which == 1) {
Intent intent = new Intent(getContext(), ChatActivity.class);
intent.putExtra("userID", listUID);
intent.putExtra("userName", userName);
startActivity(intent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public FriendsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new FriendsViewHolder(view);
}
};
FriendRecyclerView.setAdapter(FriendsRecyclerViewAdapter);
FriendsRecyclerViewAdapter.startListening();
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String date) {
TextView userStatusView = mView.findViewById(R.id.userStatus);
userStatusView.setText(date);
}
public void setName(String name) {
TextView userNameView = mView.findViewById(R.id.userName);
userNameView.setText(name);
}
public void setThumbImage(String thumbImage, Context context) {
CircleImageView circleImageView = mView.findViewById(R.id.userImage);
Picasso.get().load(thumbImage).placeholder(R.drawable.defaultimage)
.into(circleImageView);
}
public void setUserOnline(String online) {
ImageView userOnline = mView.findViewById(R.id.online);
if (online.equals("true")) {
userOnline.setVisibility(View.VISIBLE);
} else {
userOnline.setVisibility(View.INVISIBLE);
}
}
}
}
Update
I know this is weird bug. But basically when I open my app and in app firends tab (which is FriendsFragment.java), it is showing blank. So I tried to debug that is there any mistake on my code or not? But I didn't find. But while debugging time, when I go to my firends tab in my mobile app, and put any log statement in Android Studio (because when I add/remove something so Android Studio will understand that some changes made happen, and then I run Instant run(not normal run) then FriendFragment will reflect and it shows the user list.
And I have to do this every time, (means I have to add something/remove something, that consider changes for Android Studio) then only FriendsFragment will show the users list. And even if I not open my Friends tab, but open something else in app and than run (instant run) that is also not work! Only when I just go to friends tab (that time it is showing blank, but that is okay) and run Instant run, then only it will reflect.
fragment_friends.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FriendsFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/FriendRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
users_single_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/userImage"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:src="#drawable/defaultimage" />
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/userImage"
android:layout_marginStart="99dp"
android:text="Display Name"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="#+id/userStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/userName"
android:layout_below="#+id/userName"
android:text="User default Status"
android:textSize="15dp" />
<ImageView
android:id="#+id/online"
android:layout_width="8dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/userName"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/userName"
android:visibility="invisible"
android:src="#drawable/online" />
</RelativeLayout>
Another Fragment ChatFragment, which is similar to this and working pretty fine).
ChatFragment.java
package com.jimmytrivedi.lapitchat;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatFragment extends Fragment {
private RecyclerView ConversationList;
private DatabaseReference ConversationRef, MessageRef, UserRef;
private FirebaseAuth mAuth;
private String currentUID;
private View MainView;
public ChatFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainView = inflater.inflate(R.layout.fragment_chat, container, false);
ConversationList = MainView.findViewById(R.id.ConversationList);
mAuth = FirebaseAuth.getInstance();
currentUID = mAuth.getCurrentUser().getUid();
ConversationRef = FirebaseDatabase.getInstance().getReference().child("Chat").child(currentUID);
ConversationRef.keepSynced(true);
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
UserRef.keepSynced(true);
MessageRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUID);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
ConversationList.setHasFixedSize(true);
ConversationList.setLayoutManager(layoutManager);
return MainView;
}
#Override
public void onStart() {
super.onStart();
Query conversationQuery = ConversationRef.orderByChild("timestamp");
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Chat")
.limitToLast(50);
FirebaseRecyclerOptions<Conversation> options = new FirebaseRecyclerOptions.Builder<Conversation>()
.setQuery(query, Conversation.class)
.build();
FirebaseRecyclerAdapter<Conversation, ConversationViewHolder> ConversationRecyclerViewAdapter = new
FirebaseRecyclerAdapter<Conversation, ConversationViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ConversationViewHolder holder, int position, #NonNull final Conversation model) {
final String listUID = getRef(position).getKey();
Query lastMessageQuery = MessageRef.child(listUID).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String data = dataSnapshot.child("message").getValue().toString();
holder.setMassage(data, model.isSeen());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
UserRef.child(listUID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("Name").getValue().toString();
String userThumb = dataSnapshot.child("thumbImage").getValue().toString();
if (dataSnapshot.hasChild("Online")) {
String userOnline = dataSnapshot.child("Online").getValue().toString();
holder.setUserOnline(userOnline);
}
holder.setName(userName);
holder.setUserImage(userThumb, getContext());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ChatActivity.class);
intent.putExtra("userID", listUID);
intent.putExtra("userName", userName);
startActivity(intent);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ConversationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new ConversationViewHolder(view);
}
};
ConversationList.setAdapter(ConversationRecyclerViewAdapter);
ConversationRecyclerViewAdapter.startListening();
}
public static class ConversationViewHolder extends RecyclerView.ViewHolder {
View mView;
public ConversationViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setMassage(String message, boolean isSeen) {
TextView userStatusView = mView.findViewById(R.id.userStatus);
userStatusView.setText(message);
if (!isSeen) {
userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.BOLD);
} else {
userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.NORMAL);
}
}
public void setUserOnline(String online) {
ImageView userOnlineView = mView.findViewById(R.id.online);
if (online.equals("true")) {
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
public void setName(String userName) {
TextView userNameView = mView.findViewById(R.id.userName);
userNameView.setText(userName);
}
public void setUserImage(String userThumb, Context context) {
CircleImageView userImageView = mView.findViewById(R.id.userImage);
Picasso.get().load(userThumb).placeholder(R.drawable.defaultimage).into(userImageView);
}
}
}
Friends.java
package com.jimmytrivedi.lapitchat;
public class Friends {
public String date;
public Friends() {
}
public Friends(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
SectionPagerAdapter.java
package com.jimmytrivedi.lapitchat;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
RequestFragment requestFragment = new RequestFragment();
return requestFragment;
case 1:
ChatFragment chatFragment = new ChatFragment();
return chatFragment;
case 2:
FriendsFragment friendFragment = new FriendsFragment();
return friendFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Requests";
case 1:
return "Chats";
case 2:
return "Friends";
default:
return null;
}
}
}
MainActivity.java
package com.jimmytrivedi.lapitchat;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.login.LoginManager;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private Toolbar toolbar;
private ViewPager viewPager;
private SectionsPagerAdapter sectionsPagerAdapter;
private TabLayout tabLayout;
private DatabaseReference UserDatabaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
sendTostart();
} else {
UserDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
UserDatabaseReference.child("Online").setValue("true");
}
viewPager = findViewById(R.id.viewPager);
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
toolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
tabLayout = findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onPause() {
super.onPause();
if (currentUser != null) {
UserDatabaseReference.child("Online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendTostart() {
startActivity(new Intent(MainActivity.this, StartActivity.class));
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
sendTostart();
}
if (item.getItemId() == R.id.settings) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
if (item.getItemId() == R.id.allUsers) {
startActivity(new Intent(MainActivity.this, UsersActivity.class));
}
return true;
}
}
Use
`viewPager.setOffscreenPageLimit(3);`
after
viewPager.setAdapter(sectionsPagerAdapter);
inside MainActivity.
Use notifyDataSetChanged() after setting adapter to recyclerview.
FriendRecyclerView.setAdapter(FriendsRecyclerViewAdapter);
FriendsRecyclerViewAdapter.notifyDataSetChanged();
This question already has answers here:
database.DatabaseException: Can't convert object of type java.lang.String to type
(2 answers)
Closed 4 years ago.
I am new in Firebase, I am trying to create File Operation with Android Studio, I got stuck with this error.
My Error Code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ptpai.rekamedik, PID: 28972
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type Model.EditHasilLabModel
at com.google.android.gms.internal.zzelw.zzb(Unknown Source)
at com.google.android.gms.internal.zzelw.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.ptpai.rekamedik.HasilLab$1.onDataChange(HasilLab.java:69)
at com.google.android.gms.internal.zzegf.zza(Unknown Source)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
HasilLab.java
package com.ptpai.rekamedik;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 java.util.ArrayList;
import java.util.List;
import Helper.HasilLabAdapter;
import Model.EditHasilLabModel;
public class HasilLab extends AppCompatActivity {
FirebaseAuth mAuth, otentikasi;
FirebaseDatabase mFirebaseDatabase;
ListView listView;
List<EditHasilLabModel> list;
ProgressDialog progressDialog;
HasilLabAdapter Adapter;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hasil_lab);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
// Inisialisasi Objek Otentikasi Firebase
otentikasi = FirebaseAuth.getInstance();
//Cek jika user sudah memiliki login
if (otentikasi.getCurrentUser() == null) {
//Akhiri Sesi
finish();
//Alihkan Ke Login
startActivity(new Intent(this, Masuk.class));
}
listView = (ListView) findViewById(R.id.list1);
list = new ArrayList<>();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Sedang Memuat...");
progressDialog.show();
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(user.getUid()).child("HasilLab");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
list.clear();
for(DataSnapshot snap : dataSnapshot.getChildren()){
EditHasilLabModel EditHasilLabModel = snap.getValue(EditHasilLabModel.class);
list.add(EditHasilLabModel);
}
Adapter = new HasilLabAdapter(HasilLab.this,R.layout.hasil_lab_data_items,list);
listView.setAdapter(Adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
HasilLabAdapter.java
package Helper;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import Model.EditHasilLabModel;
import com.google.firebase.database.FirebaseDatabase;
import com.ptpai.rekamedik.R;
import java.util.List;
public class HasilLabAdapter extends ArrayAdapter<EditHasilLabModel> {
FirebaseDatabase adapterFirebase;
Activity activity;
int resource;
List<EditHasilLabModel> list;
public HasilLabAdapter(Activity activity, int resource, List<EditHasilLabModel> list) {
super(activity, resource,list);
this.activity = activity;
this.resource = resource;
this.list = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
adapterFirebase = FirebaseDatabase.getInstance();
LayoutInflater layoutInflater = activity.getLayoutInflater();
View view = layoutInflater.inflate(resource,null);
ImageView imageView = (ImageView) view.findViewById(R.id.getImages);
TextView NamaHasilLab = (TextView) view.findViewById(R.id.getNamaHasilLab);
TextView KeteranganHasilLab = (TextView) view.findViewById(R.id.getKeteranganHasilLab);
NamaHasilLab.setText(list.get(position).getNama_Hasil_Lab());
KeteranganHasilLab.setText(list.get(position).getKeterangan_Hasil_Lab());
Glide.with(activity).load(list.get(position).getImageUri()).into(imageView);
return view;
}
}
activity_hasil_lab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ptpai.rekamedik.HasilLab">
<ListView
android:id="#+id/list1"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
My EditHasilLabModel.java
package Model;
/**
* Created by dskymc on 14/03/2018.
*/
public class EditHasilLabModel {
private String Nama_Hasil_Lab;
private String Keterangan_Hasil_Lab;
private String imageUri;
public EditHasilLabModel(String Nama_Hasil_Lab, String Keterangan_Hasil_Lab, String imageUri) {
this.Nama_Hasil_Lab = Nama_Hasil_Lab;
this.Keterangan_Hasil_Lab = Keterangan_Hasil_Lab;
this.imageUri = imageUri;
}
public EditHasilLabModel() {
}
public String getNama_Hasil_Lab() {
return Nama_Hasil_Lab;
}
public void setNama_Hasil_Lab(String Nama_Hasil_Lab) {
this.Nama_Hasil_Lab = Nama_Hasil_Lab;
}
public String getKeterangan_Hasil_Lab() {
return Keterangan_Hasil_Lab;
}
public void setKeterangan_Hasil_Lab(String Keterangan_Hasil_Lab) {
this.Keterangan_Hasil_Lab = Keterangan_Hasil_Lab;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
}
Database Structure
User
userID
Hasil_Lab:
ImageUri
Keterangan_Hasil_Lab
Nama_Hasil_Lab
Please help me, I am trying to debug, I think the Adapter maybe wrong, but I don't know where is it.
Thanks for any Help really appreciated.
To make it work, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference hasilRef = rootRef.child("User").child(uid).child("HasilLab");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imageUri = dataSnapshot.child("imageUri").getValue(String.class);
String keterangan = dataSnapshot.child("keterangan_HasileLab").getValue(String.class);
String nama = dataSnapshot.child("nama_Hasil_Lab").getValue(String.class);
Log.d("TAG", imageUri + " / " + keterangan + " / " + nama);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
hasilRef.addListenerForSingleValueEvent(valueEventListener);
There is no need to use getChildren() method.
How do I refresh the data from a local database to RecyclerView when data was successfully submitted? I use the tabs on the application. 2nd-Tab functions to submit the data, and if successful, the data will be stored in localDB.
Data on localDB I will present at the 3rd-Tab.
But what happens, I have to swipe 1st-Tab, then swipe to the 2nd-Tab and then swipe to the new 3rd-Tab data on my localDB successfully displayed.
If the 2nd-Tab me to submit the data, then I swipe to 3rd-Tab, the data will not appear on the list of data.
How do I get the data directly displayed without the need to swipe to the first 1st-Tab and then to the 2nd-Tab and 3rd-Tab ???
MainActivity :
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.bertho.gmyl.fragments.EngagedFragment;
import com.bertho.gmyl.fragments.RequestFragment;
import com.bertho.gmyl.fragments.SigninFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.engine_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new SigninFragment(), "SIGN-IN");
adapter.addFrag(new EngagedFragment(), "ENGAGED ID");
adapter.addFrag(new RequestFragment(), "LOCATION");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
EngagedFragment (2nd-Tab) Form to save data
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bertho.gmyl.R;
import com.bertho.gmyl.model.Engaged;
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.bertho.gmyl.realm.RealmHelper;
public class EngagedFragment extends Fragment implements View.OnClickListener {
private static final String TAG = EngagedFragment.class.getSimpleName();
private EditText nama, email, nohp;
private Button btnSaveConnection;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private RelativeLayout mRoot;
private View rootView;
private String userId;
private TextView lblNama, lblEmail, lblNohp;
private RelativeLayout relativeLayout;
private RealmHelper realmHelper;
public EngagedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_engaged, container, false);
realmHelper = new RealmHelper(getActivity());
String appName = getResources().getString(R.string.app_name);
loadLocalDB();
nama = (EditText) rootView.findViewById(R.id.txtName);
email = (EditText) rootView.findViewById(R.id.txtEmail);
nohp = (EditText) rootView.findViewById(R.id.txtNoHp);
lblNama = (TextView) rootView.findViewById(R.id.lblNameval);
lblEmail = (TextView) rootView.findViewById(R.id.lblEmailval);
lblNohp = (TextView) rootView.findViewById(R.id.lblNohpval);
relativeLayout = (RelativeLayout) rootView.findViewById(R.id.panelLabelDetail);
btnSaveConnection = (Button) rootView.findViewById(R.id.btnEngaged);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("tbl_engaged");
mFirebaseInstance.getReference("titleapp").setValue(appName);
mFirebaseInstance.getReference("titleapp").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "TITLE UPDATED FROM FIREBASE");
String appTitle = dataSnapshot.getValue(String.class);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
Log.e(TAG, "FAILED TO READ TITLE FROM FIREBASE.", error.toException());
}
});
btnSaveConnection.setOnClickListener(this);
return rootView;
}
private void showSnack(String notify) {
mRoot = (RelativeLayout) rootView.findViewById(R.id.frag_engaged);
Snackbar snackbar = Snackbar.make(mRoot, notify, Snackbar.LENGTH_LONG);
snackbar.show();
}
public void onClick(View v) {
if(v.getId() == R.id.btnEngaged) {
String txtName = nama.getText().toString();
String txtEmail = email.getText().toString();
String txtNo = nohp.getText().toString();
if(txtName.equals("") || txtName.isEmpty()) {
showSnack("Name must filled");
nama.requestFocus();
} else if (txtEmail.equals("") || txtEmail.isEmpty()) {
showSnack("Email must filled");
email.requestFocus();
} else if (txtNo.equals("") || txtNo.isEmpty()) {
showSnack("No.HP must filled");
nohp.requestFocus();
} else {
createUser(txtName, txtEmail, txtNo);
saveToLocalDB(txtName, txtEmail, txtNo);
}
}
}
private void saveToLocalDB(String txtName, String txtEmail, String txtNo) {
realmHelper.addEngaged(txtName, txtEmail, txtNo);
}
private void loadLocalDB() {
realmHelper.getAllData();
}
private void createUser(String name, String email, String nohp) {
userId = mFirebaseDatabase.push().getKey();
Engaged user = new Engaged(name, email, nohp);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
private void addUserChangeListener() {
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Engaged user = dataSnapshot.getValue(Engaged.class);
if (user == null) {
Log.e(TAG, "ENGAGED DATA IS NULL");
return;
}
Log.e(TAG, "ENGAGED DATA IS CHANGED!" + user.name + ", " + user.email);
lblNama.setText(user.name);
lblEmail.setText(user.email);
lblNohp.setText(user.nohp);
//relativeLayout.setVisibility(View.VISIBLE);
nama.setText("");
email.setText("");
nohp.setText("");
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "FAILED TO READ USER", error.toException());
}
});
}
}
RequestFragment (3rd-Tab) To display localDB
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.bertho.gmyl.R;
import com.bertho.gmyl.adapter.AdapterEngaged;
import com.bertho.gmyl.model.ModelEngaged;
import com.bertho.gmyl.realm.RealmHelper;
import java.util.ArrayList;
public class RequestFragment extends Fragment {
private static final String TAG = "RequestFragment";
private RecyclerView recyclerView;
private View rootView;
private ArrayList<ModelEngaged> data;
private RealmHelper helper;
public RequestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_request, container, false);
data = new ArrayList<>();
helper = new RealmHelper(getActivity());
recyclerView = (RecyclerView) rootView.findViewById(R.id.rvArticle);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
setRecyclerView();
return rootView;
}
public void setRecyclerView() {
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
AdapterEngaged adapter = new AdapterEngaged(data, new AdapterEngaged.OnItemClickListener() {
#Override
public void onClick(ModelEngaged item) {
Toast.makeText(getContext(), "LIST CLICKED", Toast.LENGTH_LONG).show();
}
});
recyclerView.setAdapter(adapter);
}
#Override
public void onResume() {
super.onResume();
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
setRecyclerView();
}
}
Everything went smoothly, it's just that I hope the data can be displayed when the form is submitted and can be directly viewed on the 3rd-Tab
Try this,
Create an Interface in EngagedFragment
say,
public interface SubmitListener {
void onSubmit();
}
private SubmitListener onSubmitListener;
public void setSubmitListener(SubmitListener onSubmitListener){
this.onSubmitListener = onSubmitListener;
}
public SubmitListener getOnSubmitListener(){
return onSubmitListener;
}
In saveToLocalDB(...) method
call
onSubmitListener.onSubmit();
In MainActivity:
1) Update the below statement:
public class MainActivity extends AppCompatActivity implements EngagedFragment.SubmitListener
2) Make your ViewPagerAdapter adapter; variable as Global variable;
while adding fragment:
EngagedFragment engagedFrag = new EngagedFragment();
adapter.addFrag(engagedFrag, "ENGAGED ID");
...
viewPager.setAdapter(adapter);
3) add this after setting adapter
engagedFrag.setSubmitListener(this);
4) Override onSubmit() method and try the below code in that method
if(viewPager != null){
if(adapter != null){
Fragment fragment = adapter.getItem(2);
if(fragment != null){
RequestFragment requestFragment = (RequestFragment) fragment;
requestFragment.setRecyclerView();
}
}
}
try this
mViewPager.setOffscreenPageLimit(0);
if that doesnt help, please check below SO question:
fragment refresh On Swip
and about : mViewPager.setOffscreenPageLimit(0); this might not work as i found in one of #commonware 's answer's, the following :-
"Does ViewPager require a minimum of 1 offscreen pages
Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:
Requested offscreen page limit 0 too small; defaulting to 1"