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 :)
Related
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);
}
});
}
}
I'm very new to RxJava and although I have seen multiple questions related to the one I am asking, I can't seem to piece them out altogether.
I have a PostPatrol object containing the following data:
public class PostPatrol {
String checkpoint_name;
String status;
int user;
String detail;
List<String> photos;
public PostPatrol(int cpId, String checkpoint_name, String detail, List<String> photos, String detail) {
this.cpId = cpId;
this.checkpoint_name = checkpoint_name;
this.detail = detail;
this.photos = photos;
this.status = status;
}
//getters and setters
}
What I'm trying to do now is to save a local list of photos into this PostPatrol record, but before that I have to upload the photos one by one with retrofit, get back a url and save that to a list which I then set as the photos for the PostPatrol record.
Once I save all the needed details for a certain PostPatrol record, I then send that again through retrofit.
Currently, I am doing it this way:
I pass the photos to a function to upload the image one by one
The function is like this:
private void uploadImage(List<String> photos, String folder, long requestId) {
final int size = photos.size();
final long reqId = requestId;
for (String path : photos) {
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
RequestBody folderName = RequestBody.create(MediaType.parse("text/plain"), folder);
ApiEndpointInterface apiEndpointInterface = RetrofitManager.getApiInterface();
Call<FileInfo> call4File = apiEndpointInterface.postFile(body, folderName);
call4File.enqueue(new ApiCallback<FileInfo>() {
#Override
protected void do4Failure(Throwable t) {
Log.d(TAG, t.toString());
snackbar = Snackbar.make(viewPendingRequestLayout, R.string.sb_image_upload_error, Snackbar.LENGTH_SHORT);
snackbar.show();
position++;
}
#Override
protected void do4PositiveResponse(Response<FileInfo> response) {
Log.d(TAG, "Uploaded Image");
FileInfo fileDetails = response.body();
listUrls.add(fileDetails.getImage());
position++;
if (position == size) {
postRequest(reqId);
position = 0;
}
}
#Override
protected void do4NegativeResponse(Response<FileInfo> response) {
String bodyMsg = "";
try {
bodyMsg = new String(response.errorBody().bytes());
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, bodyMsg);
snackbar = Snackbar.make(viewPendingRequestLayout, R.string.sb_image_upload_error, Snackbar.LENGTH_SHORT);
snackbar.show();
position++;
}
});
}
}
In do4PositiveResponse I use local variables to keep track whether I have uploaded all the photos before sending them to a function where the list is saved to the PostPatrol record. Sometimes though, I get problems where the photos aren't uploaded at all since it fires too late or too early.
This is my code onpostRequest()
private void postRequest(long requestId) {
if(mapIdPatrol.containsKey(requestId)){
PostPatrol postPatrol = mapIdPatrol.get(requestId);
postPatrol.setPhotos(listUrls);
postPatrolRequest(postPatrol, requestId);
}
listUrls = new ArrayList<>();
}
And finally my code on postPatrolRequest()
private void postPatrolRequest(final PostPatrol postPatrol, final long requestId){
ApiEndpointInterface apiEndpointInterface = RetrofitManager.getApiInterface();
Call<ResponseId> call4Handle = apiEndpointInterface.handleCheckpoint(postPatrol);
call4Handle.enqueue(new ApiCallback<ResponseId>() {
#Override
protected void do4Failure(Throwable t) {
finishUploading();
Log.d(TAG, t.toString());
}
#Override
protected void do4PositiveResponse(Response<ResponseId> response) {
RequestsDataSource.removeRequest(getApplication(),requestId);
finishUploading();
}
#Override
protected void do4NegativeResponse(Response<ResponseId> response) {
finishUploading();
String bodyMsg = "";
try {
bodyMsg = new String(response.errorBody().bytes());
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, bodyMsg);
snackbar = Snackbar.make(viewPendingRequestLayout, getResources().getText(R.string.sb_negative_response), Snackbar.LENGTH_SHORT);
snackbar.show();
}
});
}
I know this is very inefficient and so I would like your help so I can try to find a way around it with the use of RxJava. Thank you.
Is the operation atomic? i.e. if saving some of the photos via Retrofit fails, do you still have to proceed?
Anyway, roughly the solution will be something like that (pseudocode):
Observable<String> urls = Observable.from(listOfPhotoFilePaths)
.flatMapDelayError(path -> { return retrofit.save(readFile(path))})
.toList()
Observable<PostPatrol> pp = urls
.map(list -> { return new PostPatrol(list)})
this is my method to post in server with two string and one image here i van send data correctly but when i send without image no data can be sent i want to send string and image in all cases with image and without image.
private void Posts()
{
final StringRequest stringRequest=new StringRequest(Request.Method.POST, uploadeImageUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String Response=jsonObject.getString("response");
Toast.makeText(Post.this,Response,Toast.LENGTH_LONG).show();
imagepost.setImageResource(0);
imagepost.setVisibility(View.GONE);
} 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("name",editwriter.getText().toString().trim());
params.put("postcontent",editsubject.getText().toString().trim());
params.put("imagepost",imageToString(bitmap).trim());
return params;
}
};
Mysingletone.getInstance(Post.this).addToRequestque(stringRequest);
}
this is the code of imagetostring with method that get image
private void selectImages(){
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMG_REQUEST);
}
private String imageToString(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imgbystes = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgbystes,Base64.DEFAULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==IMG_REQUEST&&resultCode==RESULT_OK&&data!=null) {
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
imagepost.setImageBitmap(bitmap);
imagepost.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}}
code of php in server .
$con= mysqli_connect($host_name,$user_name,$user_pass,$dp_name);
if($con)
{
date_default_timezone_set("Asia/Muscat");
$datee= date("Y/m/d");//strip_tags(trim($_POST["date"]));
$timee= date("h:i:sa");//strip_tags(trim($_POST["time"]));
$dt=date("Ymd");
$tm=date("his");
$name=$_POST['name'];
$postcontent=$_POST['postcontent'];
$image = $_POST["image"];
$imagepost= $_POST["imagepost"];
$rnd = rand(0, 5000);
$imgname="imagepost".$dt.$tm.$rnd.".jpg";
$url = "http://devsinai.com/DrSiani/imageUploadPostDr/images/".$imgname;
$sql="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent','$url')";
$sql2="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent')";
$uploads_path="images/$imgname";
if(mysqli_query($con,$sql))
{
file_put_contents($uploads_path,base64_decode($imagepost));
echo json_encode(array('response'=>'Successfully'));
}
else {
echo json_encode(array('response'=>'fiald'));
}
}
mysqli_close($con);
?>
Can you add the code of imageToString(Bitmap bitmap)?
Edit:
First of all add if statement to getParams() method like this:
String imageString = imageToString(bitmap);
if(!imageString.equals("false")){
params.put("imagepost",imageToString(bitmap).trim());
}
and let imageToString method return "false" as String when error.
Edit your php script like this:
$con= mysqli_connect($host_name,$user_name,$user_pass,$dp_name);
if($con){
date_default_timezone_set("Asia/Muscat");
$datee= date("Y/m/d");//strip_tags(trim($_POST["date"]));
$timee= date("h:i:sa");//strip_tags(trim($_POST["time"]));
$dt=date("Ymd");
$tm=date("his");
$name=$_POST['name'];
$postcontent=$_POST['postcontent'];
if(isset($_POST["image"])){
$imageChecker = TRUE;
$imagepost= $_POST["imagepost"];
$rnd = rand(0, 5000);
$imgname="imagepost".$dt.$tm.$rnd.".jpg";
$url = "http://devsinai.com/DrSiani/imageUploadPostDr/images/".$imgname;
$sql="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent','$url')";
} else {
$imageChecker = FALSE;
$sql="INSERT INTO posts (name,postcontent) VALUE ('$name','$postcontent')";
}
$uploads_path="images/$imgname";
if(mysqli_query($con,$sql)){
if($imageChecker)
file_put_contents($uploads_path,base64_decode($imagepost));
echo json_encode(array('response'=>'Successfully'));
} else {
echo json_encode(array('response'=>'fiald'));
}
}
mysqli_close($con);
This Android app is using Android Studio. The function is to scan and display data from the beacon/eddystone. The app already functions and after the scanning stops, the data saves to the local file. I need to transfer the data to the server. How can i insert the volley coding to the mainacitivity.java. I tried to put under the stopscanning button, but it shows error. Im really beginners to learn about android studio.
Here is the coding:
private void stopScanning(Button scanButton) {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
String scanData = logString.toString();
if (scanData.length() > 0)
{
public class MainActivity extends AppCompatActivity {
//The values of these variables will be fetched by the file(Where you will store data)
private String PREFERENCE_SCANINTERVAL = "scanInterval";
private String PREFERENCE_TIMESTAMP = "timestamp";
private String PREFERENCE_POWER = "power";
private String PREFERENCE_PROXIMITY = "proximity";
private String PREFERENCE_RSSI = "rssi";
private String PREFERENCE_MAJORMINOR = "majorMinor";
private String PREFERENCE_UUID = "uuid";
private String PREFERENCE_INDEX = "index";
private String PREFERENCE_LOCATION = "location";
private String PREFERENCE_REALTIME = "realTimeLog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://beaconscanner.byethost33.com/beaconscanner.php";//This is the url of your server where you will be sending the data to.
//StringRequest is a class in the Volley Library.
//The constructor of this class has four parameters.
// 1 parameter is Request.Method.POST =this specifies the method type, That is post.
//2 parameter is the url you will be sending the request to.That is the server
//3 parameter is the response listener , It will listen for any response from your server . you will be able to fetch the response from the server using this.
//4 parameter is the error listener, it will listen for any error's during the connection or etc.
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Here you will be able to fetch the response coming from the server.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
//This is the method we override.
{
//This is method is used to send the data to the server for post methods. This method returns all the data you want to send to server. This is how you send data using Volley.
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("scanInterval",PREFERENCE_SCANINTERVAL);
params.put("timestamp",PREFERENCE_SCANINTERVAL);
params.put("power",PREFERENCE_POWER);
params.put("proximity",PREFERENCE_PROXIMITY);
params.put("rssi",PREFERENCE_RSSI);
params.put("majorMinor",PREFERENCE_MAJORMINOR);
params.put("uuid",PREFERENCE_UUID);
params.put("index",PREFERENCE_INDEX);
params.put("location",PREFERENCE_LOCATION);
params.put("realTimelog",PREFERENCE_REALTIME);
return params;
}
};//The constructor ends here.
Volley.newRequestQueue(this).add(request);// This is the main potion of this code. if you dont add this you will not be able to send the request to your server. this helps you to send it.
}
}
// Write file
fileHelper.createFile(scanData);
// Display file created message.
Toast.makeText(getBaseContext(),
"File saved to:" + getFilesDir().getAbsolutePath(),
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
} else {
// We didn't get any data, so there's no point writing an empty file.
Toast.makeText(getBaseContext(),
"No data captured during scan, output file will not be created.",
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
}
}
Please add your stacktrace. Also I guess that you want to send the data using the body not the params :). In that case, call the request using the following signature:
new JsonObjectRequest(Request.Method.POST, url, new JSONObject(bodyData), new Response.Listener<JSONObject>() { }
public void sendMyData(HashMap map) {
String url = "http://"....";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.INVISIBLE);
try {// to receive server response, in this example it's jsonArray
JSONArray jsonArray = new JSONArray(response);
//code
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}) {
#Override
public String getBodyContentType() { // if your server uses java restfull webservice , you have to override this content type
return "application/json";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {// parameters which should server receive
Map<String, String> parameters =map;
return parameters;
}
};
requestQueue.add(request);
}
I want to pass ArrayList via Intent to another activity. However, the code doesn't give any errors but List is always empty. Any idea what i'm doing wrong ? ty
Activity1
private ArrayList<ResimBean> rbList = new ArrayList<ResimBean>();
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] thumbArray = stream.toByteArray();
Uri selectedImageUri = data.getData();
String fotopath = getRealPathFromURI(selectedImageUri);
ResimBean rb = new ResimBean(Parcel.obtain());
// rb.setResim(bar);
rb.setThumbnail(thumbArray);
rb.setPath(fotopath);
rbList.add(rb);
Intent intent = new Intent(getApplicationContext(), ResimListActivity.class);
intent.putParcelableArrayListExtra("reslist",rbList);
startActivityForResult(intent, 100);
Activity2
Bundle extras = getIntent().getExtras();
if (extras != null) {
try {
Intent i = getIntent();
ArrayList<ResimBean> rbList = i.getParcelableArrayListExtra("reslist");
} catch (Exception ex) {
String msg = ex.getMessage();
}
}
Its not giving any error but list is always empty.
EDIT
Added the code how i fill in list.
EDIT 2
Something wrong with my Parcelable class or what ?
public class ResimBean implements Parcelable {
private int Id;
private int HataBildirimId;
private byte[] Resim;
private byte[] Thumbnail;
public byte[] getThumbnail() {
return Thumbnail;
}
public void setThumbnail(byte[] thumbnail) {
Thumbnail = thumbnail;
}
private String Path;
public String getPath() {
return Path;
}
public void setPath(String path) {
Path = path;
}
public int getHataBildirimId() {
return HataBildirimId;
}
public void setHataBildirimId(int hataBildirimId) {
HataBildirimId = hataBildirimId;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public byte[] getResim() {
return Resim;
}
public void setResim(byte[] resim) {
Resim = resim;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(HataBildirimId);
dest.writeByteArray(Resim);
dest.writeByteArray(Thumbnail);
}
public ResimBean(Parcel in) {
readFromParcel(in);
}
public void readFromParcel(Parcel in){
this.HataBildirimId = in.readInt();
this.Resim = new byte[in.readInt()];
this.Thumbnail = new byte[in.readInt()];
}
public static final Parcelable.Creator<ResimBean> CREATOR = new Parcelable.Creator<ResimBean>() {
#Override
public ResimBean createFromParcel(Parcel in) {
return new ResimBean(in);
}
#Override
public ResimBean[] newArray(int size) {
return new ResimBean[size];
}
};
The way you are showing, you create a new ArrayList<> and send it empty as extra via intent to the next activity.
Where exactly do you populate your ArrayList?
You should do something like this:
private ArrayList<ResimBean> rbList = new ArrayList<ResimBean>();
//populate rbList using adapter, then call intent
Intent intent = new Intent(getApplicationContext(), ResimListActivity.class);
intent.putParcelableArrayListExtra("reslist",rbList);
startActivityForResult(intent, 100);
Otherwise, the rbList you send as extra will always be empty. It sounds obvious but I don't know how you are doing it, so this is my best guess.
You can follow this tutorial:
http://aryo.lecture.ub.ac.id/android-passing-arraylist-of-object-within-an-intent/
I got it working like this
Bundle extras = this.getIntent().getExtras();
if (extras != null) {
try {
Intent i = getIntent();
ArrayList<ResimBean> rbList = (ArrayList<ResimBean>) i.getExtras().get("reslist");
Log.i("mytag", " "+i.getExtras().get("reslist").toString());
Log.i("mytag", " "+rbList.get(0).toString());
} catch (Exception ex) {
String msg = ex.getMessage();
}
}
With the rbList in Activity2 size=1,
With your code I was getting size=0