How to implement ProgressBar in FireBaseHandler - java

I have the problem, Fragment has content and I want to add simple ProgressBar while of Firebase loading content. How can I do this and where ? (I try to add in onDataChange but it dosn't work, code below)
public void onDataChange(DataSnapshot dataSnapshot) {
progressBar.setVisibility(View.VISIBLE);
mContentLayout.setVisibility(LinearLayout.GONE);
for (final DataSnapshot snapshot : dataSnapshot.getChildren()) {
item = snapshot.getValue(Item.class);
if(item.isSales()) {
arrayOfItemProduct.add(item);
}
}
adapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
mContentLayout.setVisibility(LinearLayout.VISIBLE);
}

To sovle this, you can add in your .XML layout file of your fragment the following lines of code:
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_bar"
android:layout_centerInParent="true"
style="#style/Widget.AppCompat.ProgressBar"/>
This means that everytime you start your fragment the ProgressBar will show up.
Define the progressBar variable as a global variable and then find it in your fragmnet inside the onCreateView() method like this:
progressBar = yourFragmentView.findViewById(R.id.progress_bar);
And then inside your onDataChange() method use the following code:
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}

Related

Add a dynamic button and specify a method when it's getting clicked

I have a button and in XML it looks like this:
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:tag="Greeting"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
Also, I have the method public void onClick(View view) {}. So whenever I click on that button, that method should run. Well, that works fine.
Now, I would like to add dynamic buttons.
if (_layout == R.layout.fragment_general) {
LinearLayout layout = view.findViewById(R.id.root);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for(String text : readFromSharedPreferences(getContext())) {
Button btn = new Button(this.getContext());
btn.setText(text);
btn.setTag(text);
btn.setTextColor(Color.BLUE);
btn.setBackgroundColor(Color.RED);
layout.addView(btn);
}
}
}
The buttons will be added but when I click on them, nothing happens.
I have also tried it with btn.performClick() and btn.callOnClick() but none of them works. In those methods I am missing a parameter. So it should be btn.performClick("onClick") or btn.callOnClick("onClick"). However, I should be able to tell that the method onClick should be executed when I click on a dynamic button. How can I do this?
try this code :-
if (_layout == R.layout.fragment_general) {
LinearLayout layout = view.findViewById(R.id.root);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (String text : readFromSharedPreferences(getContext())) {
Button btn = new Button(this.getContext());
btn.setText(text);
btn.setTag(text);
btn.setTextColor(Color.BLUE);
btn.setBackgroundColor(Color.RED);
layout.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
}
you just simply have to add setOnClickListener after btn added to linear layout.
it's working for me

why listview getcount() is equal to zero?

I have a problem with counting the number of items in ListView.
I'm pushing values into a folder in the firebase database. When I pull them on a separate activity, I get a list of the values I pushed .
The problem is I want to know how many items the list has. I tried to use listView.getCount() and also with arrayList.size() and both show zero, even though in the list itself I do see the values. Why is it happening ?
Here is my Java code:
list = (ListView) findViewById(R.id.listViewId2);
check2 = findViewById(R.id.check3);
arrayList = new ArrayList<String>();
keyList = new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(recommendations_weight.this ,android.R.layout.simple_list_item_1,arrayList);
list.setAdapter(arrayAdapter);
mDatabase = FirebaseDatabase.getInstance();
mAuth = FirebaseAuth.getInstance();
mDatabaseReference= FirebaseDatabase.getInstance().getReference().child("Recommendations").child("Blood").child("WBC").child("High").child("Weight").child("1");
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String value = dataSnapshot.getValue(String.class);
arrayList.add(value); // include the scan values
keyList.add(dataSnapshot.getKey()); //include the id of each tests
arrayAdapter.notifyDataSetChanged();
}
#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) {
}
});
//check if we have item
if (list.getAdapter().getCount() != 0){
check2.setText("number");
}
and this is my xml -
<ListView
android:id="#+id/listViewId2"
android:layout_width="350dp"
android:layout_height="200dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:visibility="visible"
android:textAlignment="center" />
<Button
android:id="#+id/returnButton"
android:layout_width="200dp"
android:layout_height="50dp"
android:text="return to test page"
android:textAllCaps="false"
android:background="#60000000"
android:layout_marginTop="30dp"
android:textColor="#FFFFFF"
android:textSize="20dp"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="#+id/check3"
android:layout_marginTop="19dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="check"
/>
One simply cannot expect the ArrayAdapter to be already populated, when entering asynchronous execution and then instantly checking in a synchronous manner, if there are any items contained.
As your code currently works (or better said: won't work):
at first, it requests remote data (entering asynchronous execution).
then it instantly checks the item-count in the adapter (synchronous execution).
then the items are being added (asynchronous execution).
asynchronous execution finishes.
Asynchronous execution requires callbacks, else you won't know when it had finished.
Just add verbose logging, in order to understand what is going on and in which order.
You're getting 0 because you are checking list.getAdapter().getCount(). I think you want to check whatever list variable holds the data you pass in (I doubt it's adapter).
So maybe: list.getAdapter.getArrayList().getCount()?

Using Street View VR in my app

I'm using Android Studio and trying to show some chosen Street View paths in VR. I already have Street View running well and now I'm trying to show it in VR.
I have put the com.google.vr.sdk.widgets.pano.VrPanoramaView in the layout and, inside onCreate in my class, referenced it to a VrPanoramaView variable through findViewById. Now I'm trying to show an image calling a method which I've defined in this class, loadPanoImage. This method loads an image from the storage and shows it through loadImageFromBitmap.
The problem is that it isn't able to show anything, even though I've followed a guide and I've done everything as showed. I've even tryed calling it in different parts of the code (before doing any other action, on clicking a button, before and after showing streetview) but I can't understand why it isn't working and how will I be able to use it to show images taken from StreetView (I don't know if I will be able to do it dinamically or I should download them and put them in the storage).
I'm putting part of the code for reference:
public class VrExperience extends FragmentActivity {
Button buttonCitta;
Button buttonMare;
Button buttonMontagna;
TextView titleTextView;
// George St, Sydney
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
// LatLng with no panorama
private static final LatLng INVALID = new LatLng(-45.125783, 151.276417);
//VrPanoramaView is inserted in the layout
private VrPanoramaView panoWidgetView;
//StreetViewPanorama is another class in my project which shows Street View
private StreetViewPanorama mStreetViewPanorama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vrexperiences);
panoWidgetView = (VrPanoramaView) findViewById(R.id.pano_view);
panoWidgetView.setEventListener(new VrPanoramaEventListener());
//download image and show it, but it doesn't show anything
loadPanoImage();
titleTextView = (TextView) findViewById(R.id.titleTextView);
buttonCitta = (Button) findViewById(R.id.buttonCitta);
buttonCitta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkReady()) {
return;
}
titleTextView.setVisibility(View.GONE);
buttonCitta.setVisibility(View.GONE);
buttonMare.setVisibility(View.GONE);
buttonMontagna.setVisibility(View.GONE);
loadPanoImage(); //it doesn't show anything
mStreetViewPanorama.setPosition(SYDNEY);
loadPanoImage(); //it doesn't show anything
}
}};
//code for buttonMontagna and buttonMare as well, it's identical
SupportStreetViewPanoramaFragment streetViewPanoramaFragment =
(SupportStreetViewPanoramaFragment)
getSupportFragmentManager().findFragmentById(R.id.streetviewpanorama);
streetViewPanoramaFragment.getStreetViewPanoramaAsync(
new OnStreetViewPanoramaReadyCallback() {
#Override
public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
mStreetViewPanorama = panorama;
// Only set the panorama to INVALID on startup (when no panoramas have been
// loaded which is when the savedInstanceState is null).
if (savedInstanceState == null) {
mStreetViewPanorama.setPosition(INVALID);
}
}
});
}
/**
* When the panorama is not ready the PanoramaView cannot be used. This should be called on
* all entry points that call methods on the Panorama API.
*/
private boolean checkReady() {
if (mStreetViewPanorama == null)
return false;
return true;
}
/**
* Called when the Animate To Invalid button is clicked.
*/
public void onGoToInvalid(View view) {
if (!checkReady()) {
return;
}
mStreetViewPanorama.setPosition(INVALID);
}
//retrieves image from the assets folder and loads it into the VrPanoramaView
private void loadPanoImage() {
VrPanoramaView.Options options = new VrPanoramaView.Options();
InputStream inputStream = null;
AssetManager assetManager = getAssets();
try {
inputStream = assetManager.open("demo2.jpg");
options.inputType = VrPanoramaView.Options.TYPE_MONO;
panoWidgetView.loadImageFromBitmap(
BitmapFactory.decodeStream(inputStream), options
);
inputStream.close();
} catch (IOException e) {
Log.e("Fail", "Exception in loadPanoImage" + e.getMessage());
}
}
#Override
protected void onPause() {
panoWidgetView.pauseRendering();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
panoWidgetView.resumeRendering();
}
#Override
protected void onDestroy() {
panoWidgetView.shutdown();
super.onDestroy();
}
}
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vrExperienceActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.vr.sdk.widgets.pano.VrPanoramaView
android:id="#+id/pano_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_weight="5"
android:scrollbars="none" />
<TextView
android:id="#+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:text="VR Experience"
android:textAlignment="center"
android:textAppearance="#android:style/TextAppearance.Large"
android:textColor="#0000F0"
android:visibility="visible" />
<Button
android:id="#+id/buttonCitta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Città" />
<fragment
class="com.google.android.gms.maps.SupportStreetViewPanoramaFragment"
android:id="#+id/streetviewpanorama"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
EDIT: #LucioB
a) those are the places I've tried to call loadPanoImage, but neither of them showed anything. It acts as nothing happens calling that method, the program keeps going to the other tasks. I'd like for images to be shown directly in VR when a button is clicked, or if that isn't possible to add the classic cardboard button in Street View mode to pass to VR view.
b) I mean the code isn't doing what I expected it to do. I thought that once I created VrPanoramaView in the layout and used it to show an image through .loadImageFromBitmap it would have shown the image I loaded from asset (I have an image saved on the virtual SD), and that once I was able to do that for a single image I would have found a way to do it for a whole path.
The code doesn't give any exception, I think I'm making a logic mistake or I didn't understand how VR api work.
EDIT: I've found that the java code is working, the problem was in the layout which didn't permit to see VrPanoramaView because it was obscured by StreetViewPanorama

RecyclerView doesn't load data in first launch using FirebaseRecyclerAdapter

I'm using FirebaseRecyclerAdapter to populate a RecyclerView in a Fragment.
Here's my code
mDatabase = FirebaseDatabase.getInstance().getReference();
myAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(Product.class,
R.layout.product_item,ProductViewHolder.class,
mDatabase.child("clothes")) {
#Override
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
viewHolder.name.setText(model.name);
viewHolder.price.setText(model.price);
Glide.with(getActivity()).load(model.imageUri).into(viewHolder.thumbnail);
Log.d("NAME", model.name);
}
};
recyclerView.setAdapter(myAdapter);
The problem is, the ProgressBar keeps moving in the first launch, it never hides and the RecyclerView never shows itself but If I exit the app and launch again, the RecyclerView is properly populated, even if the screen locks itself and I unlock it, the RecyclerView is populated. I'm confused.
Remove the recyclerView.setHasFixedSize(true) from your code and then check if the code works fine now.
And for dismissing the ProgressBar, its good to set the visibility to GONE.
mProgressBar.setVisibility(View.GONE);
For more information you can see this Github link. I think the same issue is reported here.
In your activity.xml file, set ProgressBar property
android:visibility="invisible"
and in your populateViewHolder method, set mProgress.setVisibility(View.GONE);
after setting data to TextViews & ImageView
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
viewHolder.name.setText(model.name);
viewHolder.price.setText(model.price);
Glide.with(getActivity()).load(model.imageUri).into(viewHolder.thumbnail);
mProgress.setVisibility(View.GONE);
Log.d("NAME", model.name);
}

Add extra text to the copied text

I have this TextView in my application
<TextView
android:id="#+id/txtStatusMsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="#dimen/feed_item_status_pad_left_right"
android:paddingRight="#dimen/feed_item_status_pad_left_right"
android:paddingTop="#dimen/feed_item_status_pad_top"
android:textIsSelectable="true"
/>
and its selectable ..when i select text and copy it i want to add extra text
example :
Test text
what i want is when i select the text and copy it :
Test text - Copied from xx app
how i can do it ?
You'll want to add a clipboardListener:
private boolean mSkipClip;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
final ClipboardManager mClipboard = (ClipboardManager)mAct.getSystemService
(Context.CLIPBOARD_SERVICE);
mClipboard.addPrimaryClipChangedListener(new ClipboardManager
.OnPrimaryClipChangedListener() {
#Override
public void onPrimaryClipChanged() {
if (mSkipClip) {
mSkipClip = false;
} else {
// Append custom string
ClipData clipData = new ClipData(mClipboard.getPrimaryClip());
clipData.addItem(new ClipData.Item("Copied from xx app"));
mSkipClip = true;
mClipboard.setPrimaryClip(clipData);
}
}
});
}
Notes:
ClipData class which is available only since API 16.
Other classes and methods are available since API 11.
When you update the clipboard data, the listener is called again. mSkipClip helps the listener skip such callbacks.
When pausing your activity, make sure you remove the listener, as it will listen to clipboard activity on other activities and apps too.

Categories

Resources