java .lang.NullPointerException: DatabaseHelperClass.DatabaseHelper splonline.Activity.spl.getDatabaseHelper () 'для пустой ссылки на объект - PullRequest
1 голос
/ 20 января 2020

publi c класс MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
Context context;
int Different_id_everytime = 0;
Bitmap bitmap;

// когда приложение находится на переднем плане pu sh уведомление

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("Body"));

    String strtitle = remoteMessage.getNotification().getTitle();
    String strmessage = remoteMessage.getNotification().getBody();
    String strimg = remoteMessage.getData().get("image");
    bitmap = getBitmapfromUrl(strimg);
   // String imageUri = remoteMessage.getData().get("image");
    Different_id_everytime = Different_id_everytime + 1;
    Intent intent = new Intent(this, FCMNotificationListActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,  Different_id_everytime, intent, PendingIntent.FLAG_ONE_SHOT);
    String channelId = "Default";
    Uri defaultSounfUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new  NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(strtitle)
            .setContentText(strmessage)
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(bitmap))/*Notification with Image*/
            .setAutoCancel(true)
            .setSound(defaultSounfUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }
    notificationManager.notify( Different_id_everytime, notificationBuilder.build());

    NotificationCompat.InboxStyle inboxStyle =
            new NotificationCompat.InboxStyle();
    String[] events = new String[6];
    // Sets a title for the Inbox in expanded layout
    //inboxStyle.setBigContentTitle("Event tracker details:");
    // Moves events into the expanded layout
    for (int i = 0; i < events.length; i++) {
        inboxStyle.addLine(events[i]);
    }
    // Moves the expanded layout object into the notification object.
    notificationBuilder.setStyle(inboxStyle);
    // Issue the notification here.
    notificationManager.notify(0,notificationBuilder.build());


    // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {

            String title = remoteMessage.getNotification().getTitle();
            String message = remoteMessage.getNotification().getBody();
            String imageUri = remoteMessage.getData().get("image");

            String strTitle = SessionManager.setMessage(context,title);
            String strMessage =  SessionManager.setTitle(context,message);

            bitmap = getBitmapfromUrl(imageUri);
            String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");
           // sendNotification(message, bitmap,);

// создать один класс модели для сохранения pu sh уведомление и ошибка для нулевой ссылки

            try {
                NotificationModel notificationModel = new NotificationModel();
                notificationModel.setTitle(strtitle);
                notificationModel.setMessage(strmessage);
                notificationModel.setImage(imageUri);

                spl.getInstance().getDatabaseHelper().insertNotification(notificationModel);
            }catch(Exception e){
                e.printStackTrace();
            }
            sendNotification(message,title,bitmap,TrueOrFlase);
            if (TextUtils.isEmpty(title)){
                title = getString(R.string.app_name);
            }
            // Check if message contains a notification payload.
            if (remoteMessage.getNotification() != null) {
                Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            }
        }
}

// когда приложение находится в фоновом режиме pu sh уведомление

private void sendNotification(String message, String title,Bitmap image, String TrueOrFalse) {
    Intent intent = new Intent(this, FCMNotificationListActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("KEY_ISNOTIFICATION", true);
    intent.putExtra("title",title);
    intent.putExtra("message",message);
    intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
        PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(message)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(image))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Different_id_everytime, notificationBuilder.build());

// для отображения уведомления в стиле входящих сообщений

    NotificationCompat.InboxStyle inboxStyle =
            new NotificationCompat.InboxStyle();
    String[] events = new String[6];
    // Sets a title for the Inbox in expanded layout
    //inboxStyle.setBigContentTitle("Event tracker details:");
    // Moves events into the expanded layout
    for (int i = 0; i < events.length; i++) {
        inboxStyle.addLine(events[i]);
    }
    // Moves the expanded layout object into the notification object.
    //mBuilder.setStyle(inBoxStyle);
    notificationBuilder.setStyle(inboxStyle);
    // Issue the notification here.
    //mNotificationManager.notify(mId, mBuilder.build());
    notificationManager.notify(Different_id_everytime,notificationBuilder.build());
}

// для отображения изображения в уведомлении

/*
 *To get a Bitmap image from the URL received
 * */
public Bitmap getBitmapfromUrl(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    }
}

}

//to save data in database
public class spl extends Application {

    private SharedPreferences sharedPreferences;
    private DatabaseHelper databaseHelper;

    private static spl sInstance;
    private static AppCompatActivity sActivity;

    public static AppCompatActivity getsActivity() {
        return sActivity;
    }

    public static void setsActivity(AppCompatActivity sActivity) {
        spl.sActivity = sActivity;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sharedPreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
        databaseHelper = new DatabaseHelper(getApplicationContext());
        databaseHelper.openDataBase();
        sInstance = this;
//        if (Utils.isInternetAvail(getApplicationContext())) {
//            Intent intent = new Intent(getApplicationContext(), StateService.class);
//            startService(intent);
//        }
    }

    public static spl getInstance() {
        return sInstance;
    }

    public DatabaseHelper getDatabaseHelper() {
        return databaseHelper;
    }

    public SharedPreferences getSharedPreferences() {
        return sharedPreferences;
    }

    public void setSharedPreferences(SharedPreferences sharedPreferences) {
        this.sharedPreferences = sharedPreferences;
    }
}

//Databse helperclass


public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = DatabaseHelper.class.getSimpleName();
    private Context context;
    private SQLiteDatabase database;

    /**
     * Constructor
     * *
     */
    public DatabaseHelper(Context context) {
        super(context, DBUtils.DATABASE_NAME, null, DBUtils.DATABASE_VERSION);
        this.context = context;

    }

    /**
     * Create database tables if it does not exists.
     * *
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DBUtils.DB_CREATE_NOTIFICATION_TABLE);
        this.database = db;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * Open Databases
     * *
     */
    public void openDataBase() throws SQLException {
        database = this.getWritableDatabase();
    }

    @Override
    public synchronized void close() {
        // if (database != null && database.isOpen())
        // database.close();
        // super.close();
    }

    /**
     * Insert NotificationList
     *
     * @param
     */

    public void insertNotification(NotificationModel notificationModel) {
        if (!database.isOpen()) {
            openDataBase();
        }
        try {
            // database.beginTransaction();
            ContentValues values = new ContentValues();
            values.put(DBUtils.COLUMN_NOTIFICATION_MESSAGE, notificationModel.getMessage());
            values.put(DBUtils.COLUMN_NOTIFICATION_TITLE, notificationModel.getTitle());
            values.put(DBUtils.COLUMN_NOTIFICATION_IMAGE, notificationModel.getImage());
            database.insert(DBUtils.NOTIFICATION_TABLE, null, values);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close();
            SQLiteDatabase.releaseMemory();
        }
    }


    /**
     * Delete  from Notificaton
     */
    public void deleteNotification() {
        if (!database.isOpen()) {
            openDataBase();
        }
        try {
            database.delete(DBUtils.NOTIFICATION_TABLE, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }


    /**
     * Get NotificationList
     *
     * @return
     */

    public ArrayList<NotificationModel> getNotificationList() {

        final ArrayList<NotificationModel> notificationlist = new ArrayList<NotificationModel>();
        if (!database.isOpen()) {
            openDataBase();
        }
        Cursor cursor = null;

        try {

            cursor = database.query(DBUtils.NOTIFICATION_TABLE, new String[]{"*"}, null, null, null, null, DBUtils.COLUMN_NOTIFICATION_ID + " DESC");

            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    NotificationModel notificationModel=new NotificationModel();
                    notificationModel.setTitle(cursor.getString(cursor.getColumnIndex(DBUtils.COLUMN_NOTIFICATION_TITLE)));
                    notificationModel.setMessage(cursor.getString(cursor.getColumnIndex(DBUtils.COLUMN_NOTIFICATION_MESSAGE)));
                    notificationModel.setImage(cursor.getString(cursor.getColumnIndex(DBUtils.COLUMN_NOTIFICATION_IMAGE)));
                    notificationlist.add(notificationModel);
                    cursor.moveToNext();
                }
                notificationlist.trimToSize();
            }
        } catch (Exception e) {

        } finally {

            close();
            if (cursor != null) {
                cursor.close();
                SQLiteDatabase.releaseMemory();
            }
        }
        return notificationlist;
    }

    }
...