Categories
discuss

Recyclerview does not show anything?

I’m trying to show list of strings in recycler view. For some reason it is not working. it does not show anything. I dont know why it is not working, its not the first time that i use that, usally i did it with firebase recycler.

Here is my code

   rvTypeMusic = (RecyclerView)findViewById(R.id.rvMusicType);
    ArrayList<String> songs = new ArrayList<String>();
    songs.add("PHP");
    songs.add("C#");
    songs.add("Java");
    songs.add("JavaScript");
    songs.add("Android");

   adapter = new TypeMusicListAdapter(this,songs);
    rvTypeMusic.setAdapter(adapter);
    rvTypeMusic.setLayoutManager(new GridLayoutManager(this,2));
}


     public static class TypeMusicListAdapter extends 
              RecyclerView.Adapter<TypeMusicListViewHolder>{
    private LayoutInflater inflater;
    private Context context;
    private List<String> data;

    public TypeMusicListAdapter(Context context, List<String> data){
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.data = data;
    }

    @Override
    public TypeMusicListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = inflater.inflate(R.layout.type_music_item,parent,false);
        return new TypeMusicListViewHolder(v);
    }

    @Override
    public void onBindViewHolder(TypeMusicListViewHolder holder, int position) {
        String songType = data.get(position);
        //holder.musicType.setText(songType.getSongName());
        holder.musicType.setText(songType);
    }

    @Override
    public int getItemCount() {
        return 0;
    }
}

public static class TypeMusicListViewHolder extends RecyclerView.ViewHolder {
    private TextView musicType;

    public TypeMusicListViewHolder(View itemView) {
        super(itemView);
        musicType = (TextView) itemView.findViewById(R.id.musicType);
    }
}

XML File

      <android.support.constraint.ConstraintLayout 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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.world.bolandian.talent.MainActivity"
tools:showIn="@layout/app_bar_main">

<android.support.v7.widget.RecyclerView
    android:id="@+id/rvMusicType"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:layout_marginTop="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:listitem="@layout/type_music_item">

</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>

XML Item

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">


    <TextView
        android:id="@+id/musicType"
        android:padding="25dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />
</android.support.v7.widget.CardView>

</LinearLayout> 

What am i missing here? i have tried few things but nothing worked.

Answer

Problem is in this line.

 @Override
public int getItemCount() {
    return 0;
}

It should be

 @Override
public int getItemCount() {
    return data.size();
}
Categories
discuss

Java streams: Collect a nested collection

I’m learning how to use Java streams and need some help understanding how to stream nested collections and collect the results back into a collection.

In the simple example below, I’ve created 2 ArrayLists and added them to an ArrayList. I want to be able to perform a simple function on each nested collection and then capture the results into a new collection. The last line of code doesn’t even compile. Any explanations would be appreciated!

    ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1,2,3));
    ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(4,5,6));

    ArrayList<ArrayList<Integer>> nested = new ArrayList<ArrayList<Integer>>();
    nested.add(list1);
    nested.add(list2);

    ArrayList<ArrayList<Integer>> result = nested.stream()
            .map(list -> list.add(100))
            .collect(Collectors.toList());

Answer

The problem is that List#add doesn’t return a List. Instead, you need to return the list after the mapping:

List<ArrayList<Integer>> result = nested.stream()
        .map(list -> {
            list.add(100);
            return list;
        })
        .collect(Collectors.toList());

Or you may skip using map and do it using forEach, since ArrayList is mutable:

nested.forEach(list -> list.add(100));
Categories
discuss

How to center align the header text of a TemplateField?

I’ve a GridView with TemplateFields.

I have tried HeaderStyle-HorizontalAlign="Center" to align the header text of the TemplateField to center but it’s not working.

<asp:TemplateField HeaderText="Events" HeaderStyle-HorizontalAlign="Center" 
    ItemStyle-HorizontalAlign="Center">
</asp:TemplateField>

How I can align center the header text of a TemplateField?

While ItemStyle-HorizontalAlign="Center" aligning center the items of TemplateField is working correctly.

Any help will be really appreciated!

Answer

The <center> tag is deprecated in HTML 4.01 and not supported in HTML5 – the working code you posted could be “CSS-ified” as follows:

<asp:TemplateField ItemStyle-HorizontalAlign="Center">
    <HeaderTemplate>
        <asp:Panel style="margin-left: auto; margin-right: auto; text-align: center;">
            Events
        <asp:Panel>
    </HeaderTemplate>
<asp:TemplateField>

(Note: Panel is the ASP.Net equivalent of a <div>.)

A slight improvement here is to define a CSS class for the style so it can be reused elsewhere:

.center {
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

…and reference it from the panel instead of using the inline style:

<asp:Panel CssClass="center">
Categories
discuss

Background service for android oreo

How to continue background service in android Oreo without showing notification dot? i continues my background service using notification but i don’t want to show notification for running service.

Answer

If you would have read the Android Oreo 8.0 Documentation properly somewhere in here, you might not have posted this question here.

Step 1: Make sure you start a service as a foreground Service as given in below code

ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), GpsServices.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BluetoothService.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BackgroundApiService.class));

Step 2: Use notification to show that your service is running. Add below line of code in onCreate method of Service.

@Override
public void onCreate() {
    ...
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(NOTIFICATION_ID, notification);
    }
    ...
}

Step 3: Remove the notification when the service is stopped or destroyed.

@Override
public void onDestroy() {
    ...
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          stopForeground(true); //true will remove notification
    }
    ...
}

One problem with this solution is that it will keep showing the notification until your Service is running on all devices running on Android Oreo 8.0.

I’m sure that this solution will work even when the app is in the background or in kill state.

IMPORTANT NOTE: SHOWING A NOTIFICATION FOR RUNNING A SERVICE IN BACKGROUND (APP IN BACKGROUND OR KILLED STATE) IS MANDATORY IN ANDROID OREO 8.0. YOU CANNOT RUN AWAY WITH IT. SO IT IS RECOMMENDED THAT YOU MAKE NECESSARY CHANGES IN YOUR APP TO MAKE IT WORK PROPERLY AS PER THE BEST PRACTICES FOLLOWED OR ASKED BY ANDROID.

I hope this might help to solve your problem.

Categories
discuss

Facebook Account Kit Collision with Google play services gradle

After configuring account kit sdk as

  compile 'com.facebook.android:account-kit-sdk:4.+'

and gradle sync it conflict with com.google.android.gms gradle as mixing versions can lead to runtime crashes and my app crash as

Firebase API initialization failure. java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.google.firebase.FirebaseApp.zza(Unknown Source) at …

the above error is due to mixing google play services gradle (I think Google play services gradle may be used by Facebook Account Kit SDK) because I have same version for all Google play services gradles.

And one more crash is coming from Facebook Account Kit SDK side as

 java.lang.RuntimeException: Unable to get provider com.facebook.accountkit.internal.AccountKitInitProvider: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
                                                       at android.app.ActivityThread.installProvider(ActivityThread.java:5260)
                                                       at android.app.ActivityThread.installContentProviders(ActivityThread.java:4808)
                                                       at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4748)
                                                       at android.app.ActivityThread.access$1700(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5529)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
                                                       at com.facebook.accountkit.internal.Initializer.initialize(Initializer.java:99)
                                                       at com.facebook.accountkit.internal.AccountKitController.initialize(AccountKitController.java:592)
                                                       at com.facebook.accountkit.internal.AccountKitInitProvider.onCreate(AccountKitInitProvider.java:31)
                                                       at android.content.ContentProvider.attachInfo(ContentProvider.java:1758)
                                                       at android.content.ContentProvider.attachInfo(ContentProvider.java:1733)
                                                       at android.app.ActivityThread.installProvider(ActivityThread.java:5257)
                                                       at android.app.ActivityThread.installContentProviders(ActivityThread.java:4808) 
                                                       at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4748) 
                                                       at android.app.ActivityThread.access$1700(ActivityThread.java:153) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                       at android.os.Looper.loop(Looper.java:154) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:5529) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) 

But after removing

  compile 'com.facebook.android:account-kit-sdk:4.+'

my app working without any issue. But to integrate Facebook Account Kit in my app I have to include above gradle which conflict with google play services.

Totally disappointed, please help.


After upgrading Firebase Gradle as

compile 'com.google.firebase:firebase-messaging:11.6.0'

its not colliding but still gives above RuntimeException from Account Kit SDK.

Answer

For Unable to get provider RuntimeException exception it seems that, Application is not initialized first, Content Providers are initialized before it. And in Facebook account kit SDK’s code it was trying to get my application context.

Now the problem was, I did implement method getApplicationContext() in application class that is getting application shared variable but that variable was setting globally and Facebook Account Kit sdk code getting Null application context.

Solution : setting shared variable in onCreate method instead of setting globally it resolved the problem of Unable to get provider.

And For Mixing issue, Account Kit SDK use 11.0.1 version for play services gradle and in my project I am having 11.0.4 that is actually not the issue because on compile time gradle takes latest gradle but In my project I am not referring below gradle which Facebook Account Kit SDK is using.

compile 'com.google.android.gms:play-services-auth-api-phone:11.0.1'

Solution : I have added above gradle with version 11.0.4 and the mixing gradle issue has been resolved.

compile 'com.google.android.gms:play-services-auth-api-phone:11.0.4'

And as suggested by @astryk if I exclude play-services-auth-api-phone module then gradle mixing error is not showing but it is not including that module becasue in AccountKitActivity on next button click my application crashes as

Crash Report Thread:main Exception:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/auth/api/phone/SmsRetriever;
at com.facebook.accountkit.internal.PhoneLoginController.createSmsToken(PhoneLoginController.java:250)
at com.facebook.accountkit.internal.PhoneLoginController.logIn(PhoneLoginController.java:188)
at com.facebook.accountkit.internal.LoginManager.logInWithPhoneNumber(LoginManager.java:372)
at com.facebook.accountkit.internal.AccountKitController.logInWithPhoneNumber(AccountKitController.java:631)
at com.facebook.accountkit.ui.PhoneLoginFlowManager.logInWithPhoneNumber(PhoneLoginFlowManager.java:57)
at com.facebook.accountkit.ui.ActivityPhoneHandler.onPhoneLoginComplete(ActivityPhoneHandler.java:189)
at com.facebook.accountkit.ui.AccountKitActivity$1.onReceive(AccountKitActivity.java:176)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.auth.api.phone.SmsRetriever" on path: DexPathList[[zip file "/data/app/com.myapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myappList item -1/lib/arm64, /vendor/lib64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
... 16 more
Suppressed: java.lang.ClassNotFoundException: com.google.android.gms.auth.api.phone.SmsRetriever
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 17 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available`
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..