Everytime I have to change something to reflect [closed] - java

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();

Related

ThreeFragment should reload 1 times to show the RecyclerView,Asynchronus task

I have ViewPager TabLayout which hosts 3 Fragments. Each Fragment contain ListView and data from Firebase. FragmentOne and FragmentTwo running with no problem,The problem isin FragmentThree raises blank screen. But after i reload FragmentThree 1 times like on this video the data and RecyclerView just appeared
https://streamable.com/zh861
MainActivity.java
package com.example.yehezkiel.eclassapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
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.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<MataKuliah> listMatkul = new ArrayList<>();
private ArrayList<String> keys = new ArrayList<>();
private myAdapter myAdapter;
private Button logoutBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener authListener;
private RecyclerView mRecycleView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private NavigationView mNavigationView;
private TextView mTextName;
private TextView mTextNim;
static {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
FirebaseUser users = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mataKuliahRef = FirebaseDatabase.getInstance().getReference("courses");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mAuth = FirebaseAuth.getInstance();
//Navbar menu
mToolbar = (Toolbar) findViewById(R.id.navbaraction);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawabel_main);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
View header = mNavigationView.getHeaderView(0);
mTextName = (TextView) header.findViewById(R.id.header_name);
mTextNim = (TextView) header.findViewById(R.id.header_nim);
//Tab Layout
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case (R.id.tugas):
break;
case (R.id.logout_menu):
signOut();
break;
}
return true;
}
});
userRef.child(users.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue().toString();
String nim = (String) dataSnapshot.child("nim").getValue().toString();
mTextNim.setText(nim);
mTextName.setText(name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Beranda");
adapter.addFragment(new TwoFragment(), "Tugas");
adapter.addFragment(new ThreeFragment(), "Pengumuman");
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void signOut() {
mAuth.signOut();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(authListener);
}
}
ThreeFragment.java
package com.example.yehezkiel.eclassapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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 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.HashMap;
import java.util.List;
public class ThreeFragment extends Fragment {
View v;
private List<DaftarPengumuman> listPengumuman = new ArrayList<>();
private ArrayList<String> obj3 = new ArrayList<>();
List<ListItem> consolidatedList = new ArrayList<>();
private RecyclerView mRecyclerView;
private RecyclerView.Adapter adapter;
private FirebaseAuth mAuth;
private DatabaseReference userRef;
private FirebaseUser users;
private DatabaseReference mataKuliahRef;
private DatabaseReference daftarPengumumanRef;
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_three, container, false);
userRef = FirebaseDatabase.getInstance().getReference("users");
users = FirebaseAuth.getInstance().getCurrentUser();
mataKuliahRef = FirebaseDatabase.getInstance().getReference("courses");
daftarPengumumanRef = FirebaseDatabase.getInstance().getReference("pengumuman");
mAuth = FirebaseAuth.getInstance();
mRecyclerView = (RecyclerView) v.findViewById(R.id.PengumumanRView);
mRecyclerView.setHasFixedSize(true);
adapter = new PengumumanAdapter(getActivity().getApplicationContext(), consolidatedList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(adapter);
userRef.child(users.getUid()).child("courses").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
obj3.clear();
if(dataSnapshot.exists()){
long datacount = dataSnapshot.getChildrenCount();
int i = 0;
for(DataSnapshot dataHasil : dataSnapshot.getChildren()){
final String idCourse = dataHasil.getKey();
obj3.add(idCourse);
Log.e("anjay",obj3.toString());
if(datacount-1 == i){
queryObj3();
}
i++;
}
}else {
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
HashMap<String, List<DaftarPengumuman>> groupedHashMap = groupDataIntoHashMap(listPengumuman);
for (String nama_p : groupedHashMap.keySet()) {
PengumumanItem nameItem = new PengumumanItem();
nameItem.setNama_matkul(nama_p);
consolidatedList.add(nameItem);
for (DaftarPengumuman daftarPengumuman : groupedHashMap.get(nama_p)) {
GeneralItem generalItem = new GeneralItem();
generalItem.setDaftarPengumuman(daftarPengumuman);//setBookingDataTabs(bookingDataTabs);
consolidatedList.add(generalItem);
}
}
return v;
}
public void queryObj3(){
for(int j = 0 ; j<obj3.size() ;j++){
mataKuliahRef.child(obj3.get(j)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("pengumuman")) {
final String name = (String) dataSnapshot.child("name").getValue();
for (DataSnapshot idKeyPeng : dataSnapshot.child("pengumuman").getChildren()) {
daftarPengumumanRef.child(idKeyPeng.getKey()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot2) {
DaftarPengumuman pengumuman = new DaftarPengumuman();
pengumuman = dataSnapshot2.getValue(DaftarPengumuman.class);
pengumuman.setNama_p(name);
listPengumuman.add(pengumuman);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private HashMap<String, List<DaftarPengumuman>> groupDataIntoHashMap(List<DaftarPengumuman> listOfDaftarPengumuman) {
HashMap<String, List<DaftarPengumuman>> groupedHashMap = new HashMap<>();
for (DaftarPengumuman daftarPengumuman : listOfDaftarPengumuman) {
String hashMapKey = daftarPengumuman.getNama_p();
if (groupedHashMap.containsKey(hashMapKey)) {
// The key is already in the HashMap; add the pojo object
// against the existing key.
groupedHashMap.get(hashMapKey).add(daftarPengumuman);
} else {
// The key is not there in the HashMap; create a new key-value pair
List<DaftarPengumuman> list = new ArrayList<>();
list.add(daftarPengumuman);
groupedHashMap.put(hashMapKey, list);
}
}
return groupedHashMap;
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawabel_main"
tools:context="com.example.yehezkiel.eclassapp.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
layout="#layout/navbar_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"></include>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navbar_main"
android:layout_gravity="start"
app:headerLayout="#layout/navbar_header"
android:id="#+id/nav_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

How to remove Card View from Recycler View, from a separate Activity

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

RecyclerView strange adapter and rows behaviour

My RecyclerView have two problems :
The first problem is when i am finished working with its activity and press back button it creates the same activity again but after removing some row (Mostly from the end) ,, I don't know if the problem is it creates the view on multiple phases or what .
The second problem is when i press some button(Like button for example) it recreates the activity with the new result at each time it is pressed .
here is my Adapter
package com.example.agh.grad.Adapters;
import android.Manifest; import android.app.Activity; import
android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; 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 com.example.agh.grad.ItemClickListner; import com.example.agh.grad.Models.Services; import com.example.agh.grad.R; import com.example.agh.grad.SearchServices; import com.example.agh.grad.ServiceDetail; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.parceler.Parcels; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by cz on 17/06/17. */ public class recylerServiceAdapter extends RecyclerView.Adapter<recylerServiceAdapter.ViewHolder> { ArrayList<Services> service; Context context; ItemClickListner clickListner; public recylerServiceAdapter(ArrayList<Services> service, Context context) { this.service = service; this.context = context; } #Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recyler_services, parent, false); ViewHolder viewHolder = new ViewHolder(v); context= parent.getContext(); return viewHolder; }
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.tvServiceName.setText(service.get(position).getName());
holder.tvServiceDisrption.setText(service.get(position).getServiceShortDesrption());
holder.tvServiceProvider.setText(service.get(position).getServiceProvider());
holder.tvLikeCounter.setText(String.valueOf(service.get(position).getLikes()));
holder.tvDislikeCounter.setText(String.valueOf(service.get(position).getDislikes()));
holder.tvLocationDescrption.setText(service.get(position).getLocationAddress());
holder.tvServiceName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* Intent myIntent= new Intent(context,SearchServices.class);
context.startActivity(myIntent);*/
}
});
holder.btnLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firedatabase.getReference("Services");
DatabaseReference wantedService = ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
final Long uplikes= service.get(holder.getAdapterPosition()).getLikes()+1;
wantedService.child("likes").setValue(uplikes, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
holder.tvLikeCounter.setText(String.valueOf(uplikes));
}
});
// TODO: 11/10/17 update on the database
//// TODO: 05/12/17 Check state of buttons and act upon it
holder.btnLike.setClickable(false);//// TODO: 05/12/17 set a clicked icon
holder.btnDislike.setClickable(false);
}
});
holder.btnDislike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firedatabase.getReference("Services");
DatabaseReference wantedService = ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
final Long dislikes= service.get(holder.getAdapterPosition()).getLikes()-1;
wantedService.child("likes").setValue(dislikes, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
holder.tvLikeCounter.setText(String.valueOf(dislikes));
}
});
}
});
holder.btnCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + service.get(holder.getAdapterPosition()).getPhoneNumber()));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Ask for permission
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
context.startActivity(callIntent);
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent= new Intent(context,ServiceDetail.class);
myIntent.putExtra(SearchServices.PARCELER_TAG, Parcels.wrap(service.get(holder.getAdapterPosition()) ));
context.startActivity(myIntent);
((Activity)context).finish();
}
});
}
#Override
public int getItemCount() {
return service.size();
}
public void setClickListener(ItemClickListner itemClickListener) {
this.clickListner = itemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView (R.id.serviceName) TextView tvServiceName;
#BindView (R.id.serviceProvider)TextView tvServiceProvider;
#BindView (R.id.serviceShortDescrption)TextView tvServiceDisrption;
#BindView (R.id.tvLikeCounter)TextView tvLikeCounter;
#BindView (R.id.tvDislikeCounter)TextView tvDislikeCounter ;
#BindView (R.id.locationDescrption)TextView tvLocationDescrption;
#BindView (R.id.btnLike) Button btnLike;
#BindView (R.id.btnDislike) Button btnDislike;
#BindView (R.id.btnCall) Button btnCall;
#BindView (R.id.serviceCard) CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setTag(itemView);
ButterKnife.bind(this, itemView);
}
}
}
and here is my activity
public class MainActivity extends AppCompatActivity {
List<String> arrayServices = new ArrayList<>();
RecyclerView recyclerViewServices;
recylerServiceAdapter recylerServiceAdapter;
ArrayList<Services> newServices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = this.getIntent();
// arrayServices= intent.getStringArrayListExtra("newServices");
// System.out.println(arrayServices.size());
newServices = Parcels.unwrap(intent.getParcelableExtra(SearchServices.PARCELER_TAG)) ;
Log.e( "onCreate: ",newServices.toString() );
recyclerViewServices = (RecyclerView) findViewById(R.id.recylerViewServiceDetail);
recyclerViewServices.setLayoutManager(new LinearLayoutManager(this));
recylerServiceAdapter = new recylerServiceAdapter(newServices, getApplicationContext());
recyclerViewServices.setAdapter(recylerServiceAdapter);
}
}
and my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:background="#color/lightPrimary"
tools:context="com.example.agh.grad.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recylerViewServiceDetail"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="5dp"
tools:layout_editor_absoluteY="5dp" />
</RelativeLayout>
instead of using this
holder.tvServiceName.setText(service.get(position).getName());
use
holder.tvServiceName.setText(service.get(getAdapterPosition())
.getName());
Instead of using this in onClick
holder.getAdapterPosition()
use
public void onBindViewHolder(final ViewHolder holder,final int position)
position
Changing activity launch mode to android:launchMode="singleTask" solved the problem

how to open link when user click on Text ( Click Here To See Full Topic )?

I develop (NEWS Android app) with android studio and I have a problem, I Post a Short topic in the app and I need to let the user see the full topic when clicks on TextView (Click Here), but I need to change the site link on every topic. Anyone can help me, please ??
I Update the news through (Firebase Database and Online Database)
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class Home extends AppCompatActivity {
RequestQueue requestQueue;
String url = "https://mobarmejlebanon.000webhostapp.com/show.php";
TextView textView;
ListView listview;
ArrayList<listitme> listitmes = new ArrayList<listitme>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
textView = (TextView) findViewById(R.id.textView);
listview = (ListView) findViewById(R.id.listview);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("allstudents");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String info = respons.getString("info");
String img = respons.getString("img");
listitmes.add(new listitme(id, name, info, img));
listAllItme();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
listAdpter lA = new listAdpter(listitmes);
listview.setAdapter(lA);
}
class listAdpter extends BaseAdapter {
ArrayList<listitme> listA = new ArrayList<listitme>();
public listAdpter(ArrayList<listitme> listA) {
this.listA = listA;
}
#Override
public int getCount() {
return listA.size();
}
#Override
public Object getItem(int position) {
return listA.get(position).id;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item, null);
TextView id = (TextView) view.findViewById(R.id.textView_id);
TextView name = (TextView) view.findViewById(R.id.textView_name);
TextView info = (TextView) view.findViewById(R.id.textView_info);
ImageView img = (ImageView) view.findViewById(R.id.image);
id.setText(listA.get(position).id);
name.setText(listA.get(position).name);
info.setText(listA.get(position).info);
Picasso.with(Home.this).load("https://mobarmejlebanon.000webhostapp.com/images/" + listA.get(position).img).into(img);
return view;
}
}
}
Here is the Firebase database code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
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;
public class Topic2 extends AppCompatActivity {
TextView TopicTitle,Topic;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference mRootReference = firebaseDatabase.getReference();
DatabaseReference mKidRefernece = firebaseDatabase.getReference("topictwotitle");
DatabaseReference mChildReference = mRootReference.child("topictwomessage");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic2);
TopicTitle = (TextView) findViewById(R.id.twotitle);
Topic = (TextView) findViewById(R.id.twomsg);
TopicTitle.setText("Please Wait");
Topic.setText("Loading");
}
#Override
protected void onStart() {
super.onStart();
mChildReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.getValue(String.class);
Topic.setText(message);
mKidRefernece.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String topictitle = dataSnapshot.getValue(String.class);
TopicTitle.setText(topictitle);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I suggest you to use CardView and RecyclerView in order to achieve your purpose. You can get a better insight of it here:
Also you can catch a glimpse of it in action here and hither.
EDIT
According to the new query regarding this question; I think you must catch up this How to get a text after clicking on the CardView.
Happy Coding...
EDIT
Here is your sample:
I added dummy right now.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<TopicDTO> topics = new ArrayList<>();
for (int i = 0; i < 10; i++) {
topics.add(new TopicDTO("" + i, "Topic " + (i + 1), "Your Topic info goes here", "Your Topic Image goes here", "http://www.google.com"));
}
ListView listTopics = (ListView) findViewById(R.id.listTopics);
listTopics.setAdapter(new TopicsListAdapter(MainActivity.this, topics));
}
}
TopicsListAdapter.java
public class TopicsListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<TopicDTO> mData;
public TopicsListAdapter(Context context, ArrayList<TopicDTO> data) {
mInflater = LayoutInflater.from(context);
mData = data;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ChildViewHolder holder;
if (convertView == null) {
holder = new ChildViewHolder();
convertView = mInflater.inflate(R.layout.row_topics, parent,
false);
holder.textTopicTitle = (TextView) convertView
.findViewById(R.id.textTopicTitle);
holder.textTopicInfo = (TextView) convertView
.findViewById(R.id.textTopicInfo);
holder.textTopicLink = (TextView) convertView
.findViewById(R.id.textTopicLink);
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
}
final TopicDTO mItem = mData.get(position);
holder.textTopicTitle.setText(mItem.name);
holder.textTopicInfo.setText(mItem.info);
/*You need to have a more info link per topic*/
holder.textTopicLink.setClickable(true);
holder.textTopicLink.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='" + mItem.moreInfoLink + "'> Click here to see full topic </a>";
holder.textTopicLink.setText(Html.fromHtml(text));
return convertView;
}
class ChildViewHolder {
TextView textTopicTitle, textTopicInfo, textTopicLink;
}
}
row_topics.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textTopicTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textTopicInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" />
</LinearLayout>
</LinearLayout>
<!--You need to add extra TextView in your row file of listview.
It will work as a link per topic.-->
<TextView
android:id="#+id/textTopicLink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:text="Click here to see full topic" />
</LinearLayout>
Read each comment carefully and then implement it. That's it. Nothing can be better than this.
OLD
You need to have a textView for each topic you have.You have something like listview or recyclerview. Then when user clicks on that textView open link associated with that topic only that is from your dataset of listview.
Try this on your textview on which you want to open a link :
info.setClickable(true);
info.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
info.setText(Html.fromHtml(text));
Replace "http://www.google.com" with your topic's link.

How to refresh RecyclerView in one fragment when data changed in another fragment

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"

Categories

Resources