I am facing an issue in using the FirebaseRecyclerAdapter.
The firebase realtime database structure is as follows:
What I'm trying to do here is,
Get only the key's from data present in the "MainGroup" part of the firebase realtime database.
So to do that, I've created a model class named RecyclerDataGetSetCLass
and one viewholder class named RecyclerDataGetSetClassViewHolder
but i am getting an error saying
com.google.firebase.database.DatabaseException: Can't convert object
of type java.lang.String to type
com.example.talarir.mapproject.NonAdminClasses.RecyclerDataGetSetCLass
The Activity classes and other java files are as follows:
1) NonAdminACtivity.java //which contains the viewholder class
public class NonAdminACtivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
public Button saveLocationBtn,getLocationBtn;
public RecyclerView nonAdminRecyclerView;
private Boolean flag=false;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private DatabaseReference mFirebaseDatabase1;
private FirebaseDatabase mFirebaseInstance1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_non_admin_activity);
mFirebaseInstance1 = FirebaseDatabase.getInstance();
mFirebaseDatabase1 = mFirebaseInstance1.getReference("MainGroup");
nonAdminRecyclerView= (RecyclerView) findViewById(R.id.recycler_view_fragment_one);
nonAdminRecyclerView.setHasFixedSize(true);
nonAdminRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
flag=true;
Log.d("CooActivity", "onAuthStateChanged:signed_in:" + user.getUid());
Toast.makeText(getApplicationContext(),"done",Toast.LENGTH_SHORT).show();
}
else
{
// User is signed out
Log.d("CooActivity", "onAuthStateChanged:signed_out");
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
}
};
}
#Override
public void onStart()
{
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
saveLocationBtn= (Button) findViewById(R.id.saveLocationOfUser);
saveLocationBtn.setOnClickListener(this);
getLocationBtn= (Button) findViewById(R.id.getLocationOfUser);
getLocationBtn.setOnClickListener(this);
FirebaseRecyclerAdapter<RecyclerDataGetSetCLass,RecyclerDataGetSetClassViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<RecyclerDataGetSetCLass, RecyclerDataGetSetClassViewHolder>(
RecyclerDataGetSetCLass.class,
R.layout.each_list_non_admin,
RecyclerDataGetSetClassViewHolder.class,
mFirebaseDatabase1
) {
#Override
protected void populateViewHolder(RecyclerDataGetSetClassViewHolder viewHolder, RecyclerDataGetSetCLass model, int position)
{
viewHolder.setMainGroupName(model.getMainGroupName());
}
};
nonAdminRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class RecyclerDataGetSetClassViewHolder extends RecyclerView.ViewHolder
{
View mView;
public RecyclerDataGetSetClassViewHolder(View itemView) {
super(itemView);
mView=itemView;
}
public void setMainGroupName(String mainGroupName)
{
TextView textView= (TextView) mView.findViewById(R.id.textViewRecyclerViewNonAdmin);
textView.setText(mainGroupName);
}
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onDestroy() {
FirebaseAuth.getInstance().signOut();
super.onDestroy();
}
#Override
public void onClick(View v)
{
if (v.getId()==R.id.saveLocationOfUser)
{
if (flag)
{
saveUserLocation_NonAdminActivity();
}
else
{
Toast.makeText(this,"firebase not ready",Toast.LENGTH_SHORT).show();
}
}
if (v.getId()==R.id.getLocationOfUser)
{
retrieveUserLocation_NonAdminActivity();
}
}
private void retrieveUserLocation_NonAdminActivity()
{
CreationOfUserClass creationOfUserClass=new CreationOfUserClass(this);
creationOfUserClass.retrieveUserDataFromFireBase(mFirebaseDatabase,mFirebaseInstance);
}
private void saveUserLocation_NonAdminActivity()
{
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
final CreationOfUserClass creationOfUserClass=new CreationOfUserClass(this);
creationOfUserClass.createUsers(user, mFirebaseDatabase,mFirebaseInstance);
}
}
2) RecyclerDataGetSetCLass //The model class
public class RecyclerDataGetSetCLass
{
private String mainGroupName;
public RecyclerDataGetSetCLass()
{
}
public RecyclerDataGetSetCLass(String mainGroupName)
{
this.mainGroupName=mainGroupName;
}
public String getMainGroupName() {
return mainGroupName;
}
public void setMainGroupName(String mainGroupName) {
this.mainGroupName = mainGroupName;
}
}
3) activity_non_admin_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_non_admin_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.talarir.mapproject.NonAdminACtivity">
<Button
android:text="SaveLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/saveLocationOfUser" />
<Button
android:text="getLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/getLocationOfUser" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_fragment_one"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</LinearLayout>
4) each_list_non_admin.xml //the layout to be inflated for each recycler list element
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
xmlns:card_view="http://schemas.android.com/tools">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_margin="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/textViewRecyclerViewNonAdmin"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
The error log is as follows :
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.talarir.mapproject.NonAdminClasses.RecyclerDataGetSetCLass
at com.google.android.gms.internal.zzbtg.zze(Unknown Source)
at com.google.android.gms.internal.zzbtg.zzb(Unknown Source)
at com.google.android.gms.internal.zzbtg.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:151)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:140)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:183)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6308)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6341)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5287)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5550)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5392)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5388)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2149)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1533)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1496)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:593)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3535)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3264)
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1633)
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:341)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:616)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6209)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
D/AppTracker: App Event: crash
I/Process: Sending signal. PID: 29821 SIG: 9
Application terminated.
Kindly assist me to get through this issue.
The value of each item you're displaying is a single string (-K....). You're trying to read an entire class out of the value, and that simply won't work.
final FirebaseRecyclerAdapter<RecyclerDataGetSetCLass,RecyclerDataGetSetClassViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<RecyclerDataGetSetCLass, RecyclerDataGetSetClassViewHolder>(
String.class,
R.layout.each_list_non_admin,
RecyclerDataGetSetClassViewHolder.class,
mFirebaseDatabase1
) {
#Override
protected void populateViewHolder(RecyclerDataGetSetClassViewHolder viewHolder, String model, int position)
{
String key = adapter.getRef(position).getKey();
viewHolder.setMainGroupName(key);
}
};
In this snippet I look up the key of the item being shown, which is likely the value that you're looking for.
Related
Is there a panorama open-source solution for the Android camera app?
I came across these options:
panoramagl-android
WideAnglePanoramaModule.java
but they look a little old and have no support, is there anything newer?
I also came across this page:
But there is not much documentation about it that I could find.
I would like to get a full solution including capturing the images, stitching and displaying.
Look at this article:
https://itnext.io/android-360-panorama-cedbfb47a9e
The thing that i dont like is that all images are from assets. I did it with image from firebase:
add dependancy:
dependencies {
/*
* Google VR SDK
* Release version: https://github.com/googlevr/gvr-android-sdk/releases
* */
implementation 'com.google.vr:sdk-panowidget:1.180.0'
implementation 'com.github.silvestrpredko:dot-progress-bar:1.1'
}
add class
public class SimpleVrPanoramaActivity extends Activity {
#BindView(R.id.progressBar2)
DotProgressBar dotProgressBar;
#BindView(R.id.pano_view)
VrPanoramaView panoWidgetView;
private String bar_panorama1;
private String mPost_key = null;
private Bitmap[] bitmaps = new Bitmap[1];
private DatabaseReference databaseReference;
private VrPanoramaView.Options panoOptions = new VrPanoramaView.Options();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_panorama);
ButterKnife.bind(this);
if (getIntent().getExtras() != null) {
mPost_key = getIntent().getExtras().getString("bar_id");
}
panoOptions.inputType = VrPanoramaView.Options.TYPE_MONO;
databaseReference = FirebaseDatabase.getInstance().getReference().child("bars").child(mPost_key).child("pano");
fetchPanorama();
}
private void fetchPanorama() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
bar_panorama1 = dataSnapshot.child("i1").getValue(String.class);
glideImage(bar_panorama1);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(SimpleVrPanoramaActivity.this, "Проверьте подключение к интернету!", Toast.LENGTH_LONG).show();
}
});
}
public void glideImage(String bar_panorama) {
Glide.with(SimpleVrPanoramaActivity.this)
.asBitmap()
.load(bar_panorama)
.into(new CustomTarget<Bitmap>() {
#Override
public void onLoadFailed(#Nullable Drawable errorDrawable) {
dotProgressBar.setVisibility(View.GONE);
}
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
bitmaps[0] = resource;
panoWidgetView.loadImageFromBitmap(bitmaps[0], panoOptions);
dotProgressBar.setVisibility(View.GONE);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
#Override
protected void onPause() {
panoWidgetView.pauseRendering();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
panoWidgetView.resumeRendering();
}
#Override
protected void onDestroy() {
// Destroy the widget and free memory.
panoWidgetView.shutdown();
super.onDestroy();
}
}
add xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
tools:context=".aktau.panorama.PanoramaGLActivity">
<include
android:id="#+id/toolbar_pano"
layout="#layout/toolbar_pano"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" />
<View
android:id="#+id/yellow_layer"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorOrange"
android:layout_below="#+id/toolbar_pano"
/>
<com.google.vr.sdk.widgets.pano.VrPanoramaView
android:id="#+id/pano_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/yellow_layer"/>
<com.github.silvestrpredko.dotprogressbar.DotProgressBar
android:id="#+id/progressBar2"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_below="#+id/toolbar_pano"
android:layout_alignParentBottom="true"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
app:amount="3"
android:layout_centerHorizontal="true"
app:animationDirection="right"
app:duration="#android:integer/config_shortAnimTime"
app:endColor="#color/colorPrimaryDark"
app:startColor="#color/colorLightBlue" />
</RelativeLayout>
I am getting Error that i wrote below when showing custom Dialog from FragmentActivity.
Error i am getting :
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Here is my DriverMapActivity that i show custom Dialog from :
Note: I removed some codes that they are not related to my question
DriverMap FragmentActivity
public class DriverMapActivity extends FragmentActivity{
private GoogleMap mMap;
GoogleApiClient googleApiClient;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
private Location lastLocation;
private FirebaseAuth mAuth;
private Switch workingswitch;
private String customerId, userId;
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private DatabaseReference driverInfoDB;
private String name, surname, profileimageURL;
private String distancetopick,distancetodes;
private int distancefinal;
private Button yesBtn, noBtn;
private UserInfoShower cdd;
private int cameraupdatedandzoomed;
private Map<String,String> infoMap;
private LatLng pickupLoc;
private LatLng destiantionLoc;
private Marker pickupMarker, destinationMarker;
private float rideDistance;
private Button btnzoom;
private String customerprofileUrl;
private Button logoutbtn, settingsbtn, historybtn, opendrawer;
private boolean pickupgeted;
private String rideStatus = "";
private LatLng target;
#SuppressLint("NewApi")
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_map);
customerId = "";
cameraupdatedandzoomed=0;
mAuth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbar);
polylines = new ArrayList<>();
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
btnzoom=findViewById(R.id.btnzoom);
pickupgeted = false;
startService(new Intent(DriverMapActivity.this,onAppKilled.class));
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
// This method will trigger on item Click of navigation menu
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setDriverStuffToNavView();
btnzoom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(lastLocation!=null)
{
}
else
{
Toast.makeText(DriverMapActivity.this, "Turn on Working
}
}
});
private void listenForCustomerRequest() {
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReferencelistenerRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Drivers").child(userId).child("CustomerRequest");
listenerRef.addChildEventListener(new ChildEventListener() {
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
customerId = dataSnapshot.getKey();
showUserInfo();
}
}
});
}
Here is method that i show CustomDialog:
UserInfoShower Method
Note: I removed some codes that they are not related to my question
private void showUserInfo() {
DatabaseReferenceuserinfoRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
Log.i("TEST", "CustomerId Comes Driver " + customerId);
infoMap=new HashMap<>();
cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
DatabaseReferenceuserInfoDB=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
userInfoDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) {
Map<String, Object> map = (Map<String, Object>)
dataSnapshot.getValue();
infoMap.put("DriverOrCus", "1");
infoMap.put("Name", map.get("name").toString());
infoMap.put("Surname", map.get("surname").toString());
if(map.get("profileimageURL") !=null)
{
infoMap.put("profileimageURL",
map.get("profileimageURL").toString());
customerprofileUrl=map.get("profileimageURL").toString();
}
infoMap.put("customerId", customerId);
cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
cdd.show();
cdd.setCanceledOnTouchOutside(false);
yesBtn = cdd.findViewById(R.id.yesBtn);
noBtn = cdd.findViewById(R.id.noBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userId=FirebaseAuth.getInstance().
getCurrentUser().getUid();
DatabaseReference decisionRef=FirebaseDatabase.
getInstance().getReference().
child("Users").child("Drivers").child(userId).child("CustomerRequest")
.child(customerId)
.child("driverDecision");
decisionRef.setValue("YES").addOnCompleteListener(newOnCompleteListener
<Void>() {
#Override
public void onComplete(#NonNull
Task<Void>task) {
cdd.cancel();
cdd.dismiss();
cdd=null;
getCustomerRideInfo();
}
});
}
});
}
Error happens when i call cdd.show();
Here is UserInfoShower Dialog:
public class UserInfoShower extends Dialog {
public Context c;
private Button noBtn, yesBtn;
private String name, surname, profileimageURL;
private TextView customerName, customerSurname;
private ImageView customerprofile;
private int position;
private String driverId;
private LatLng CustomerPickupLoc, CustomerDestinationLoc;
private String customerId, desName;
private SharedPreferences sharedpref;
Map<String,String> infoMap;
public UserInfoShower(Context a,Map<String,String> infoMap) {
super(a);
this.c = a;
this.infoMap=infoMap;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_customer_info_shower);
noBtn = findViewById(R.id.noBtn);
yesBtn = findViewById(R.id.yesBtn);
customerName = findViewById(R.id.customerName);
customerSurname = findViewById(R.id.customerSurname);
customerprofile = findViewById(R.id.customerprofile);
position = Integer.valueOf(infoMap.get("DriverOrCus"));
if (position == 1) {
showCusInfo();
} else {
showDriverInfo();
}
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) // If user is Driver
{
dismiss();
} else //if user is Cusomer And Liked Driver
{
dismiss();
}
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) //if User is Driver
{
dismiss();
} else// if User is Customer And not liked Driver
{
dismiss();
}
}
});
}
private void showCusInfo() {
name = infoMap.get("Name");
surname = infoMap.get("Surname");
customerId = infoMap.get("customerId");
customerName.setText("Name " + name);
customerSurname.setText("Surname " + surname);
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
}
public static boolean isValidContextForGlide(final Context context) {
if (context == null) {
return false;
}
if (context instanceof Activity) {
final Activity activity = (Activity) context;
if (activity.isDestroyed() || activity.isFinishing()) {
return false;
}
}
return true;
}
}
Here is My Dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://
schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".UserInfoShower">
<ImageView
android:id="#+id/customerprofile"
android:layout_width="90dp"
android:layout_height="102dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="35dp"
android:src="#drawable/customer"
tools:ignore="RtlCompat" />
<TextView
android:layout_width="240dp"
android:layout_height="wrap_content"
android:id="#+id/customerName"
android:layout_alignParentTop="true"
android:layout_marginTop="36dp"
android:layout_toEndOf="#+id/customerprofile"
android:text="Name : Vuqar"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
tools:ignore="RtlCompat" />
<TextView
android:id="#+id/customerSurname"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="92dp"
android:layout_toEndOf="#+id/customerprofile"
android:text="Surname : Samed"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
tools:ignore="RtlCompat" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="219dp"
android:orientation="horizontal">
<Button
android:id="#+id/yesBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK.Looks Good" />
<Button
android:id="#+id/noBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nope" />
</LinearLayout>
</RelativeLayout>
And finally here is whole error log :
Hope you can help me.Cheers !
Problem solved by : #dr3k
Here is solution. Solution
I have been working on an android project in which I have used YouTube API and Firebase as a database, I also used recyclerView in it but my videos from Firebase database are not showing in the application, I have implemented it correctly I guess but there is something wrong with it, please help.
I am using Android Studio
YouTube Firebase Adapter java class:
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.youtube_videos);
YDatabaseReference = FirebaseDatabase.getInstance().getReference().child("youT");
YouRecycler = (RecyclerView)findViewById(R.id.Youtube_recycler);
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder>(
post2youtube.class,
R.layout.youtube_videos_card,
YoutubeViewHolder.class,
YDatabaseReference
) {
#Override
protected void populateViewHolder(YoutubeViewHolder viewHolder, post2youtube model, int position) {
viewHolder.setYoutube(model.getYoutubing());
}
};
YouRecycler.setAdapter(firebaseRecyclerAdapter);
}
public static class YoutubeViewHolder extends RecyclerViewPager.ViewHolder {
View yView;
public YoutubeViewHolder(View itemView) {
super(itemView);
yView = itemView;
}
public void setYoutube(final String youtubing){
final YouTubePlayerView youPlay = (YouTubePlayerView) yView.findViewById(R.id.youtuber);
youPlay.initialize("SOME KEY",
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo(youtubing);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
Getter and setters class :
public class post2youtube {
private String youtubing;
public post2youtube(){
}
public post2youtube(String youtubing) {
this.youtubing = youtubing;
}
public String getYoutubing() {
return youtubing;
}
public void setYoutubing(String youtubing) {
this.youtubing = youtubing;
}
}
RecyclerView xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/Youtube_recycler"/>
</LinearLayout>
CardView xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtuber"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
</android.support.v7.widget.CardView>
I'm trying to do an exercise from edx.org (Chat Firebase, whole code from https://github.com/ykro/android-chat-firebase) and I cannot understand where does this error comes, it's a NPE but it's getting me off, it crashes when application runs on Genymotion Emulator.
ERROR
java.lang.RuntimeException: Unable to start activity ComponentInfo{cat.edx_manel.exercises.chatfirebase/cat.edx_manel.exercises.chatfirebase.activities.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at cat.edx_manel.exercises.chatfirebase.activities.LoginActivity.setInputs(LoginActivity.java:114)
at cat.edx_manel.exercises.chatfirebase.activities.LoginActivity.disableInputs(LoginActivity.java:57)
at cat.edx_manel.exercises.chatfirebase.implementations.login.LoginPresenterImpl.checkForAuthenticateUser(LoginPresenterImpl.java:43)
at cat.edx_manel.exercises.chatfirebase.activities.LoginActivity.onCreate(LoginActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
LOGINACTIVITY
public class LoginActivity extends AppCompatActivity implements LoginView {
#BindView(R.id.user)
EditText inputEmail;
#BindView(R.id.pass)
EditText inputPassword;
#BindView(R.id.signIn)
Button btnSignIn;
#BindView(R.id.signUp)
Button btnSignUp;
#BindView(R.id.progressBar)
ProgressBar progressBar;
#BindView(R.id.layoutMainContainer)
RelativeLayout container;
private LoginPresenter loginPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
loginPresenter = new LoginPresenterImpl(this);
loginPresenter.onCreate();
loginPresenter.checkForAuthenticateUser();
}
#Override
protected void onDestroy() {
loginPresenter.onDestroy();
super.onDestroy();
}
#Override
public void disableInputs() {
setInputs(false);
}
#Override
public void enableInputs() {
setInputs(true);
hideProgress();
}
#Override
public void showProgress() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void hideProgress() {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
#OnClick(R.id.signUp)
public void handleSignUp() {
loginPresenter.registerNewUser(inputEmail.getText().toString(),
inputPassword.getText().toString());
}
#Override
#OnClick(R.id.signIn)
public void handleSignIn() {
loginPresenter.validateLogin(inputEmail.getText().toString(),
inputPassword.getText().toString());
}
#Override
public void navigateToMainScreen() {
startActivity(new Intent(this, ContactListActivity.class));
}
#Override
public void loginError(String error) {
inputPassword.setText("");
String msgError = String.format(getString(R.string.login_error_message_signin), error);
inputPassword.setError(msgError);
}
#Override
public void newUserSuccess() {
Snackbar.make(container, R.string.login_error_message_signup, Snackbar.LENGTH_SHORT).show();
}
#Override
public void newUserError(String error) {
inputPassword.setText("");
String msgError = String.format(getString(R.string.login_error_message_signup), error);
inputPassword.setError(msgError);
}
private void setInputs(boolean enabled) {
btnSignIn.setEnabled(enabled);
btnSignUp.setEnabled(enabled);
inputEmail.setEnabled(enabled);
inputPassword.setEnabled(enabled);
}
}
As you can see, button is binded by Butterknife framework, but I don't know what causes it...
Thanks you very much
UPDATED
LAYOUT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layoutMainContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".activities.LoginActivity">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/user"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Password"
android:ems="10"
android:id="#+id/pass"/>
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:id="#+id/layoutButtons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/signIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_below="#id/layoutButtons"/>
UPDATE 2
LOGINVIEW INTERFACE
public interface LoginView {
void enableInputs();
void disableInputs();
void showProgress();
void hideProgress();
void handleSignUp();
void handleSignIn();
void navigateToMainScreen();
void loginError(String error);
void newUserSuccess();
void newUserError(String error);
}
First, here is one of my answers I shared to setup ButterKnife correctly.
Consider this possible issue:
What are you Overriding here?
#Override //this line here
#OnClick(R.id.signUp)
public void handleSignUp() {
loginPresenter.registerNewUser(inputEmail.getText().toString(),
inputPassword.getText().toString());
}
#Override //this line here
#OnClick(R.id.signIn)
public void handleSignIn() {
loginPresenter.validateLogin(inputEmail.getText().toString(),
inputPassword.getText().toString());
}
Try this instead without the overrides:
#OnClick(R.id.signUp)
public void handleSignUp() {
loginPresenter.registerNewUser(inputEmail.getText().toString(),
inputPassword.getText().toString());
}
#OnClick(R.id.signIn)
public void handleSignIn() {
loginPresenter.validateLogin(inputEmail.getText().toString(),
inputPassword.getText().toString());
}
Then clean your project and run again!
I hope this helps!
I'm referring to the tutorial at ButterKnife tutorial. I think instead of using #BindView it should be #Bind
#Bind(R.id.button)
Button button;
#Bind(R.id.textView)
TextView textView;
#Bind(R.id.radioButton)
RadioButton radioButton;
#Bind(R.id.checkBox)
I am trying to implement "Swipe to load more" method in my application but I got that error when I swipe down in the first time. This is what it showed in the console:
E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have an active
pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have
an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but
don't have an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE
event but don't have an active pointer id.
This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="training.com.chatgcmapplication.ChatActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="380dp">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
</android.support.v4.widget.SwipeRefreshLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.92"
android:inputType="text" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
And when I swipe in the second time: it load double data.
This is ChatActivity, what implement that method:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
private static EditText txt_chat;
private String registId;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private int offsetNumber = 5;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Button btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(this);
ListView lv_message = (ListView) findViewById(R.id.listMessage);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
Bundle bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), 0);
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), offsetNumber);
messageAdapter.insertToTheFirst(messages);
messageAdapter.notifyDataSetChanged();
offsetNumber += 5;
Log.i("Offset number", offsetNumber + "");
swipeRefreshLayout.setRefreshing(false);
}
}
UPDATE ISSUE's REASON
I found the reason of that issue. It due to I force the listview scroll to the bottom when it init with this code :
android:stackFromBottom="true"
I replace that code with this but still have same issue:
lv_message.post(new Runnable() {
#Override
public void run() {
lv_message.setSelection(lv_message.getCount() -1);
}
});
I think the problem is , You are trying to show , dismiss and refresh swipeRefreshLayout inside the same method i.e onRefresh().
Make seperate methods for showing and dismissing dialog and invoke them from the place where they are required as I have done below:
#Override
public void onRefresh() {
// refresh code here.
}
#Override
public void showDialog() {
swipeRef.post(new Runnable() {
#Override
public void run() {
if(swipeRef != null)
swipeRef.setRefreshing(true);
}
});
}
#Override
public void dismissDialog() {
if(swipeRef!=null && swipeRef.isShown() )
swipeRef.setRefreshing(false);
}