Store multiple Image from programatically added ImageView with POST - android

I have the EditText and Button, where I can put number in EditText of how many ImageView I want to display on my app. Let say, I write 3 then it will display 3 ImageViews on Layout and it works just fine.
I successfully take pictures and display it on those ImageViews.
container.removeAllViews();
for (int i = 1; i <= no; i++) {
final View addView = layoutInflater.inflate(R.layout.shelter_row, null);
txtV1 = (TextView) addView.findViewById(R.id.txtV1);
txtV1.setText(String.valueOf(i));
addView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imgLantai = (ImageView)view.findViewById(R.id.imgLantai);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_10);
}
});
container.addView(addView);
}
I try to get the bitmap and display it on ImageView. It works
if(requestCode == CAMERA_10){
if(resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
byte[] byte_arr = output.toByteArray();
mbitmap10 = Base64.encodeToString(byte_arr, Base64.DEFAULT);
imgLantai.setImageBitmap(bitmap);
}else if(resultCode == RESULT_CANCELED){
}
}
By using submit button I try to insert the bitmap to database using POST
public void insertFoto(){
final String URL = "http://www.lineitopkal.com/genset/insert_site.php";
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.contains("success")) {
loading.dismiss();
Toast.makeText(getApplicationContext(),mbitmap01,Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Toast.makeText(getApplicationContext(),"Data gagal disimpan",Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("lantai",mbitmap10);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(stringRequest);
}
I can't seem store all the images (the mbitmap10 one) in database with POST. Only the latest image was stored. Should I use array to store the image? If so how do I implement it? Or there is other way?

NOTE: This is general pseudo-code to demonstrate a concept and answer a general question
1) Put an empty array of bitmaps in your app:
Bitmap[] allBitmaps = new Bitmap[];
2) Each time that a new image is assigned to one of the image views, add it to the array in the position corresponding to the image view -- allBitmaps[2] = imageView2.getBitmap...
3) Then, when the user clicks submit, do something like this:
#Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
// int paramNumber = 0;
// for (bitmap : allBitmaps) {
// params.put"paramNumber.toString()",bitmap);
// paramNumber ++;
// }
return params;
}

Related

Save QR code into Google Spreadsheet with Android Studio

im developing an app to create products and save them directly to a Google Spreadsheet. My problem is that the name and brand are saving correctly, but i cant find a way to also save the QR code. The QR code is encrypted using AES encryption.
Here is the CreateProduct.java activity:
public class CreateProduct extends AppCompatActivity {
EditText editBrand,editName;
Button buttonCreateProduct;
ImageView imageQR;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_product);
editBrand = findViewById(R.id.product_brand);
editName = findViewById(R.id.product_name);
buttonCreateProduct = findViewById(R.id.button_create);
imageQR = findViewById(R.id.image_qr);
buttonCreateProduct.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if (!editBrand.getText().toString().isEmpty()&&!editName.getText().toString().isEmpty()){
String qrTextBrand;
String qrTextName;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
qrTextBrand = editBrand.getText().toString();
qrTextName = editName.getText().toString();
BitMatrix bitMatrix = multiFormatWriter.encode(Crypto.encrypt("Marca: "+ qrTextBrand +
"\nNombre: "+qrTextName), BarcodeFormat.QR_CODE, 300, 300);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
imageQR.setImageBitmap(bitmap);
}catch (Exception e){e.printStackTrace();}
}
addProduct();
}
});
}
public void addProduct(){
String sBrand = editBrand.getText().toString();
String sName = editName.getText().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://script.google.com/macros/s/AKfycbz4Tu7febkY3EGhQfVvXIa_GGKFgCZbPza7MMZJeEnEPllQEDV9SyaUWeSTyhOq8cq7/exec", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("action", "addProduct");
params.put("vBrand",sBrand);
params.put("vName",sName);
return params;
}
};
int socketTimeOut = 50000;
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
And the AppScript code:
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1Utf6HKqvaSoUd_Ep9vu2qqIKSqHwYbi13jDGrz9QBzo/edit?usp=sharing");
var sheet = ss.getSheetByName("ProductData");
function doPost(e) {
var action = e.parameter.action;
if (action == "addProduct") {
return addItem(e);
}
}
function addItem(e) {
var ID = sheet.getLastRow();
var Brand = e.parameter.vBrand;
var Name = e.parameter.vName;
var Date = new Date();
var QR = e.parameter.vQR;
sheet.appendRow([ID, Brand, Name, Date, QR]);
return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT);
}

How to upload multiple images using multi-part in Volley in Android

I want to upload multiple images to server using multi-part, I didn't get proper code, anyone please help me to fix solve my problem.If i send as base64 format ,backend team cant able to get my image. Thats' why I go with multipart. Either Volley or Asynctask.
I tried this code from this link
https://www.simplifiedcoding.net/upload-image-to-server/
But multiple images I dont know how to do.
Main.Java
package com.getspot.getspot.imagerestapi;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if everything is ok we will open image chooser
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//displaying selected image to imageview
imageView.setImageBitmap(bitmap);
//calling the method uploadBitmap to upload image
uploadBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
Log.i("AS","--"+byteArrayOutputStream.toByteArray());
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {
//getting the tag from the edittext
final String tags = editTextTags.getText().toString().trim();
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, ServerUtils.Gs_Clock_Image,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Log.i("AS","obj--"+obj);
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("AS","error--"+error);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("gs_userId", "6");
return params;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
Log.i("AS","imagename--"+imagename);
Log.i("AS","getFileDataFromDrawable(bitmap)--"+getFileDataFromDrawable(bitmap));
params.put("gs_task_image", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
Note:While passing the byte-array in gs_text_image,in that how can i send multiple images.I referred that above link.Please help me
I'll show you how I do it (particular case ofc, but it might give you an idea)
So, first of all you need the method interface which will look like this:
#Multipart
#POST(RestClient.UPLOAD_PICTURES_FOR_ORDER)
Call<YourTypeOfResponse> uploadPictures(#Part("images[]") RequestBody[] file, #Part MultipartBody.Part[] images);
now, you will have to prepare the files(images) that you have, for the request
private void multiparts(){
RequestBody reqFullPicFile;
MultipartBody.Part filepart;
RequestBody filename;
images = new MultipartBody.Part[files.size()];
filenameImages = new RequestBody[files.size()];
for (int file = 0; file < files.size(); file++){
reqFullPicFile = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(file));
filepart = MultipartBody.Part.createFormData("full_picture", files.get(file).getName(), reqFullPicFile);
filename = RequestBody.create(MediaType.parse("text/plain"), files.get(file).getName());
images[file] = filepart;
filenameImages[file] = filename;
}
}
And, in the end, make the request with the created Multiparts (in this case images & filenameImages)
private void uploadPicturesReq(){
if (files != null) {
multiparts();
RestClient.getApi().uploadPictures(filenameImages, images)
.enqueue(new Callback<PicturesResponse>() {
#Override
public void onResponse(Call<PicturesResponse> call, Response<PicturesResponse> response) {
if (response.isSuccessful() && response.code() == 200) {
// here you can handle the response from server
}
}
#Override
public void onFailure(Call<PicturesResponse> call, Throwable t) {
Log.e(TAG, "-=onFailure=- " + t.getMessage(), t);
}
});
}
}

Unable to upload image to the server it show zero byte?

When I'm taking an image from gallery and want to insert into server, it puts the image with zero byte size. And in the table I have two columns, rollno and image. I get the rollno value from shared preference but it does not put the rollno in the database table, rollno column shows empty.
Help me to resolve this.
Here is my code
public class ImageEditActivity extends AppCompatActivity implements View.OnClickListener {
ImageView image;
Button btn_cancel_edit,btn_done_edit;
Bitmap bitmap;
SharedPreferences sp;
String rollno;
String KEY_Rollno = "rollno";
String KEY_IMAGE = "image";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_edit);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
image=(ImageView)findViewById(R.id.image);
bitmap=ProfileActivity.bitmap;
image.setImageBitmap(bitmap);
btn_done_edit = (Button) findViewById(R.id.btn_done_edit);
btn_cancel_edit = (Button) findViewById(R.id.btn_cancel_edit);
btn_done_edit.setOnClickListener(this);
btn_cancel_edit.setOnClickListener(this);
sp=getSharedPreferences("rajput",MODE_PRIVATE);
rollno=sp.getString("rollno",null);
}
#Override
public void onClick(View v) {
if(v == btn_done_edit){
uploadImage();
}
if(v == btn_cancel_edit){
onBackPressed();
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
String UPLOAD_URL ="http://aptronnoida.com/applock/image_insert.php";
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.GET, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(ImageEditActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(ImageEditActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_Rollno,rollno);
params.put(KEY_IMAGE, image);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
public void onBackPressed(){
super.finish();
}
}
Please try below working code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL = "http://coderzheaven.com/sample_file_upload/upload_image.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
editTextName = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put("Roll_NO", "5");
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
}
}
Reference source: http://www.coderzheaven.com/2011/04/25/android-upload-an-image-to-a-server/
Try changing it to PNG and reduce the compression in the following line
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
To
bmp.compress(Bitmap.CompressFormat.PNG, 80, baos);

Android: not able to add listview items dynamically through volley

Hi I'm working on CardSwipe functionality like tinder. (For understanding see the attached image)
For this i followed this code, when using static data like bellow, I'm successfully adding items in ListView
private void loadCards2(){
itemsaArrayList = new ArrayList<>();
for(int i = 0; i < 10; i++){
CardSwipeItems items = new CardSwipeItems();
items.setCardImageUrl("http://i.ytimg.com/vi/PnxsTxV8y3g/maxresdefault.jpg");
items.setCardDescription("But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness.");
itemsaArrayList.add(items);
}
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
myAppAdapter = new CardSwipeAdapter(itemsaArrayList, CardSwipeActivity.this);
flingContainer.setAdapter(myAppAdapter);
initControlls();
}
But when I'm trying to add the items dynamically by using volley means, items are not adding in the ListView. (For this volley
please see the loadCards() method in the CardSwipeActivity)
I tried lot of approaches to load the items in the list view dynamically. For ex: I used Thread (For code see this) and i also used Handler (For code see this) but I'm not able to add the items in ListView dynamically
If any one know the solution for this means please tell me. Thank you.......
Edit
*My method*
private void loadCards(){
String Url = "myApi";
Log.e("Url", Url);
final ProgressDialog dialog = ProgressDialog.show(CardSwipeActivity.this, null, null);
ProgressBar spinner = new android.widget.ProgressBar(CardSwipeActivity.this, null,android.R.attr.progressBarStyle);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#009689"), android.graphics.PorterDuff.Mode.SRC_IN);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(spinner);
dialog.setCancelable(false);
dialog.show();
StringRequest request = new StringRequest(Request.Method.GET, Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
if(response != null && !response.startsWith("<HTML>")){
Log.e("OnResponse", response);
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray.length() > 0){
itemsaArrayList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++){
JSONObject singleObj = jsonArray.getJSONObject(i);
String imgId = singleObj.getString("avatar_file_id");
String name = singleObj.getString("name");
CardSwipeItems items = new CardSwipeItems();
Log.e("imgId", imgId);
Log.e("name", name);
items.setCardImageUrl(imgId);
items.setCardDescription(name);
itemsaArrayList.add(items);
}
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
myAppAdapter = new CardSwipeAdapter(itemsaArrayList, CardSwipeActivity.this);
flingContainer.setAdapter(myAppAdapter);
initControlls();
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Log.e("Internet", "Internet");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
if(error != null){
Log.e("error", error.toString());
}else{
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("token","b32daf7b50c7f21dba80dd0651174e3839c22f56");
params.put("user_id","386");
Log.e("Headers", "**********Headers*************");
Log.e("token","b32daf7b50c7f21dba80dd0651174e3839c22f56");
Log.e("user_id","386");
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(CardSwipeActivity.this);
queue.add(request);
queue.getCache().remove(Url);
}
You can add items dynamically to the adapter by addding items to the list you passed originally to adapter like this:
itemsaArrayList.add(items);
than you need to notify the adapter like this from your UI thread:
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
And to call it on the UI-Thread, use have to use runOnUiThread() of Activity. Then only, notifyDataSetChanged() will work.
Also have a look at this post
If you are getting response from server then try to move below line from onResponse method to onCreate method.
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
Hope this will work

How to upload Android sqlite BLOB data into MySQL BLOB

I am developing a project where user store some information and image into SQLite database. The image is stored as BLOB data. Now I want to upload all data into my MySQL database. I am using Volley to upload all rows one by one from SQLite to MySQL server with a AsyncTask calling a Web API.
Everything working fine without the image BLOB data. I do not know is there any way to upload blob data using Volley.
I have search a lot into StackOverflow but did not get any solution, please help me.
I am giving some code example to make my question better understandable.
Here is my function calling in a AsyncTask:
/**
* function to upload data into server
* */
private void SyncTaskDoInBack(final dataDB data) {
// Tag used to cancel the request
String tag_string_req = "Inserting Online";
StringRequest strReq = new StringRequest(Method.POST, AppConfig.API_LINK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
Log.d(TAG, "Success");
} else {
// Error in found
String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("ID", data._id);
params.put("PersonName", data.pName);
params.put("Photo", data.photo.toString());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
My "dataDB" Class is as follows:
public class dataDB implements Comparable<dataDB>{
String _id = null;
String pName = null;
byte[] photo = null;
#Override
public int compareTo(dataDB o) {
//return title.toLowerCase().compareTo(o.title.toLowerCase());
return 0;
}
}
List Data Model class is follows:
public class ListDataModel {
private int _id;
private String name;
private byte[] image;
public ListDataModel() { }
public ListDataModel(String name, String thumbnailUrl) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getImage() {
return this.image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
After searching a lot into StackOverflow, I have come up with the following formula, which appears to produce the camera image into Base64 String and Vice-versa. Hope this will help others.
I am using Apache Commons Codec for Base64 encode/decode from here http://commons.apache.org/proper/commons-codec/ (I think one can use Android default Base64 class too, I am using this for other purposes also)
Here is my onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap myImage = extras.getParcelable("data");
ByteArrayOutputStream bao = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.JPEG, 90, bao);
imageInByte = bao.toByteArray();
imageInBase64Str = Base64.encodeBytes(imageInByte); // using internal class
}
break;
}
}
Then I'm passing the Base64 String imageInBase64Str to my insert statement of SQlite and MySQL online database.
When getting image Base64 encoded data from SQLite or MySQL to view, I'm processing my image like the following way:
try {
byte[] decodedByte = Base64.decode(imageData, 0);
theImage = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}catch (IOException io){
Log.d("ViewRecord",io.getMessage());
}
That's it :)

Categories

Resources