Как я могу исправить ошибку: Fatal Exception: java .lang.NoClassDefFoundError - PullRequest
0 голосов
/ 29 апреля 2020

Я постоянно получаю эту ошибку в базе данных. показывает неправильный метод на скриншоте. Я не понял, почему он совершил ошибку. Я не думаю, что есть какая-либо ошибка в линии с методом. Цель метода - присвоить данным sharedPreferences значения по умолчанию в ночное время. Только то. Заранее спасибо.

Снимок экрана: https://i.stack.imgur.com/SMHyH.png

Класс AlarmReceiver


    public class AlarmReceiver extends BroadcastReceiver {
    int notificationID;
    private SharedPreferences.Editor editor;
    private SharedPreferences.OnSharedPreferenceChangeListener sharedpreflistener;
    private SharedPreferences sharedPreferences;
    private String MAIN_DATA = "com.xxx.xxx.MAIN";

   @RequiresApi(api = Build.VERSION_CODES.O)
    public void createNotification(Context context, String title, String text, String bigtext, int icon, int i, String channelID, int color,int[] saatler,int[] dklar) {
        Intent myintent = new Intent(context, SplashActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context.getApplicationContext(), channelID);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationChannel channel = new NotificationChannel(channelID, channelID, NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription(channelID);
        Objects.requireNonNull(notificationManager).createNotificationChannel(channel);


        mbuilder
                .setSmallIcon(icon)
                .setChannelId(channelID)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setChannelId(channelID)
                .setColor(color)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(title)
                .setContentText(text)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .setContentInfo("Info")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(bigtext));
        notificationManager.notify(i, mbuilder.build());



        AlarmHelper alarmHelper=new AlarmHelper();
        alarmHelper.helper(context,saatler,dklar);

    }
    public void waterDataClear(Context context) {
        sharedPreferences = context.getSharedPreferences(MAIN_DATA, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.putFloat(SU_KAYIT,  0.0f);
        editor.putBoolean(SU_DIALOG, true);
        editor.putInt(SU_ML, 0);
        editor.apply();

        WaterAlarmClear waterClear=new WaterAlarmClear();
        waterClear.alarmClear(context);

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context context, Intent intent) {

        sharedPreferences = context.getSharedPreferences(MAIN_DATA, Context.MODE_PRIVATE);


        Bundle extras = intent.getExtras();
        notificationID = Objects.requireNonNull(extras).getInt("NotificationID");

        if (notificationID == 6) {
            createNotification(context, context.getString(R.string.tracker_title), trackertxt, trackertxt, R.mipmap.ic_launcher, 6, context.getString(R.string.weight_channel), context.getResources().getColor(R.color.colorhedef), saatler, dklar);
            notificationID = 0;
        }


        if (notificationID == 10) {
            waterDataClear(context);
            notificationID = 0;
        }


    }


Манифест

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.xxx.xxx"
    android:installLocation="auto">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SET_ALARM" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:resizeableActivity="false"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning,InnerclassSeparator,UnusedAttribute"
        tools:targetApi="n">

        <activity
            android:name=".MainActivity"
            android:windowSoftInputMode="stateAlwaysHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>


        <receiver android:name=".AlarmReceiver" />
    </application>

</manifest>

Fatal Exception: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/app/NotificationChannel;
       at androidx.core.app.NotificationCompat$Builder.setSmallIcon(NotificationCompat.java)
       at com.xxxx.xxxx.AlarmReceiver.waterDataClear(AlarmReceiver.java)
       at android.app.ActivityThread.handleReceiver(ActivityThread.java:2739)
       at android.app.ActivityThread.access$1800(ActivityThread.java:157)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1428)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5437)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.3'
        classpath 'com.google.gms:google-services:4.3.3'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.0.0'
    }
}

allprojects {
    repositories {
        maven {url 'https://jitpack.io'}
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 10
        versionName '1.0.5.5'
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.2.0-alpha06'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.google.firebase:firebase-core:17.4.0'
    implementation 'com.google.firebase:firebase-ads:19.1.0'
    implementation 'com.google.android.gms:play-services-ads:19.1.0'
    implementation 'com.google.firebase:firebase-analytics:17.4.0'
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
public class WaterAlarmClear {

    public void alarmClear(Context context){

        Calendar suthatDay = Calendar.getInstance();
        Calendar sutoday = Calendar.getInstance();

        int sutoday_month_day = sutoday.get(Calendar.DAY_OF_MONTH);
        int sutoday_month = sutoday.get(Calendar.MONTH);
        int sutoday_year = sutoday.get(Calendar.YEAR);
        suthatDay.setTime(new Date(0)); /* reset */

        suthatDay.set(Calendar.DAY_OF_MONTH, sutoday_month_day);
        suthatDay.set(Calendar.MONTH, sutoday_month); // 0-11 so 1 less
        suthatDay.set(Calendar.YEAR, sutoday_year);
        suthatDay.set(Calendar.HOUR_OF_DAY, 23);
        suthatDay.set(Calendar.MINUTE, 50);
        suthatDay.set(Calendar.SECOND, 0);
        suthatDay.set(Calendar.MILLISECOND, 0);
        if (suthatDay.getTimeInMillis() - sutoday.getTimeInMillis() < 0) {
            suthatDay.set(Calendar.DAY_OF_MONTH, sutoday_month_day + 1);
        } else {
            suthatDay.set(Calendar.DAY_OF_MONTH, sutoday_month_day);
        }


        AlarmManager sualarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent suintent = new Intent(context, AlarmReceiver.class);
        suintent.putExtra("NotificationID", 10);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 23, suintent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= 23) {
            Objects.requireNonNull(sualarmManager).setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, suthatDay.getTimeInMillis(), pendingIntent);
        } else if (Build.VERSION.SDK_INT >= 19) {
            Objects.requireNonNull(sualarmManager).setExact(AlarmManager.RTC_WAKEUP, suthatDay.getTimeInMillis(), pendingIntent);
        } else {
            Objects.requireNonNull(sualarmManager).set(AlarmManager.RTC_WAKEUP, suthatDay.getTimeInMillis(), pendingIntent);
        }

    }
}

Ответы [ 2 ]

0 голосов
/ 29 апреля 2020

Если это развернуто на любой версии ОС

NotificationChannel поступило 26, поэтому класс не найден.

0 голосов
/ 29 апреля 2020

Я обновил ваш приемник. попробуйте:

    public class AlarmReceiver extends BroadcastReceiver {
     int notificationID;
     private SharedPreferences.Editor editor;
     private SharedPreferences.OnSharedPreferenceChangeListener sharedpreflistener;
     private SharedPreferences sharedPreferences;
     private String MAIN_DATA = "com.xxx.xxx.MAIN";



     public void createNotification(Context context, String title,
                                String text, String bigtext, 
                                int icon, int i, String channelID,
                                int color,int[] saatler,int[] dklar) {

     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

     if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

        NotificationChannel channel = new NotificationChannel(channelID, channelID, NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription(channelID);
        notificationManager.createNotificationChannel(channel);

     }

     Intent myintent = new Intent(context, SplashActivity.class);

     PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT);

     NotificationCompat.Builder notification = new NotificationCompat.Builder(context.getApplicationContext(), channelID)
            .setSmallIcon(icon)
            .setChannelId(channelID)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setChannelId(channelID)
            .setColor(color)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setContentTitle(title)
            .setContentText(text)
            .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
            .setContentInfo("Info")
            .setStyle(new NotificationCompat.BigTextStyle()
             .bigText(bigtext));

    AlarmHelper alarmHelper=new AlarmHelper();
    alarmHelper.helper(context,saatler,dklar);
    notificationManager.notify(i, notification);

  }
  public void waterDataClear(Context context) {
      sharedPreferences = context.getSharedPreferences(MAIN_DATA, Context.MODE_PRIVATE);
      editor = sharedPreferences.edit();
      editor.putFloat(SU_KAYIT,  0.0f);
      editor.putBoolean(SU_DIALOG, true);
      editor.putInt(SU_ML, 0);
      editor.apply();

      WaterAlarmClear waterClear=new WaterAlarmClear();
      waterClear.alarmClear(context);

  }

  @Override
  public void onReceive(Context context, Intent intent) {

      sharedPreferences = context.getSharedPreferences(MAIN_DATA, Context.MODE_PRIVATE);

      Bundle extras = intent.getExtras();
      notificationID = Objects.requireNonNull(extras).getInt("NotificationID");

      if (notificationID == 6) {
        createNotification(context, context.getString(R.string.tracker_title),
        trackertxt, trackertxt, R.mipmap.ic_launcher, 6,
        context.getString(R.string.weight_channel),
        context.getResources().getColor(R.color.colorhedef), saatler, dklar);
        notificationID = 0;
    }


    if (notificationID == 10) {
        waterDataClear(context);
        notificationID = 0;
    }

}
...