я не могу синхронизировать c изображение из sqlite в mysql - PullRequest
0 голосов
/ 09 марта 2020

Я пытаюсь синхронизировать c из sqlite в mysql строку и изображение (blob). Но я понятия не имею, как это сделать с изображением. Кто-нибудь знает, как это сделать?

MainActivity {

..............

приватный файл createImageFile () throws IOException {

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
    );
    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

private void showCamera(){

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "ro.ase.woodapp",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);



        }
    }

}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        File imgFile = new File(mCurrentPhotoPath);
        if (imgFile.exists()) {
            thumbnail = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            ImageView myImage = findViewById(R.id.imageViewId);
            myImage.setImageBitmap(thumbnail);
            imageView.setRotation(90);

        }
    }


}




public static String getStringImage(Bitmap bmp) {

    ByteArrayOutputStream baoss = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baoss);
    byte[] imageBytess = baoss.toByteArray();
    String encodedImages = Base64.encodeToString(imageBytess, Base64.DEFAULT);
    return encodedImages;

}

public static byte[] getByteImage(ImageView image) {
    Bitmap thumbnail = ((BitmapDrawable)image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 95, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

private void loadNames() {

    names.clear();
    Cursor cursor  = db.getData();
    if (cursor.moveToFirst()) {
        do {
            Avize name = new Avize(

                    cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Numar)),
                    cursor.getBlob(cursor.getColumnIndex(DatabaseHelper.COLUMN_Photoo)),
                    cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_STATUS))
            );
            names.add(name);

        } while (cursor.moveToNext());
    }

}

public void saveNameToServer() throws IOException {
    final ProgressDialog progressDialog = new ProgressDialog(this);

        final String nr = et_nr.getText().toString().trim();

        final String imageOnline=getStringImage(thumbnail);
        final byte[] imageOffline = getByteImage(imageView);

    StringRequest  stringRequest = new StringRequest(Request.Method.POST, BASE_URL,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        try {
                            JSONObject obj = new JSONObject(response);
                            if (!obj.getBoolean("error")) {
                                saveNameToLocalStorage( nr, imageOffline ,NAME_SYNCED_WITH_SERVER);

                            } else {
                                saveNameToLocalStorage( nr, imageOffline ,NAME_SYNCED_WITH_SERVER);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        saveNameToLocalStorage( nr, imageOffline ,NAME_SYNCED_WITH_SERVER);

                    }
                }) {


            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();

                params.put("Numar", nr);
                params.put("imagee",imageOnline);
                progressDialog.setMessage("salvare...");
                progressDialog.show();
                progressDialog.dismiss();

                return params;

            }

        };

    VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}



private void saveNameToLocalStorage(String nr, byte[] photo, int status) {

    db.addName( nr ,photo,status);
    Avize n = new Avize( nr,photo,status);
    names.add(n);
    db.close();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_editor, menu);
    return true;
}

//syncs

@Override
protected void onStart() {
    super.onStart();
    registerReceiver(broadcastReceiver, new IntentFilter(DATA_SAVED_BROADCAST));
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);
}


@Override
public void onClick(View v) {

}

}

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

publi c Класс NetworkStateChecker extends BroadcastReceiver {

private Context context;
private DatabaseHelper db;

ImageView imageView;
Bitmap thumbnail;


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

    this.context = context;

    db = new DatabaseHelper(context);
    SQLiteDatabase dbb = db.getWritableDatabase();
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();


    //if there is a network
    if (activeNetwork != null) {
        //if connected to wifi or mobile data plan
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {

            //getting all the unsynced names
            Cursor cursor = db.getData();

            if (cursor.moveToFirst()) {
                do {
                    //calling the method to save the unsynced name to MySQL
                    saveName(
                            cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)),
                            cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Numar)),
                            cursor.getBlob(cursor.getColumnIndex(DatabaseHelper.COLUMN_Photoo))
                    );
                    db.deleteAll();

                } while (cursor.moveToNext());
            }
        }

    }
}


private void saveName(final int id,
         final String nr, final byte[] photo
) {

    //final String pkk = String.valueOf(MainActivity.getByteImage(imageView));

    StringRequest stringRequest = new StringRequest(Request.Method.POST, MainActivity.BASE_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        if (!obj.getBoolean("error")) {
                            //updating the status in sqlite
                            db.updateNameStatu(id, nr, photo, MainActivity.NAME_SYNCED_WITH_SERVER);
                            //sending the broadcast to refresh the list
                            context.sendBroadcast(new Intent(MainActivity.DATA_SAVED_BROADCAST));
                            // myDb.deleteAll();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<>();
            params.put("Numar", nr);
           //here is the problem

            return params;


        }

    };

    VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);

}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...