I hope you understand the errors in my coding. I want to retrieve value from function "ambilKey()" to get the value for "hasilKey". "hasilKey" is the node of my firebase database structure.
MyPictureDatabaseFirebase:
MyPictureResultLog:
value -KkonCYNZV6BX5BmWUI not saved to variable "hasilKey". So, this code doesn't work: dbAmbilDataProduk=FirebaseDatabase.getInstance().getReference().child("DataBisnis").child(hasilKey).child("DataProduk").
public class IbuActivity extends AppCompatActivity {
private Fireb][1]aseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference mCekBisnis_Id;
private String nilaiBisnis="error";
private String hasilKey="error";
private RecyclerView mProdukList;
private DatabaseReference dbAmbilKeyPengguna;
private DatabaseReference dbAmbilDataProduk;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ibu);
Log.i("Aktivitas :","OnCreate");
mAuth=FirebaseAuth.getInstance();
cekAkunBisnis();
//Retrieve Value hasilKey is my problem
ambilKey();
//Check Value
Log.i("Result=",hasilKey);
//Not working function ambilkey() ?????
dbAmbilDataProduk=FirebaseDatabase.getInstance().getReference().child("DataBisnis").child(hasilKey).child("DataProduk");
mProdukList=(RecyclerView) findViewById(R.id.ibuRvProduk);
mProdukList.setHasFixedSize(true);
mProdukList.setLayoutManager(new LinearLayoutManager(this));
}
private void ambilKey() {
dbAmbilKeyPengguna=FirebaseDatabase.getInstance().getReference().child("DataPengguna").child(mAuth.getCurrentUser().getUid()).child("BisnisId");
dbAmbilKeyPengguna.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
hasilKey=dataSnapshot.getValue(String.class);
Log.i("ResultKeyAmbilKey=",hasilKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i("Pesan","DatabaseError");
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<AmbilDataProduk,ProdukViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<AmbilDataProduk, ProdukViewHolder>(
AmbilDataProduk.class,
R.layout.listprodukrow,
ProdukViewHolder.class,
dbAmbilDataProduk
) {
#Override
protected void populateViewHolder(ProdukViewHolder viewHolder, AmbilDataProduk model, int position) {
viewHolder.setNamaProduk(model.getNamaProduk());
viewHolder.setHargaProduk(model.getHargaProduk());
viewHolder.setFotoProduk(getApplicationContext(),model.getFotoProduk());
}
};
mProdukList.setAdapter(firebaseRecyclerAdapter);
}
public static class ProdukViewHolder extends RecyclerView.ViewHolder{
View view;
public ProdukViewHolder(View itemView) {
super(itemView);
view=itemView;
}
public void setNamaProduk(String namaProduk){
TextView buNamaProduk=(TextView) view.findViewById(R.id.prowTvNama);
buNamaProduk.setText(namaProduk);
}
public void setHargaProduk(String hargaProduk) {
TextView kelolaHargaProduk=(TextView) view.findViewById(R.id.prowTvHarga);
kelolaHargaProduk.setText("Harga : Rp."+hargaProduk);
}
public void setFotoProduk(final Context ctx, final String fotoProduk){
final ImageView imageViewFotoProduk=(ImageView) view.findViewById(R.id.prowIvFoto);
//Picasso.with(ctx).load(fotoProduk).into(imageViewFotoProduk);
Picasso.with(ctx).load(fotoProduk).networkPolicy(NetworkPolicy.OFFLINE).into(imageViewFotoProduk, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(fotoProduk).into(imageViewFotoProduk);
}
});
}
}
//Cek Akun sudah Login Jika sudah login apakah sudah terdaftar / punya bisnis
private void cekAkunBisnis() {
//CekAkunLogin
if(mAuth.getCurrentUser()!=null){
mCekBisnis_Id= FirebaseDatabase.getInstance().getReference().child("DataPengguna").child(mAuth.getCurrentUser().getUid()).child("BisnisId");
mCekBisnis_Id.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
nilaiBisnis=dataSnapshot.getValue(String.class);
//Cek sudah punya bisnis belum?
if(!nilaiBisnis.equals("belumada")){
//Sudah ada
}
else if(nilaiBisnis.equals("error")){
}
else{
//Belum ada
Intent bisnisIntent=new Intent(IbuActivity.this, BisnisActivity.class);
//Data activitynya dilupakan
bisnisIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(bisnisIntent);
Toast.makeText(IbuActivity.this, "Selamat Datang. Silahkan Isi nama Bisnis Anda", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(IbuActivity.this, "Database Error!!!", Toast.LENGTH_SHORT).show();
}
});
}
else{
//User tidak ada
Intent loginRegister=new Intent(IbuActivity.this, LoginRegister.class);
loginRegister.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginRegister);
}
}
//Membuat menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tambahproduk, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.actionTambahProduk){
startActivity(new Intent(IbuActivity.this,KelolaProduk.class));
}
return super.onOptionsItemSelected(item);
}
}
You cannot use that variable outside the onDataChange() method in the way you do. This is happening because onDataChange() is called asynchronously. This means that your method is executed before onDataChange has been called. That's why is not displaying the correct value. So in order to use that variable, you need to use it inside the onDataChange() method.
For other approach, please visit this post and this post. You'll understand for sure better how things works.
Related
does anyone here encountered when you are updating a data it duplicates the existing data visually only but when I will back and go to the activity again it shows the real data.
Data 1 and Data 2, when I delete Data 2, it will show Data 1 Data2 and Data 1. However like I said, it is just visual had to go back and go to the activity again to show the current data which is Data 1 only since Data 2 has been deleted. I have tried searching but none of them are related to my problem and I genuinely do not know if this is from the database or the card or in the recyclerview. Any help will be much appreciated.
MainActivity
public class AdminReqFormsActivity extends AppCompatActivity {
RecyclerView adminreqform_recycler;
ImageView adminreqfromfield_backbtn;
DatabaseReference databaseReference;
ArrayList<ResearchReqForm> reqFormArrayList;
AdminRequestFormAdapter adminRequestFormAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_req_forms);
adminreqform_recycler = findViewById(R.id.adminreqform_recycler);
adminreqfromfield_backbtn = findViewById(R.id.adminreqfromfield_backbtn);
databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRequest");
adminreqform_recycler.setLayoutManager(new LinearLayoutManager(this));
reqFormArrayList = new ArrayList<ResearchReqForm>();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ResearchReqForm researchReqForm = dataSnapshot.getValue(ResearchReqForm.class);
reqFormArrayList.add(researchReqForm);
}
adminRequestFormAdapter = new AdminRequestFormAdapter(AdminReqFormsActivity.this, reqFormArrayList);
adminreqform_recycler.setAdapter(adminRequestFormAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminReqFormsActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
adminreqfromfield_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
}
}
Model
public class ResearchReqForm {
String studentName;
String requestedtitle;
String requestedtags;
String requestMessage;
String requestid;
String requestStatus;
public ResearchReqForm() {
}
public ResearchReqForm(String studentName, String requestedtitle, String requestedtags, String requestMessage, String requestid, String requestStatus) {
this.studentName = studentName;
this.requestedtitle = requestedtitle;
this.requestedtags = requestedtags;
this.requestMessage = requestMessage;
this.requestid = requestid;
this.requestStatus = requestStatus;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getRequestedtitle() {
return requestedtitle;
}
public void setRequestedtitle(String requestedtitle) {
this.requestedtitle = requestedtitle;
}
public String getRequestedtags() {
return requestedtags;
}
public void setRequestedtags(String requestedtags) {
this.requestedtags = requestedtags;
}
public String getRequestMessage() {
return requestMessage;
}
public void setRequestMessage(String requestMessage) {
this.requestMessage = requestMessage;
}
public String getRequestid() {
return requestid;
}
public void setRequestid(String requestid) {
this.requestid = requestid;
}
public String getRequestStatus() {
return requestStatus;
}
public void setRequestStatus(String requestStatus) {
this.requestStatus = requestStatus;
}
}
Adapter
public class AdminRequestFormAdapter extends RecyclerView.Adapter<AdminRequestFormAdapter.AdminRequestFormViewHolder> {
Context context;
ArrayList<ResearchReqForm> requestFormArrayList;
public AdminRequestFormAdapter(Context c, ArrayList<ResearchReqForm> reqFormsList){
context = c;
requestFormArrayList = reqFormsList;
}
#NonNull
#Override
public AdminRequestFormViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminRequestFormAdapter.AdminRequestFormViewHolder(LayoutInflater.from(context).inflate(R.layout.admin_request_list,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminRequestFormViewHolder holder, final int position) {
holder.adminsudentname_reqcv.setText(requestFormArrayList.get(position).getStudentName());
holder.adminrelatedtopic_requestcv.setText(requestFormArrayList.get(position).getRequestedtitle());
holder.admintopictags_requestcv.setText(requestFormArrayList.get(position).getRequestedtags());
holder.adminbriefmessage_reqeuestcv.setText(requestFormArrayList.get(position).getRequestMessage());
holder.deleteresearch_request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Delete Request Research?");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRequest");
final String uniqueKey = requestFormArrayList.get(position).getRequestid();
databaseReference.child(uniqueKey).removeValue();
Toast.makeText(context, "Student's Request has been deleted.", Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Form Closed.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
alert.show();
}
});
holder.acceptresearch_request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Test Toast For Accept", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return requestFormArrayList.size();
}
class AdminRequestFormViewHolder extends RecyclerView.ViewHolder{
TextView adminsudentname_reqcv, adminrelatedtopic_requestcv, admintopictags_requestcv, adminbriefmessage_reqeuestcv;
Button deleteresearch_request, acceptresearch_request;
public AdminRequestFormViewHolder(#NonNull View itemView) {
super(itemView);
adminsudentname_reqcv = itemView.findViewById(R.id.adminsudentname_reqcv);
adminrelatedtopic_requestcv =itemView.findViewById(R.id.adminrelatedtopic_requestcv);
admintopictags_requestcv = itemView.findViewById(R.id.admintopictags_requestcv);
adminbriefmessage_reqeuestcv = itemView.findViewById(R.id.adminbriefmessage_reqeuestcv);
deleteresearch_request = itemView.findViewById(R.id.deleteresearch_request);
acceptresearch_request = itemView.findViewById(R.id.acceptresearch_request);
}
}
}
Yes, this is actually quite common and comes from a misunderstanding of how Firebase snapshots work.
Whenever your onDataChange is called it gets a full snapshot of all the data at databaseReference. So even if there's only one change since you rendered the data, you get called with a full snapshot of all data at databaseReference including the change. And since you add all data in snapshot to reqFormArrayList, you end up duplicating it each time onDataChange gets called.
The simplest solution is to clear reqFormArrayList inside onDataChange:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
reqFormArrayList.clear(); // this is the new line
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ResearchReqForm researchReqForm = dataSnapshot.getValue(ResearchReqForm.class);
reqFormArrayList.add(researchReqForm);
}
adminRequestFormAdapter = new AdminRequestFormAdapter(AdminReqFormsActivity.this, reqFormArrayList);
adminreqform_recycler.setAdapter(adminRequestFormAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminReqFormsActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)
I have a profile activity that user upload their profile images, user uploads 2 images ( back and front) the images are showing fine in the profile activity, but I also want to show one of this image (back or front) in another activity ( ViewHolder activity ). I have tried many things but couldn't figure out as i am only testing how firebase works, I really appreciate if someone can help me here.
Here is my profile activity where user upload images to firebase.
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView backimage;
private CircleImageView profileimage;
TextView totalscore,correctattempts,totalattempts,user_name,java_score,python_score,php_score,android_score,phone_number;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl;
String Storage_Path = "All_Image_Uploads/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference("Database_Path");
java_score=findViewById(R.id.javascore);
phone_number=findViewById(R.id.user_phonenumber);
python_score=findViewById(R.id.pythonscore);
php_score=findViewById(R.id.phpscore);
android_score =findViewById(R.id.androidscore);
backimage = findViewById(R.id.header_cover_image);
profileimage=findViewById(R.id.user_profile_photo);
totalattempts=findViewById(R.id.questionsattempted);
correctattempts=findViewById(R.id.correctattempts);
totalscore=findViewById(R.id.totalscore);
user_name =findViewById(R.id.user_profile_name);
backimage.setOnClickListener(this);
profileimage.setOnClickListener(this);
user_name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
user_name.setText(Common.currentUser.getUserName());
phone_number.setText(Common.currentUser.getEmail());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
/* String score=dataSnapshot.child(Common.currentuser.getUsername()).child("totalScore").getValue().toString();
totalscore.setText(score);
String tattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("questionsAttempted").getValue().toString();
totalattempts.setText(tattempts);
String cattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("correctAttempts").getValue().toString();
correctattempts.setText(cattempts);
phone_number.setText(Common.currentuser.getEmail());
*/
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtobackimage").getValue().toString())
.into(backimage);
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtoprofileimage").getValue().toString())
.into(profileimage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
scoretbl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Java").exists())
java_score.setText(dataSnapshot.child("Java").child("score").getValue().toString());
if(dataSnapshot.child("Python").exists())
python_score.setText(dataSnapshot.child("Python").child("score").getValue().toString());
if(dataSnapshot.child("PHP").exists())
php_score.setText(dataSnapshot.child("PHP").child("score").getValue().toString());
if(dataSnapshot.child("Android").exists())
android_score.setText(dataSnapshot.child("Android").child("score").getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST&&resultCode ==RESULT_OK
&& data !=null && data.getData()!= null){
filepath = data.getData();
if(id==R.id.header_cover_image)
Picasso.with(this).load(filepath).into(backimage);
else
Picasso.with(this).load(filepath).into(profileimage);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.header_cover_image:{
id = R.id.header_cover_image;
chooseImage();
uploadImageback();
break;
}
case R.id.user_profile_photo:{
id = R.id.user_profile_photo;
chooseImage();
uploadImageprofile();
break;
}
}
}
private void uploadImageback() {
final StorageReference backref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"back");
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading..");
progressDialog.show();
backref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
backref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtobackimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void uploadImageprofile() {
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading.. ");
progressDialog.show();
final StorageReference profileref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"profile");
profileref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
profileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtoprofileimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Profile Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Profile not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+" %");
}
});
}
}
}
and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity
public class RankingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name_text,score_text;
private ItemClickListener itemClickListener;
public RankingViewHolder(View itemView) {
super(itemView);
name_text = (TextView) itemView.findViewById(R.id.name_text);
score_text = (TextView) itemView.findViewById(R.id.score_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
and the Fragment activity
public class RankingFragment extends Fragment {
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
//Using orderByChild method , this will sort the ranking in ascending order
//reverse the data by using layout manager
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(RankingViewHolder viewHolder, final Ranking model, int position) {
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
//prevent crash when user click
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
and here is my Ranking class
public class Ranking {
private String userName;
private long score;
private String urlProfilePic;
public Ranking(){
}
public Ranking(String userName, long score, String pathtobackimage ) {
this.userName = userName;
this.score = score;
this.urlProfilePic = pathtobackimage;
}
public String getUrlProfilePic() {
return urlProfilePic;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
}
Here the screen shot to help more how I wanted
I put my comment in answer field because of this restriction: 'You must have 50 reputation to comment'.
Anyway, back to your question. One solution would be to save the current user 'key' to a SharedPreference file. In your new Activity, use that 'key' to retrieve the data from Firebase.
EDIT: Added solution
Quoted: "...and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity..."
Solution: Search for fixme. In RankingViewHolder class, add:
public class RankingViewHolder extends ...
//...
public TextView name_text, score_text;
public ImageView profileImageView; //fixme
//...
public RankingViewHolder(View itemView) {
//...
score_text = (TextView) itemView.findViewById(R.id.score_text);
profileImageView = (ImageView) itemView.findViewById(R.id.profile_image_view); //fixme
//...
Inside populateViewHolder()
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext()) //fixme
.load(Common.currentUser.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView); //fixme
Inside RankingFragment class, since you are already using Common.currentUser.getUserName(), might as well create another variable under it to store the url link to the user's profile picture, and retrieve the link via Common.currentUser.getUrlProfilePic().
EDIT#2:
The images stored in FB storage have this links:
gs://FIXME_FIREBASE.com/images/userName/userNameback.jpeg
gs://FIXME_FIREBASE.com/images/userName/userNameprofile.jpeg
However to use in Picasso, need this kind of links:
https://firebasestorage.googleapis.com/v0/b/FIXME/o/FIXME/images/userName/userNameback.jpeg?alt=media&token=FIXME
Question is how to get that?
One solution is that after you successfully upload the image, get the download url (example below).
The tricky part is that the download url is not immediately available, and you have to use .getMetadata(), .getDownloadUrl() to do that.
Once the url is received, you have to figure out how to save this link to the user's profile in your FB database.
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageMetadata storageMetadata = taskSnapshot.getMetadata();
StorageReference reference = storageMetadata.getReference();
reference.getDownloadUrl() // Get the download URL for the file
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i(TAG, uri.toString()); //fixme: save this to user's profile
}
});
}
Inside populateViewHolder, you are using Ranking model that contains the username and score.
Modify that Ranking model class to add an additional String variable urlProfilePic that contains the url to the user's image (above result), and generate the getter for it called getUrlProfilePic(). Then you can use it in this way inside the populateViewHolder:
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext())
.load(model.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView);
I'm doing a realtime tracking application from a tutorial online, Here i'm setting the presence system using firebase. But it's crashing with:
/java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
I don't understand what's wrong the guy who coded this has it working perfectly.
The exception is happening at this line :if(dataSnapshot.getValue(Boolean.class)){
When i log this on screen the datasnapshot object has a key but no value
HELP!
ListOnline Class
//firebase
DatabaseReference onlineRef,currentUserRef,counterRef;
FirebaseRecyclerAdapter<User,ListOnlineViewHolder> adapter;
//View
RecyclerView listOnline;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_online);
//setting the recyclerview
listOnline = (RecyclerView)findViewById(R.id.listOnlineRecyclerview);
listOnline.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listOnline.setLayoutManager(layoutManager);
//set toolbar and menu / join,logout
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbarID);
toolbar.setTitle("Presence System");
setSupportActionBar(toolbar);
//firebase
onlineRef = FirebaseDatabase.getInstance().getReference().child("info/connected");
counterRef = FirebaseDatabase.getInstance().getReference("lastOnline"); //create new child name lastOnline
currentUserRef = FirebaseDatabase.getInstance().getReference().child(FirebaseAuth.getInstance().getCurrentUser().getUid());
setupSystem();
//after setup we load all users and display in recyclerview
//this is online list
updateList();
}
private void updateList() {
adapter = new FirebaseRecyclerAdapter<User, ListOnlineViewHolder>(
User.class,R.layout.user_layout,ListOnlineViewHolder.class,counterRef
) {
#Override
protected void populateViewHolder(ListOnlineViewHolder viewHolder, User model, int position) {
viewHolder.emailTextView.setText(model.getEmail());
}
};
adapter.notifyDataSetChanged();
listOnline.setAdapter(adapter);
}
private void setupSystem() {
onlineRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue(Boolean.class)){
currentUserRef.onDisconnect().removeValue();
//set online user in list
counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(FirebaseAuth.getInstance().getCurrentUser().getEmail(),"Online");
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
counterRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren()){
User user = postSnapshot.getValue(User.class);
Log.d("LOG",""+user.getEmail()+"is "+user.getStatus());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_join:
counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(FirebaseAuth.getInstance().getCurrentUser().getEmail(),"Online");
break;
case R.id.action_logout:
currentUserRef.removeValue();
}
return super.onOptionsItemSelected(item);
}
}
User Class
public class User {
private String email,status;
public User(String email, String status) {
this.email = email;
this.status = status;
}
public User() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}}
MainActivity
public class MainActivity extends AppCompatActivity {
Button signInButton;
private final static int LOGIN_PERMISSION = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = (Button) findViewById(R.id.signInButton);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().setAllowNewEmailAccounts(true).build(),LOGIN_PERMISSION);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == LOGIN_PERMISSION){
startNewActivity(resultCode,data);
}
}
private void startNewActivity(int resultcode, Intent data) {
if(resultcode == RESULT_OK){
Intent intent = new Intent(MainActivity.this,ListOnline.class);
startActivity(intent);
finish();
}
else{
Toast.makeText(this,"login failed!!",Toast.LENGTH_SHORT).show();
}
}}
In your setupSystem() method, you are attaching a listener to onlineRef (the info/connected node) and then marshalling the returned value to a Boolean value.
However, DataSnapshot#getValue() will return null if there is no data at the specified location in the database. If this happens, the dataSnapshot.getValue(Boolean.class) call will create a Boolean variable with the value of null, which then cannot be checked for a true value in your current if statement (see Check if null Boolean is true results in exception).
You could check that getValue() does not return null first by adding a null-check to your if statement:
if(dataSnapshot.getValue() != null && dataSnapshot.getValue(Boolean.class)){
// ...
}
Or check that the location exists using DataSnapshot#exists():
if(dataSnapshot.exists() && dataSnapshot.getValue(Boolean.class)){
// ...
}
However, if you're trying to detect connection state, did you mean to attach the listener to the .info/connected node instead? As from the documentation:
For many presence-related features, it is useful for your app to know
when it is online or offline. Firebase Realtime Database provides a
special location at /.info/connected which is updated every time the
Firebase Realtime Database client's connection state changes. Here is
an example:
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
its null since it does not exist in the database..
onlineRef = FirebaseDatabase.getInstance().getReference().child("info/connected");
you are querying on the above location. So dataSnapshot is a snapshot of the above..
if(dataSnapshot.getValue(Boolean.class)){
This does not exist in the database.. Thus you get that error
It seems that you do not have a value in database. This will handle the error
if(dataSnapshot.getValue(Boolean.class) != null && dataSnapshot.getValue(Boolean.class)){
I want to show Firebase data filtered by userID. But the app crashes and after debugging it shows a NullPointerException on the Firebase adapter. What to do? I am implementing it in fragment. I am not pasting the imported libraries.
Here is my code:
public class MyPosts extends Fragment{
private RecyclerView postList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseAppriciate;
private DatabaseReference mDatabaseDisgrace;
private LinearLayoutManager layoutManager;
private FirebaseAuth mAuth= FirebaseAuth.getInstance();
private DatabaseReference mDatabaseCurrentUser;
public Query mQueryCurrentUser=null;
//private static final String TAG = "MyActivity";
private boolean mProcessAppriciate=false;
private boolean mProcessDisgrace=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
View rootView = inflater.inflate(R.layout.allposts, container, false);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mDatabase.keepSynced(true);
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
//EXPERIMENT WITH LISTVIEW STARTS
postList=(RecyclerView) rootView.findViewById(R.id.postList);
postList.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
postList.setHasFixedSize(true);
postList.setLayoutManager(layoutManager);
postList.getRecycledViewPool().clear();
//EXPERIMENT WITH LISTVIEW ENDS
return rootView;
}
#Override
public void onStart() {
super.onStart();
//EXP CODE STARTS
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
mDatabaseCurrentUser=FirebaseDatabase.getInstance().getReference().child("Posts");
String currentUserId=user.getUid();
mQueryCurrentUser=mDatabaseCurrentUser.orderByChild("uid").equalTo(currentUserId);
}else{
}
}
});
//EXP CODE ENDS
FirebaseRecyclerAdapter<Posts,PostViewHolder> firebaseRecyclerAdapter= new FirebaseRecyclerAdapter<Posts,PostViewHolder>(
Posts.class,
R.layout.single_post,
PostViewHolder.class,
mQueryCurrentUser
) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Posts model, final int position) {
final String post_key=getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDescription(model.getDescription());
viewHolder.setProfileName(model.getProfilename());
viewHolder.setImage(getContext(),model.getImage());
viewHolder.getLayoutPosition();
viewHolder.setAppriciateButton(post_key);
viewHolder.setDisgraceButton(post_key);
//Share click code below
viewHolder.Share.setOnClickListener(new View.OnClickListener() {
CallbackManager callbackManager;
ShareDialog shareDialog;
#Override
public void onClick(View v) {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(MyPosts.this);
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentTitle(model.getTitle())
.setContentDescription(model.getDescription())
.setImageUrl(Uri.parse(model.getImage()))
.setContentUrl(Uri.parse("https://developers.facebook.com"))
.build();
shareDialog.show(content);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
}
});
//Share click code ends above
//Appriciate button on click event below
viewHolder.Appriciate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessAppriciate=true;
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessAppriciate) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessAppriciate = false;
}else {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessAppriciate = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Appriciate button click event CODE ENDS
//Disgrace Button Click Event Code Starts
viewHolder.Disgrace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessDisgrace=true;
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessDisgrace) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessDisgrace = false;
} else {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessDisgrace = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Disgrace Button Click code Ends
}
};
postList.setAdapter(firebaseRecyclerAdapter);
//test code
firebaseRecyclerAdapter.notifyDataSetChanged();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
View mView;
Button Appriciate;
Button Disgrace;
Button Share;
DatabaseReference mDatabaseAppriciate;
DatabaseReference mDatabaseDisgrace;
FirebaseAuth mAuth;
public PostViewHolder(View itemView) {
super(itemView);
mView=itemView;
Appriciate=(Button) mView.findViewById(R.id.appriciate);
Disgrace=(Button) mView.findViewById(R.id.disgraceful);
Share=(Button) mView.findViewById(R.id.share);
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mAuth=FirebaseAuth.getInstance();
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
}
public void setAppriciateButton(final String post_key){
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Appriciate.setBackgroundColor(Color.GRAY);
Appriciate.setText("Appriciated");
}else{
Appriciate.setBackgroundColor(Color.GREEN);
Appriciate.setText("APPRICIATE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE BELOW
public void setDisgraceButton(final String post_key){
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Disgrace.setBackgroundColor(Color.GRAY);
Disgrace.setText("Disgraced");
}else{
Disgrace.setBackgroundColor(Color.RED);
Disgrace.setText("DISGRACE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE ENDS
//Setting the title to the AllActivity
public void setTitle(String title){
TextView postTitle=(TextView) mView.findViewById(R.id.allPostTitle);
postTitle.setText(title);
}
public void setDescription(String description){
TextView postDescription=(TextView) mView.findViewById(R.id.allPostDescription);
postDescription.setText(description);
}
//PROFILE NAME EXPERIMENT
public void setProfileName(String profilename){
TextView postName=(TextView) mView.findViewById(R.id.profileName);
postName.setText(profilename);
}
public void setImage(final Context context, final String image) {
final ImageView postImage=(ImageView) mView.findViewById(R.id.allPostImage);
with(context).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(postImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(context).load(image).resize(500,700).into(postImage);
}
});
}
//THREADING EXPERIMENT CODE
}
}