I'm using fragement actitivty ,but context error
Picasso.get(activity)
this line activity error
public void setdetails(FragmentActivity activity, String sitename, String sitelink, final String imageuri) {
TextView District = (TextView) mview.findViewById(R.id.txtsitename);
final ImageView imageView = (ImageView) mview.findViewById(R.id.imgsiteimage);
Picasso.get(activity).load(imageuri).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(imageuri).placeholder(R.drawable.loadbar).into(imageView);
}
});
Remove activity from get() like this.
Picasso.get().load(imageuri).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback()
This will fix your problem.
Replace activity with context like this
File file = new File(filePath);
Picasso.with(context).load(file).placeholder(R.drawable.draw_detailed_view_display).error(R.drawable.draw_detailed_view_display)
.resize(400, 400).into(mImageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
mImageView.setVisibility(View.GONE);
}
});
Related
So I have a app where I am displaying the products list from the database using a Recycler View.
There is delete button beside each item which is working fine.
And there is a scan item button which opens a BARCODE SCANNER which on succesfull scanning adds the new product to the database and goes back to the Recycler View display is supposed to refresh the view and display the new Item.
but I am having problem with refreshing the recycler view on adding a new Product.
there is also a delete product function which works perfectly so I tried to do the add item method the same way, but the recycler view doesn't refresh.
UserPage activity
public class UserPage extends AppCompatActivity implements ProductAdaptar.clickedItem {
Toolbar toolbar;
RecyclerView recyclerView;
String rfidNo;
public static String barcode;
Button scanItem;
Button payBill;
TextView total;
ProductAdaptar productAdaptar;
Call<List<UserLoginResp>> productList;
List<UserLoginResp> productListsItems = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_page);
toolbar=findViewById(R.id.toolbar);
recyclerView=findViewById(R.id.recyclerview);
scanItem = findViewById(R.id.scanItem);
payBill = findViewById(R.id.payBill);
total = findViewById(R.id.total);
scanItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),ScannerView.class).putExtra("rfid",rfidNo));
}
});
payBill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkout();
}
});
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
productAdaptar = new ProductAdaptar(this::clickedItem, this);
Intent intent =getIntent();
if(intent.getExtras()!=null){
rfidNo= intent.getStringExtra("rfid");
}
getAllProducts(rfidNo);
}
public void getAllProducts(String rfidno){
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
productAdaptar = new ProductAdaptar(this::clickedItem,this);
productList= ApiClient.getUserPageService().getCartItems(rfidno);
productList.enqueue(new Callback<List<UserLoginResp>>() {
#Override
public void onResponse(Call<List<UserLoginResp>> call, Response<List<UserLoginResp>> response) {
if (response.isSuccessful()) {
productListsItems = response.body();
productAdaptar.setData(productListsItems);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setAdapter(productAdaptar);
getTotal();
}
}
#Override
public void onFailure(Call<List<UserLoginResp>> call, Throwable t) {
Log.e("listfailed",t.getLocalizedMessage());
}
});
}
public void getTotal(){
Call<getBill> bill = ApiClient.getUserPageService().getBill(rfidNo);
bill.enqueue(new Callback<getBill>() {
#Override
public void onResponse(Call<getBill> call, Response<getBill> response) {
if(response.isSuccessful()){
getBill getBill = response.body();
String bill = String.valueOf(getBill.getBill());
total.setText(bill);
}
}
#Override
public void onFailure(Call<getBill> call, Throwable t) {
Log.e("bill error",""+t);
}
});
}
public void checkout(){
Call<String> payment= APIClientString.getUserPageService().checkout(rfidNo);
payment.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
getAllProducts(rfidNo);
Toast.makeText(UserPage.this, "Payment Successful", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("paymentfail",""+t);
}
});
}
#Override
public void clickedItem(UserLoginResp userLoginResp) {
Log.e("clicked prodcut", userLoginResp.toString());
}
}
ScannerView Class
enter #Override
public void handleResult(Result rawResult) {
barcode = rawResult.getText();
if(addItem(barcode,rfidNo)) {
userPage.getAllProducts(rfidNo);
}
onBackPressed();
}
public boolean addItem(String barcode,String rfidNo){
final boolean[] res = {false};
Call<String> resp = APIClientString.getUserPageService().addProduct(barcode,rfidNo);
resp.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(ScannerView.this, response.body().toString(), Toast.LENGTH_SHORT).show();
res[0] =true;
}
}
This is the scanner class which is suppose to call the call the getAllproducts function from the UserPage Activity to refresh the view. It shows no error but the recycler view doesn't get updated.
This is the Adapter Class
public class ProductAdaptar extends RecyclerView.Adapter<ProductAdaptar.ProductAdaptarVH> {
private List<UserLoginResp> productListItems;
private UserPage context;
private clickedItem clickedItem;
public ProductAdaptar(clickedItem clickedItem, UserPage activity) {
this.clickedItem = clickedItem;
this.context= activity;
}
public void setData(List<UserLoginResp> productListItems) {
this.productListItems = productListItems;
notifyDataSetChanged();
}
#NonNull
#Override
public ProductAdaptarVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ProductAdaptar.ProductAdaptarVH(LayoutInflater.
from(context).inflate(R.layout.row_products,parent,false));
}
#Override
public void onBindViewHolder(#NonNull ProductAdaptarVH holder, int position) {
UserLoginResp userLoginResp = productListItems.get(position);
String pName = userLoginResp.getProductName();
String pQuan = userLoginResp.getQuantity();
String pPrice = userLoginResp.getProductPrice();
String pBarcode = userLoginResp.getProductID();
String userID = userLoginResp.getUserID();
holder.pName.setText(pName);
holder.pQuan.setText(pQuan);
holder.pPrice.setText(pPrice);
holder.delProdcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delProduct(userID,pBarcode);
}
});
holder.moreDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public interface clickedItem{
public void clickedItem(UserLoginResp userLoginResp);
}
public void delProduct(String userID, String pBarcode){
Call<String> res = APIClientString.getUserPageService().deleteProduct(pBarcode,userID);
res.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(context, response.body().toString(), Toast.LENGTH_SHORT).show();
context.getAllProducts(userID);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("deletefailed",""+t);
}
});
}
#Override
public int getItemCount() {
return productListItems.size();
}
public static class ProductAdaptarVH extends RecyclerView.ViewHolder {
TextView pName;
TextView pQuan;
TextView pPrice;
Button delProdcut;
Button moreDetails;
public ProductAdaptarVH(#NonNull View itemView) {
super(itemView);
pName=itemView.findViewById(R.id.pName);
pQuan=itemView.findViewById(R.id.pQuantity);
pPrice=itemView.findViewById(R.id.pPrice);
delProdcut=itemView.findViewById(R.id.delProduct);
moreDetails=itemView.findViewById(R.id.moreDetails);
}
}
}
In this Product Apdapter there is a delete product item function
holder.delProdcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delProduct(userID,pBarcode);
}
});
public void delProduct(String userID, String pBarcode){
Call<String> res = APIClientString.getUserPageService().deleteProduct(pBarcode,userID);
res.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(context, response.body().toString(), Toast.LENGTH_SHORT).show();
context.getAllProducts(userID);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("deletefailed",""+t);
}
});
}
Which also calls the getProduts function from UserPage activity and it works perfectly fine but the AddItem function doesn't refresh the view.
The Retrofit APIs are working completly fine too, the problem is only with refreshing the recycler view display on Item Add.
I am new to android coding so I can't seem to understand how to do it.
As you are refreshing your adapter using getAllProducts() method but it is being called in onCreate(). Now whenever you start a ScannerView activity, UserPage activity gets paused and then started (not created) when ScannerView activity finishes. So, you should call getAllProducts() in onStart() method like this:
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
if (intent.getExtras() != null) {
rfidNo = intent.getStringExtra("rfid");
}
getAllProducts(rfidNo);
}
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 want to show Unity banner ads (Unity ads 3.0.0) for my Java Android app.
I have read https://unityads.unity3d.com/help/android/integration-guide-android
According to the guide lines the following code has to be added to get banner ads.
public class UnityBannerExample extends Activity {
private View bannerView;
private Button bannerButton;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.unityads_example_layout);
final Activity myActivity = this;
final IUnityBannerListener unityBannerListener = new UnityBannerListener ();
final IUnityMonetizationListener unityMonetizationListener = new UnityMonetizationListener ();
UnityBanners.setBannerListener (unityBannerListener);
bannerButton = (Button) findViewById (R.id.unityads_example_banner_button);
bannerButton.setEnabled (true);
bannerButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick (View v) {
if (bannerView == null) {
UnityBanners.loadBanner (myActivity, "banner");
} else {
UnityBanners.destroy ();
}
}
});
final Button initializeButton = (Button) findViewById (R.id.unityads_example_initialize_button);
initializeButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
UnityMonetization.initialize (myActivity, "1234567", unityMonetizationListener, true);
}
});
}
private class UnityBannerListener implements IUnityBannerListener {
#Override
public void onUnityBannerLoaded (String placementId, View view) {
bannerView = view;
((ViewGroup) findViewById (R.id.unityads_example_layout_root)).addView (view);
}
#Override
public void onUnityBannerUnloaded (String placementId) {
bannerView = null;
}
#Override
public void onUnityBannerShow (String placementId) {
}
#Override
public void onUnityBannerClick (String placementId) {
}
#Override
public void onUnityBannerHide (String placementId) {
}
#Override
public void onUnityBannerError (String message) {
}
}
private class UnityMonetizationListener implements IUnityMonetizationListener {
#Override
public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
}
#Override
public void onPlacementContentStateChange (String placementId, PlacementContent placementContent, UnityMonetization.PlacementContentState previousState, UnityMonetization.PlacementContentState newState) {
}
#Override
public void onUnityServicesError (UnityServices.UnityServicesError error, String message) {
}
}
}
There are two buttons bannerButton and initializeButton.
But I don't want to show buttons to the user to initialize and show the banner ad. I want to show the ads in the on start method of the activity.
What is the proper way to show the banner ads without bannerButton and initializeButton.
You can just use OnResume method of your activity:
#Override
protected void onResume() {
....
....
UnityMonetization.initialize (myActivity, "1234567", unityMonetizationListener, true);
if (bannerView != null) {
UnityBanners.destroy ();
}
UnityBanners.loadBanner (myActivity, "banner");
}
But it is not the end. You should also take care about Banner visibility and refresh.
#Override
public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
UnityBanners.loadBanner (myActivity, "banner");
}
I have an Activity in which I load bitmaps in a ScrollGalleryView using Picasso.
When I exit from that activity and enter again the memory is not emptied and an OutOfMemory error is thrown.
I tried using .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) in Picasso but the images are still loaded and kept in memory.
I also tried to recycle the bitmaps when the back button is pressed but I still had no luck.
This is the code i'm using:
//Method called in the onCreate that loads the photo in the scrollGalleryView:
private void loadPhotos() {
savedImages = new ArrayList<Uri>();
File file = new File(getPhotoDirectory());
File[] files = file.listFiles();
if (files != null) {
for (File f : files) { // loop and print all file
savedImages.add(Uri.fromFile(f));
}
}
if (!savedImages.isEmpty()) {
for (final Uri savedImage : savedImages) {
if (savedImage.getLastPathSegment().contains(radiatorId)) {
scrollGalleryView.setVisibility(View.VISIBLE);
RadiatorSettingsMediaLoader mMediaLoader = new RadiatorSettingsMediaLoader(savedImage);
scrollGalleryView.addMedia(MediaInfo.mediaLoader(mMediaLoader));
}
}
}
}
class RadiatorSettingsMediaLoader implements MediaLoader {
Uri savedImage;
public RadiatorSettingsMediaLoader(Uri savedImage) {
this.savedImage = savedImage;
}
#Override
public boolean isImage() {
return true;
}
#Override
public void loadMedia(final Context context, final ImageView imageView,
final MediaLoader.SuccessCallback callback) {
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public ViewTreeObserver.OnGlobalLayoutListener getLayoutListener() {
return this;
}
#Override
public void onGlobalLayout() {
Picasso.with(getApplicationContext()).load(savedImage)
.resize(imageView.getWidth(), (imageView.getHeight()) - 175)
.centerInside()
.placeholder(imageView.getDrawable())
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
callback.onSuccess();
imageView.setPadding(0, 0, 0, 175);
imageView.getViewTreeObserver().removeOnGlobalLayoutListener(getLayoutListener());
Picasso.with(getApplicationContext()).invalidate(new File(savedImage.getPath()));
}
#Override
public void onError() {
Toast.makeText(context, "non sono riuscito a caricare l'immagine", Toast.LENGTH_SHORT).show();
imageView.getViewTreeObserver().removeOnGlobalLayoutListener(getLayoutListener());
loadMedia(context, imageView, callback);
}
});
imageViewsToClear.add(imageView);
}
});
}
#Override
public void loadThumbnail(final Context context, final ImageView thumbnailView,
final MediaLoader.SuccessCallback callback) {
thumbnailView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public ViewTreeObserver.OnGlobalLayoutListener getLayoutListener() {
return this;
}
#Override
public void onGlobalLayout() {
Picasso.with(context)
.load(savedImage)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(thumbnailView, new Callback() {
#Override
public void onSuccess() {
callback.onSuccess();
thumbnailView.setLongClickable(true);
thumbnailView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(RadiatorSettingsActivity.this);
builder.setTitle(R.string.safe_delete_photo_title).setMessage(R.string.safe_delete_photo_text);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File fdelete = new File(savedImage.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
deleteFileFromMediaStore(getContentResolver(), fdelete);
System.out.println("file Deleted ");
finish();
startActivity(getIntent().putExtra("PhotoRemoved", true));
} else {
System.out.println("file not Deleted :");
}
}
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
return true;
}
});
thumbnailView.getViewTreeObserver()
.removeOnGlobalLayoutListener(getLayoutListener());
}
#Override
public void onError() {
Toast.makeText(context, "errore a caricare thumbnail", Toast.LENGTH_SHORT).show();
loadThumbnail(context, thumbnailView, callback);
thumbnailView.getViewTreeObserver()
.removeOnGlobalLayoutListener(getLayoutListener());
}
});
imageViewsToClear.add(thumbnailView);
}
});
}
}
Call this in your program
public void clearAllResources() {
// Set related variables null
System.gc();
Runtime.getRuntime().gc();
}
that is clearAllResources(); on start of activity
i'm using facebook runner to apply some facebook api tesk.
i want to check if i got a JSON object with data or and error message so i'm checking the "message" field to check if it's null.
if it is not null and i have a massage, i want to display the message and exit the application.
this is my code in my activity:
public class Loader extends Activity implements FacebookConnectionListener, ServerDataListener {
private TextView loaderStatus;
private Facebook facebook;
private AsyncFacebookRunner facebookRunner;
private FacebookConnection facebookConnection;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loader);
facebook = new Facebook(facebookAppId);
facebookRunner = new AsyncFacebookRunner(facebook);
facebookConnection = new FacebookConnection(this, 1);
facebookRunner.request("me",facebookConnection);
}
#Override
public void onFacebookResponse(final String response , int step) {
final JSONObject facebookResults = convertToJSON(response);
final Context thisContext = (Context) getBaseContext();
String id = "", name = "", gender = "", homeTown = "";
Drawable profilePicture = null;
if (step == 1) {
if (facebookResults.isNull("message")) {
try {
id = facebookResults.getString("id");
name = facebookResults.getString("name");
gender = facebookResults.getString("gender");
JSONObject homeTownObject = (JSONObject) facebookResults.get("hometown");
homeTown = homeTownObject.getString("name");
profilePicture = getProfilePicture(id);
} catch (JSONException e) {
alert("Facebook", e.toString(), "Ok", thisContext);
}
facebookCurrentUser = new FacebookCurrentUser(id, name, gender);
facebookCurrentUser.setHomeTown(homeTown);
facebookCurrentUser.setProfilePicture(profilePicture);
app.setFacebookCurrentUser(facebookCurrentUser);
facebookConnection = new FacebookConnection(this, 2);
this.runOnUiThread(new Runnable() {
public void run() {
loaderStatus.setText("Getting friends details");
}
});
}
else {
this.runOnUiThread(new Runnable() {
public void run() {
alert("Facebook", "Can't get user details! Please try again", "Ok", thisContext);
}
});
}
}
public void alert (String title, String message, String ok, Context listener)
{
AlertDialog.Builder alert = new AlertDialog.Builder(listener);
alert.setMessage(message);
alert.setTitle(title);
alert.setPositiveButton(ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
this is FacebookConnection class:
public class FacebookConnection implements RequestListener {
private FacebookConnectionListener listener;
private int step;
public FacebookConnection (FacebookConnectionListener listener, int step) {
this.listener = listener;
this.step = step;
}
public void updateFacebookListener(String response) {
listener.onFacebookResponse(response, step);
}
#Override
public void onComplete(String response, Object state) {
updateFacebookListener(response);
}
#Override
public void onIOException(IOException e, Object state) { }
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) { }
#Override
public void onMalformedURLException(MalformedURLException e, Object state) { }
#Override
public void onFacebookError(FacebookError e, Object state) { }
}
the FacebookConnectionListener interface:
public interface FacebookConnectionListener {
public void onFacebookResponse(String response, int step);
}
my alerts keep giving me the :
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
and i can't understand why.. help ?
Well, try this:
public void alert (String title, String message, String ok) {
this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog alert = new AlertDialog.Builder(Loader.this).create();
alert.setMessage(message);
alert.setTitle(title);
alert.setPositiveButton(ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
});
}
Instead of what you have now, and when you call it, just call it like any other method:
this.alert("Facebook", "Can't get user details! Please try again", "Ok")
I'm not exactly sure where it goes wrong, it even might have to do with you forgetting the create() part when constructing the dialog.
Hope this will sort things for you.
The reason it is appearing is because you are trying to update Ui from a different thread. As this is a partial code, I can suggest you changing your code to
MyActivity.this.runOnUiThread(new Runnable() {
public void run() {
loaderStatus.setText("Getting friends details");
}
});
where MyActivity is your Activity's name.
the easy way:
u can publishProgress(something)
and process the publishing, to show your alert :D