I'm trying to upload objects form my client sq-lite database to MSSQL using Retrofit 2 & Web API 2.
The app is working without any issue if I assign null
or new byte[1000]
to the visit. Image, but whenever its assigned value is retrieved from the sq-lite database I get error response code 400
{
"Message": "The request is invalid.",
"ModelState": {
"visit.Image[0]": [
"An error has occurred."
],
"visit.Image[1]": [
"An error has occurred."
]
}
}
Here is my model in android:
public class Visit {
public int VisitId;
public String DealerMId;
public byte[] Image; // read image from database (blob data type)
}
This is the code how I retrieve values from database and making Visit object
public Visit getVisitByVisitId(long visitId) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_VISIT + " WHERE "
+ KEY_ID + " = " + visitId;
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
Visit visit = new Visit();
visit.VisitId = c.getInt(c.getColumnIndex(KEY_ID));
visit.DealerMId = c.getString(c.getColumnIndex(KEY_DEALER_MID));
visit.Image= c.getBlob(c.getColumnIndex(KEY_PICTURE));
return visit ;
}
And this is the used interface from retrofit service:
@POST("visits/PostVisit")
public Call<Integer> postVisit(@Body Visit visit);
This is the activity code:
Visit vistit = db.getVisitById(1) ;
// Note that : every thing working fine
// if visit.Image = null or visit.Image = new byte[1000] or visit.Image = new byte[]{1,4,3 ..}
// but I am receiving error 400 when visit.Image contains value from database
Call<Integer> call = RetrofitService.postVisit(visit);
call.enqueue(new Callback<Integer>() {
@Override
public void onResponse(Call<Integer> call, Response<Integer>response){
//....
}
@Override
public void onFailure(Call<Integer> call, Throwable t) {
//....
}
});
And this Web API 2 code
[HttpPost]
public IHttpActionResult PostVisit(Visit visit)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Visits.Add(visit);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (VisitExists(visit.VisitId))
{
return Ok(-1);
}
else
{
throw;
}
}
return Ok(visit.VisitId);
}
The below screenshot from android studio shows the retrieved content of the Visit.Image, and I am sure there is no problem with the content it self because I can read it on my android app in ImageView.