before i'm so sorry if my post maybe duplicated, but i have another case in this problem, i wanna show an image that i capture from camera in ImageView and after that i save it or upload it into my json file, but after i take the picture, it's stopped in Log.i ("Error", "Maybe Here");
no error in my code but the image cant saved into thumbnail ImageView
Here is my code, i'm using Asyntask
public class StoreTodoDisplayActivity extends AppCompatActivity {
public Context ctx;
Uri imgUri;
ActionBar actionBar;
public static CategoryData category_data_ar[];
public static CategoryData category_data_ar2[];
String targetUrl;
String path = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/img11.jpg";
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
RestData restData;
ImageData imgData;
public Uri mCapturedImageURI;
public String image_path = "";
Toolbar toolbar;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera_display);
targetUrl = Config.getEndPointUrl();
ctx = this.getApplicationContext();
System.gc();
set_Spinner();
set_Spinner2();
// Toolbar show
toolbar = (Toolbar) findViewById(R.id.actionbarCameraDisplay);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar abar = getSupportActionBar();
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
// Back button pressed
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
settings = getSharedPreferences(PREFS_NAME, 0);
}
#Override
public void onResume() {
if (!UserInfo.loginstatus) {
finish();
}
super.onResume();
}
public void get_pic(View view) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 12345);
}
public void save_img(View view) {
EditText te = (EditText) findViewById(R.id.camera_display_txt);
String msg = te.getText().toString();
Spinner sp = (Spinner) findViewById(R.id.spinner1);
int catid = (int) sp.getSelectedItemId();
String cat = category_data_ar[catid].catid;
Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
int catid2 = (int) sp2.getSelectedItemId();
String cat2 = category_data_ar2[catid2].catid;
ImageUploader uploader = new ImageUploader("display", msg, cat, cat2);
uploader.execute(Config.getEndPointUrl() + "/uploadimage.json");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if (resultCode == RESULT_OK) {
getimage getm = new getimage();
getm.execute();
}
}
}
public void set_Spinner2() {
Spinner sp = (Spinner) findViewById(R.id.spinner2);
sp.setVisibility(View.VISIBLE);
CatProductHelper helper = new CatProductHelper(ctx);
category_data_ar2 = helper.getCategories();
String[] isidesc = new String[category_data_ar2.length];
for (int k = 0; k < category_data_ar2.length; k++) {
isidesc[k] = category_data_ar2[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + category_data_ar2[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
public void set_Spinner() {
// set list activity
Spinner sp = (Spinner) findViewById(R.id.spinner1);
category_data_ar = StoreInfo.storeDisplayCat;
try {
String[] isidesc = new String[category_data_ar.length];
Log.i("toTry", "Normal");
for (int k = 0; k < category_data_ar.length; k++) {
isidesc[k] = category_data_ar[k].catdesc;
Log.i("AndroidRuntime", "Desc -- "
+ category_data_ar[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
} catch (Exception e) {
Log.i("toCatch", "NULL EXCEPTION");
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
CategoryData[] displayCat = helperDisplayCat.getCategories();
String[] isidesc = new String[displayCat.length];
for (int k = 0; k < displayCat.length; k++) {
isidesc[k] = displayCat[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + displayCat[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
}
private class ImageUploader extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private String url;
private String cameraType;
private String cameraMsg;
private String cameraCat;
private String catproduct;
public ImageUploader(String type, String msg, String cat, String cat2) {
cameraType = type;
cameraMsg = msg;
cameraCat = cat;
catproduct = cat2;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StoreTodoDisplayActivity.this, "",
"Uploading...", false);
// none
}
#Override
protected String doInBackground(String... params) {
url = params[0];
Log.i("ncdebug", "upload image to: " + url);
try {
if (image_path.equals("")) {
Log.i("ncdebug", "bmp kosong!!!!");
} else {
Log.i("ncdebug", "Ok bmp gak kosong, mari kirim");
restData = new RestData();
imgData = new ImageData();
restData.setTitle("Display : " + StoreInfo.storename);
restData.setRequestMethod(RequestMethod.POST);
restData.setUrl(url);
imgData.setImageData(url, image_path, cameraMsg, cameraCat
+ "-" + catproduct, UserInfo.username,
StoreInfo.storeid, cameraType, UserInfo.checkinid);
saveToDb();
return "Success";
}
} catch (Exception e) {
//saveToDb();
}
return "Penyimpanan gagal, ulangi tahap pengambilan gambar";
}
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result.equals("Success")) {
Toast.makeText(ctx, "Data tersimpan", Toast.LENGTH_SHORT)
.show();
// checked todo
String vVar = StoreInfo.storeid + "-" + UserInfo.username
+ "-displaycam";
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(vVar, true);
editor.commit();
Intent intent = new Intent(ctx, StoreTodoActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(ctx, Result, Toast.LENGTH_LONG)
.show();
}
}
}
public void saveToDb() {
Log.i("eris", "connection failed so save to db");
RestHelper helper = new RestHelper(ctx);
helper.insertRest(restData);
imgData.setRestId(helper.getRestId());
Log.i("REST ID", helper.getRestId());
ImageHelper imgHelper = new ImageHelper(ctx);
imgHelper.insertRest(imgData);
}
public class getimage extends AsyncTask<String, String, String> {
String orientation = "";
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Log.i("INI BACKGROUND", "LIHAT");
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
String parentPath = Environment.getExternalStorageDirectory()
+ "/Nestle Confect";
String filename = System.currentTimeMillis() + ".jpg";
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(capturedImageFilePath,
opts);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(parentPath);
file.mkdir();
try {
file.createNewFile();
Log.i("absoulute path", file.getAbsolutePath());
FileOutputStream fo = new FileOutputStream(file + "/"
+ filename, true);
// 5
fo.write(bytes.toByteArray());
fo.close();
image_path = parentPath + "/" + filename;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
image_path = capturedImageFilePath;
}
byte[] thumb = null;
try {
ExifInterface exif = new ExifInterface(
capturedImageFilePath);
orientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
thumb = exif.getThumbnail();
} catch (IOException e) {
}
if (thumb != null) {
Log.i("IMAGEVIEW", "THUMBNAIL");
bitmap = BitmapFactory.decodeByteArray(thumb, 0,
thumb.length);
} else {
Log.i("IMAGEVIEW", "REALFILE");
return "not fine";
}
return "fine";
} catch (Exception e) {
return "not fine";
}
}
#Override
public void onPostExecute(String result) {
// PROBLEM HERE
Log.i("ERROR", "HERE MAYBE");
if (result.equals("fine")) {
ImageView gambarHasil = (ImageView) findViewById(R.id.camera_display_img);
gambarHasil.setImageBitmap(bitmap);
if (!orientation.equals("1")) {
Log.i("ORIENTATION", orientation);
float angel = 0f;
if (orientation.equals("6")) {
angel = 90f;
} else if (orientation.equals("8")) {
angel = -90f;
}
Matrix matrix = new Matrix();
gambarHasil.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angel, gambarHasil.getDrawable()
.getBounds().width() / 2, gambarHasil.getDrawable()
.getBounds().height() / 2);
gambarHasil.setImageMatrix(matrix);
}
} else {
Toast.makeText(
ctx,
"Error, Try To Take Picture Again",
Toast.LENGTH_LONG).show();
}
}
}
}
I think your activity just got restarted you need to put below code in manifest where you declare. and save your uri on saveInstanceState and restore it on onrestoreinstancestate. it will be resolve your issue
android:configChanges="orientation|keyboardHidden|screenSize"
Use this lib,Provides support above API 14
https://github.com/google/cameraview
Related
Hi I am new to android i have searching this for a week,
i have a fragment that contains
textview
editext
spinner
calender
image choosing
Adding and removing same fragment in an container with unique tag. in spinner there is multiple numbers that is displayed in activity dynamically, if i add or remove same fragment, the values shown in textview should change dynamically. I know to access each instance by its tag and can get the values in activity but unable to find which fragment instance have changed.
For example, if i have added same fragment four times, made change in spinner in all the four fragment, unable to identify which instance have increased or decreased and correct the total
And also unable to find whether image is added or not.
My fragment is
public class Service_details extends Fragment {
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
ProgressDialog pDialog;
TextView textView_service_no, textView_datePicker, textView_amount, textView_optionalDate;
Spinner spinner_services;
EditText editText_dedicated, editText_intention;
ImageView display_photo;
HashMap<String, String> cList = new HashMap<>();
String[] services;
String initial_spinner_value;
String birthday_price;
String deathday_price;
String rosary_price;
String mass_price;
String prayer_price;
String marriageday_price;
OnMessageReadListener messageReadListener;
String service_value = null;
String service_spinner_string=null;
String person_image_string =null;
String editText_dedicated_string=null;
String editText_intention_string=null;
String textView_telecast_date_string=null;
String textView_amount_string =null;
String total_amount_string=null;
String tax_amount_string=null;
String final_total_amount_string=null;
int c;
int count;
String TAG = "Fragment";
Bitmap bitmap;
LinearLayout linearLayout10;
public interface OnMessageReadListener {
void onMessageRead(String message);
}
public Service_details() {
// Required empty public constructor
}
public static Service_details newInstance(int i) {
Service_details service_details = new Service_details();
Bundle bundle = new Bundle();
int c = i;
bundle.putInt("service_count",i);
service_details.setArguments(bundle);
return service_details;
}
Calendar cal;
public String message;
String path;
int temp;
int a;
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_service_details, container, false);
textView_service_no = view.findViewById(R.id.service_counting);
editText_dedicated = view.findViewById(R.id.editText_dedicated_to);
editText_intention = view.findViewById(R.id.editText_intention);
textView_datePicker = view.findViewById(R.id.date_picker);
spinner_services = view.findViewById(R.id.spinner_services);
textView_amount = view.findViewById(R.id.textview_amount);
display_photo = view.findViewById(R.id.display_photo);
textView_optionalDate = view.findViewById(R.id.textview_exactDate);
cal = Calendar.getInstance();
linearLayout10 = view.findViewById(R.id.linear10);
ButterKnife.bind(this, view);
getJson();
assert getArguments() != null;
count = getArguments().getInt("service_count");
Log.e(TAG, "count value : "+ count);
textView_service_no.setText(valueOf(count));
++count;
a=0;
display_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
textView_optionalDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
textView_optionalDate.setText(""+arg3+"/"+(arg2+1)+"/"+arg1);
Toast.makeText(getActivity(), ""+arg3+"/"+(arg2+1)+"/"+arg1, Toast.LENGTH_SHORT).show();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
dialog.show();
}
});
textView_datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
textView_datePicker.setText(""+arg3+"/"+(arg2+1)+"/"+arg1);
Toast.makeText(getActivity(), ""+arg1+"/"+(arg2+1)+"/"+arg3, Toast.LENGTH_SHORT).show();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 5);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.show();
}
});
services = new String[]{"Select Service","Birth Day", "Death Day", "Rosary", "Hollymass", "Prayer", "Marriage Day"};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, services);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_services.setAdapter(arrayAdapter);
spinner_services.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spin_value = parent.getItemAtPosition(position).toString();
((Services)getActivity()).setCurrentSpinnerItem(spin_value);
switch (position) {
case 0:
textView_amount.setText(cList.get("empty"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
Log.e(TAG,"textView_amount (fragment name)"+ textView_amount.getTag());
String message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
Log.e(TAG, "message_temp: "+message_temp);
messageReadListener.onMessageRead(message);
break;
case 1:
textView_amount.setText(cList.get("birthday_price"));
display_photo.setVisibility(View.VISIBLE);
linearLayout10.setVisibility(View.VISIBLE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
a= Integer.parseInt(message_temp);
a= a-temp;
message = Integer.toString(a);*/
messageReadListener.onMessageRead(message);
break;
case 2:
textView_amount.setText(cList.get("deathday_price"));
display_photo.setVisibility(View.VISIBLE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 3:
textView_amount.setText(cList.get("rosary_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 4:
textView_amount.setText(cList.get("mass_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 5:
textView_amount.setText(cList.get("prayer_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 6:
textView_amount.setText(cList.get("marriageday_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.VISIBLE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
}
// String message = textView_amount.getText().toString();
// messageReadListener.onMessageRead(message);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getActivity());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
Log.e(TAG, "contentURI : " + contentURI);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
display_photo.setImageBitmap(bitmap);
Log.e(TAG, "PATH1" + path);
Log.e(TAG, "BITMAP " + bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
display_photo.setImageBitmap(thumbnail);
path = saveImage(thumbnail);
Log.e(TAG, "PATH2" + path);
saveImage(thumbnail);
Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
public String saveImage(Bitmap myBitmap) {
Log.e(TAG, "PATH3" + path);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
Log.e(TAG, "wallpaperDirectory" + wallpaperDirectory);
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getActivity(),
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
Log.e(TAG, "File Saved::--->" + f.getAbsolutePath());
Log.e(TAG, "PATH4" + path);
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
/*------------------------------------------------------------------------------------------------------------*/
public void getDetailsFromFragment() {
service_value = textView_service_no.getText().toString();
editText_dedicated_string = editText_dedicated.getText().toString();
editText_intention_string = editText_intention.getText().toString();
textView_telecast_date_string = textView_datePicker.getText().toString();
textView_amount_string = textView_amount.getText().toString();
service_spinner_string = spinner_services.getSelectedItem().toString();
if(bitmap!=null){
person_image_string = bitmap.toString();
}
Log.e(TAG, " SERVICE NO. : " + service_value + " \n" + "SERVICES :" + service_spinner_string + " \n" + "DEDICATED TO : " + editText_dedicated_string + " \n" + " INTENTION : " +
editText_intention_string + " \n" + " TELECASTE DATE : " + textView_telecast_date_string + " \n" + " AMOUNT : " + textView_amount_string + "\n" + "IMAGE : " + person_image_string);
Log.e(TAG, "FINAL PAYMENT DETAILS: " + total_amount_string + " " + tax_amount_string + " " + final_total_amount_string);
messageReadListener.onMessageRead(message);
}
public void changeCount(int a){
c = a;
textView_service_no.setText(valueOf(c));
}
#Override
public void onAttach (Context context){
super.onAttach(context);
Activity activity = (Activity) context;
try {
messageReadListener = (OnMessageReadListener) activity;
} catch (ClassCastException c) {
throw new ClassCastException(activity.toString() + " must override onMessageReadListener...");
}
}
}
My activity is
public class Services extends DashBoard implements Service_details.OnMessageReadListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_services);
}
#OnClick(R.id.add_service)
public void addService(){
service_one_amount = Integer.parseInt(message4);
// service_one_amount = message4;
Log.e(TAG, "service_one_amount : "+ service_one_amount);
// service_one_amount = service_one_amount+ ;
if(size<5){
fragTag = "numericField" + numericFragmentCount;
getSupportFragmentManager().beginTransaction().add(R.id.container_frame,Service_details.newInstance(a), fragTag).commit();
++a;
++numericFragmentCount;
Log.e(TAG, "fragment size: "+ size);
}else {
Toast.makeText(this,"Maximum limit reached",Toast.LENGTH_LONG).show();
}
}
#OnClick(R.id.remove_service)
public void removeService(){
size= getSupportFragmentManager().getFragments().size();
if(size>1) {
--numericFragmentCount;
fragTag = "numericField" + numericFragmentCount;
fragment = getSupportFragmentManager().findFragmentById(R.id.container_frame);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
--a;
}
Log.e(TAG, "fragment : " + fragment);
}else {
Toast.makeText(this,"Minimum limit reached",Toast.LENGTH_LONG).show();
}
}
#SuppressLint("SetTextI18n")
#Override
public void onMessageRead(String message) {
try{
String identity_frag = "numericField1";
Fragment service_details1 = getSupportFragmentManager().findFragmentByTag("numericField1");
Fragment service_details2 = getSupportFragmentManager().findFragmentByTag("numericField2");
Fragment service_details3 = getSupportFragmentManager().findFragmentByTag("numericField3");
Fragment service_details4 = getSupportFragmentManager().findFragmentByTag("numericField4");
Fragment service_details5 = getSupportFragmentManager().findFragmentByTag("numericField5");
Log.e(TAG,"before adding message4: "+message4);
message1 = Integer.parseInt(message);
service_details1 instanceof Service_details;
Log.e(TAG,"before initial temp: "+ temp);
if(!textView_amount_view.getText().toString().equals("0")){
initial_amount= String.valueOf(message4);
}else {
initial_amount =textView_amount_view.getText().toString();
}
message3 = Integer.parseInt(initial_amount);
message1= message3+message1-temp;
temp = message1;
Log.e(TAG,"after initial temp: "+ temp);
message1 = message1+service_one_amount;
long res = (long) Math.ceil((message1/ 100.0f) * 18);
double res1 = ((message1/ 100f) * 18);
Toast.makeText(getApplicationContext(), "" + res1, Toast.LENGTH_SHORT).show();
int final_amount = (int) (message1 + res);
message4 = Integer.toString(message1);
Log.e(TAG,"after adding message4: "+message4);
textView_amount_view.setText(currency_symbol+" "+ String.valueOf(message4));
textView_tax_amount_view.setText(currency_symbol+" "+ String.valueOf(res)+ decimal_value);
textView_total_amount_view.setText(currency_symbol+" "+ String.valueOf(final_amount)+ decimal_value);
Log.e(TAG,"total amount: "+message4);
Log.e(TAG,"tax amount: "+res);
Log.e(TAG,"amount after tax: "+final_amount);
}catch (NumberFormatException e){
e.printStackTrace();
}
}
}
if u find question is hard please upvote to reach more people..
Thanks in advance..
I am uploading image to server but image is rotate after uploaded to server Even preview is showing correct.
So many people facing this problem i found this link but didn't work. And there is many solution but i am not figure out how to fit in my code.
Please help me.
Here is my code
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fonts.Text.MyTextView;
import com.generalClass.files.UploadFile;
import com.hwindiapp.driver.db.sqLite.DBConnect;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
public class AddVehicleDocActivity extends AppCompatActivity {
private static final int FILE_SELECT_CODE = 124;
private Toolbar mToolbar;
TextView text_header;
MyTextView insuranceHTxt;
MyTextView permitHTxt;
MyTextView vRegHTxt;
MyTextView insNotFoundTxt;
MyTextView permitNotFoundTxt;
MyTextView vRegNotFoundTxt;
DBConnect dbConnect;
Button insBtn;
Button permitBtn;
Button vRegBtn;
LinearLayout insImgVIew;
LinearLayout permitImgVIew;
LinearLayout vRegImgVIew;
String language_labels_get_frm_sqLite = "";
String LBL_DOCUMENTS_TXT_str = "";
String LBL_YOUR_INSURANCE_TXT_str = "";
String LBL_WRONG_FILE_SELECTED_TXT_str = "";
String LBL_LOADING_TXT_str = "";
String LBL_YOUR_PERMIT_TXT_str = "";
String LBL_VEHICLE_REG_TXT_str = "";
String LBL_NOT_FOUND_TXT_str = "";
String LBL_BTN_OK_TXT_str = "";
String LBL_ERROR_TXT_str = "";
String LBL_TRY_AGAIN_LATER_TXT_str = "";
String LBL_DOC_UPLOAD_SUCCESS_TXT_str = "";
String LBL_ADD_TXT_str = "";
String LBL_EDIT_TXT_str = "";
String LBL_SUCCESS_TXT_str = "";
String LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = "";
String LBL_NOTE_UPLOAD_DOC_TXT_str = "";
String LBL_CANCEL_TXT_str = "";
String currentDocType = "";
String carJson_str = "";
String vIns = "";
String vPermit = "";
String vReg = "";
android.support.v7.app.AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_vehicle_doc);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
dbConnect = new DBConnect(this, "UC_Partner_Labels.db");
text_header = (TextView) findViewById(R.id.text_header);
insuranceHTxt = (MyTextView) findViewById(R.id.insuranceHTxt);
permitHTxt = (MyTextView) findViewById(R.id.permitHTxt);
vRegHTxt = (MyTextView) findViewById(R.id.vRegHTxt);
insNotFoundTxt = (MyTextView) findViewById(R.id.insNotFoundTxt);
permitNotFoundTxt = (MyTextView) findViewById(R.id.permitNotFoundTxt);
vRegNotFoundTxt = (MyTextView) findViewById(R.id.vRegNotFoundTxt);
insImgVIew = (LinearLayout) findViewById(R.id.insImgArea);
permitImgVIew = (LinearLayout) findViewById(R.id.permitImgArea);
vRegImgVIew = (LinearLayout) findViewById(R.id.vRegImgArea);
insBtn = (Button) findViewById(R.id.insBtn);
permitBtn = (Button) findViewById(R.id.permitBtn);
vRegBtn = (Button) findViewById(R.id.vRegBtn);
insBtn.setOnClickListener(new setOnClickAct());
permitBtn.setOnClickListener(new setOnClickAct());
vRegBtn.setOnClickListener(new setOnClickAct());
insImgVIew.setOnClickListener(new setOnClickAct());
permitImgVIew.setOnClickListener(new setOnClickAct());
vRegImgVIew.setOnClickListener(new setOnClickAct());
carJson_str = getIntent().getStringExtra("CarJson");
/* Set Labels */
getLanguageLabelsFrmSqLite();
/* Set Labels Finished */
ImageView back_navigation = (ImageView) findViewById(R.id.back_navigation);
back_navigation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AddVehicleDocActivity.super.onBackPressed();
}
});
Log.d("carJson_str", ":" + carJson_str);
try {
parseCarJson(carJson_str);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLanguageLabelsFrmSqLite() {
Cursor cursor = dbConnect.execQuery("select vValue from labels WHERE vLabel=\"Language_labels\"");
cursor.moveToPosition(0);
language_labels_get_frm_sqLite = cursor.getString(0);
JSONObject obj_language_labels = null;
try {
obj_language_labels = new JSONObject(language_labels_get_frm_sqLite);
LBL_DOCUMENTS_TXT_str = obj_language_labels.getString("LBL_DOCUMENTS_TXT");
LBL_YOUR_INSURANCE_TXT_str = obj_language_labels.getString("LBL_YOUR_INSURANCE_TXT");
LBL_WRONG_FILE_SELECTED_TXT_str = obj_language_labels.getString("LBL_WRONG_FILE_SELECTED_TXT");
LBL_LOADING_TXT_str = obj_language_labels.getString("LBL_LOADING_TXT");
LBL_YOUR_PERMIT_TXT_str = obj_language_labels.getString("LBL_YOUR_PERMIT_TXT");
LBL_VEHICLE_REG_TXT_str = obj_language_labels.getString("LBL_VEHICLE_REG_TXT");
LBL_NOT_FOUND_TXT_str = obj_language_labels.getString("LBL_NOT_FOUND_TXT");
LBL_BTN_OK_TXT_str = obj_language_labels.getString("LBL_BTN_OK_TXT");
LBL_ERROR_TXT_str = obj_language_labels.getString("LBL_ERROR_TXT");
LBL_TRY_AGAIN_LATER_TXT_str = obj_language_labels.getString("LBL_TRY_AGAIN_LATER_TXT");
LBL_DOC_UPLOAD_SUCCESS_TXT_str = obj_language_labels.getString("LBL_DOC_UPLOAD_SUCCESS_TXT");
LBL_ADD_TXT_str = obj_language_labels.getString("LBL_ADD_TXT");
LBL_EDIT_TXT_str = obj_language_labels.getString("LBL_EDIT_TXT");
LBL_SUCCESS_TXT_str = obj_language_labels.getString("LBL_SUCCESS_TXT");
LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = obj_language_labels.getString("LBL_BTN_TRIP_CANCEL_CONFIRM_TXT");
LBL_NOTE_UPLOAD_DOC_TXT_str = obj_language_labels.getString("LBL_NOTE_UPLOAD_DOC_TXT");
LBL_CANCEL_TXT_str = obj_language_labels.getString("LBL_CANCEL_TXT");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (obj_language_labels != null) {
text_header.setText("" + LBL_DOCUMENTS_TXT_str);
insuranceHTxt.setText("" + LBL_YOUR_INSURANCE_TXT_str);
permitHTxt.setText("" + LBL_YOUR_PERMIT_TXT_str);
vRegHTxt.setText("" + LBL_VEHICLE_REG_TXT_str);
insNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
permitNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
vRegNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
insBtn.setText(LBL_ADD_TXT_str);
permitBtn.setText(LBL_ADD_TXT_str);
vRegBtn.setText(LBL_ADD_TXT_str);
}
}
public void parseCarJson(String carJson) throws JSONException {
JSONObject obj_profile = new JSONObject(carJson);
vIns = obj_profile.getString("vInsurance");
vPermit = obj_profile.getString("vPermit");
vReg = obj_profile.getString("vRegisteration");
if (vIns == null || vIns.equals("")) {
insNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(0);
}
if (vPermit == null || vPermit.equals("")) {
permitNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(1);
}
if (vReg == null || vReg.equals("")) {
vRegNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(2);
}
}
public void setDocView(int id) {
if (id == 0) {
insNotFoundTxt.setVisibility(View.GONE);
insBtn.setText(LBL_EDIT_TXT_str);
insImgVIew.setVisibility(View.VISIBLE);
} else if (id == 1) {
permitNotFoundTxt.setVisibility(View.GONE);
permitBtn.setText(LBL_EDIT_TXT_str);
permitImgVIew.setVisibility(View.VISIBLE);
} else if (id == 2) {
vRegNotFoundTxt.setVisibility(View.GONE);
vRegBtn.setText(LBL_EDIT_TXT_str);
vRegImgVIew.setVisibility(View.VISIBLE);
}
}
public class setOnClickAct implements View.OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.insBtn:
currentDocType = "vInsurance";
chooseFIle();
break;
case R.id.permitBtn:
currentDocType = "vPermit";
chooseFIle();
break;
case R.id.vRegBtn:
currentDocType = "vRegisteration";
chooseFIle();
break;
case R.id.insImgArea:
openDocument(vIns);
break;
case R.id.permitImgArea:
openDocument(vPermit);
break;
case R.id.vRegImgArea:
openDocument(vReg);
break;
}
}
}
public void openDocument(String documentName) {
Log.d("Open doc","::"+CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName));
startActivity(browserIntent);
}
public void chooseFIle() {
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, FILE_SELECT_CODE);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri uri = data.getData();
// Log.d("Path", "::" + uri.getPath());
// Log.d("Path", "::" + getPath(uri));
String filePath = "";
filePath = (getPath(uri) == null) ? uri.getPath() : getPath(uri);
// Log.d("Ext", ":" + getFileExt(filePath));
final ArrayList<String[]> paramsList = new ArrayList<>();
paramsList.add(generateImageParams("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId")));
paramsList.add(generateImageParams("type", "UploadVehicleDoc"));
paramsList.add(generateImageParams("iDriverId", getIntent().getStringExtra("UserID")));
paramsList.add(generateImageParams("DocUploadType", currentDocType));
if (getFileExt(filePath).equalsIgnoreCase("jpg") || getFileExt(filePath).equalsIgnoreCase("gif") || getFileExt(filePath).equalsIgnoreCase("png")
|| getFileExt(filePath).equalsIgnoreCase("jpeg") || getFileExt(filePath).equalsIgnoreCase("bmp") || getFileExt(filePath).equalsIgnoreCase("pdf")
|| getFileExt(filePath).equalsIgnoreCase("doc") || getFileExt(filePath).equalsIgnoreCase("docx")) {
File selectedFile = new File(filePath);
if (selectedFile != null) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str);
final String finalFilePath = filePath;
alertDialogBuilder
.setMessage(selectedFile.getName() + "\n" + LBL_NOTE_UPLOAD_DOC_TXT_str)
.setCancelable(true)
.setNegativeButton(LBL_CANCEL_TXT_str, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
})
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
new uploadDocument(finalFilePath, currentDocType + "." + getFileExt(finalFilePath), paramsList).execute();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
// showErrorOnSelection();
showMessage(LBL_ERROR_TXT_str, LBL_WRONG_FILE_SELECTED_TXT_str);
}
}
}
}
public String[] generateImageParams(String key, String content) {
String[] tempArr = new String[2];
tempArr[0] = key;
tempArr[1] = content;
return tempArr;
}
public class uploadDocument extends AsyncTask<String, String, String> {
String selectedPath;
String responseString = "";
ProgressDialog myPDialog;
String temp_File_Name = "";
ArrayList<String[]> paramsList;
public uploadDocument(String selectedPath, String temp_File_Name, ArrayList<String[]> paramsList) {
this.selectedPath = selectedPath;
this.temp_File_Name = temp_File_Name;
this.paramsList = paramsList;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
myPDialog = new ProgressDialog(AddVehicleDocActivity.this, R.style.DialogTheme_custom);
myPDialog.setMessage("" + LBL_LOADING_TXT_str);
myPDialog.setCancelable(false);
myPDialog.setCanceledOnTouchOutside(false);
myPDialog.show();
}
#Override
protected String doInBackground(String... strings) {
responseString = new UploadFile().uploadImageAsFile(selectedPath, temp_File_Name, "vFile", paramsList);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
myPDialog.dismiss();
Log.d("responseString", "::" + responseString);
if (responseString != null && !responseString.equals("")) {
try {
JSONObject obj_temp = new JSONObject(responseString);
String action_str = obj_temp.getString("Action");
String fileName_str = obj_temp.getString("vFileName");
if (action_str.equals("1")) {
showMessage(LBL_SUCCESS_TXT_str, LBL_DOC_UPLOAD_SUCCESS_TXT_str);
JSONObject obj_CarJson = new JSONObject(carJson_str);
if (currentDocType.equals("vInsurance")) {
obj_CarJson.remove("vInsurance");
obj_CarJson.put("vInsurance", fileName_str);
vIns = fileName_str;
setDocView(0);
} else if (currentDocType.equals("vPermit")) {
obj_CarJson.remove("vPermit");
obj_CarJson.put("vPermit", fileName_str);
vPermit = fileName_str;
setDocView(1);
} else if (currentDocType.equals("vRegisteration")) {
obj_CarJson.remove("vRegisteration");
obj_CarJson.put("vRegisteration", fileName_str);
vReg = fileName_str;
setDocView(2);
}
obj_CarJson.remove("eStatus");
obj_CarJson.put("eStatus", "Inactive");
carJson_str = obj_CarJson.toString();
Intent setData = new Intent();
setData.putExtra("CarJson", carJson_str);
setData.putExtra("DriverProfileData", obj_temp.getString("DriverProfileData").toString());
setData.putExtra("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId"));
setResult(RESULT_OK, setData);
// Driver_main_profile.updated_json_responseString_profile = obj_profileJson.toString();
//
// Driver_main_profile.driverDocUpdated = true;
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} catch (JSONException e) {
e.printStackTrace();
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
}
}
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public String getPath(Uri uri) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else {
return null;
}
}
public void showMessage(String title_str, String content_str) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(title_str);
alertDialogBuilder
.setMessage(content_str)
.setCancelable(true)
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Here is my Upload code
public class UploadFile {
public String uploadImageAsFile(String sourceFileUri, String fileName, String imageParamKey, ArrayList<String[]> params) {
ExifInterface exif = null; //Since API Level 5
try {
exif = new ExifInterface(sourceFileUri);
} catch (IOException e) {
e.printStackTrace();
}
String exifImage = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
String responseString = "";
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(exifImage));
byte[] data;
try {
data = convertToByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(CommonUtilities.SERVER_URL);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity(/*HttpMultipartMode.BROWSER_COMPATIBLE,"9999999999", Charset.defaultCharset()*/);
for (int i = 0; i < params.size(); i++) {
String[] paramsArr = params.get(i);
multipartEntity.addPart(paramsArr[0], new StringBody(paramsArr[1]));
}
ContentBody cbFile = new FileBody(new File(exifImage)/*, "multipart/form-data"*/);
multipartEntity.addPart(imageParamKey, cbFile);
httpPost.setEntity(multipartEntity);
// httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
// httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
// httpPost.setHeader("Content-Type", "multipart/form-data");
// httpPost.setHeader("Content-Type", "image/png");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setRequestProperty("ENCTYPE", "multipart/form-data");
// httpPost.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// httpPost.addHeader("Content-Type", "multipart/form-data;charset=UTF-8;boundary=654654");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setHeader("ENCTYPE", "multipart/form-data");
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if (httpResponse != null) {
Log.d("success", "success:" + httpResponse.toString());
responseString = EntityUtils.toString(httpResponse.getEntity());
} else { // Error, no response.
Log.d("Failed", "failed:" + httpResponse.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return responseString;
}
private byte[] convertToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = inputStream.read();
while (next > -1) {
bos.write(next);
next = inputStream.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* #param encodedString
* #return bitmap (from given string)
*/
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
}
You shouldn't rotate the image after upload. You need to rotate it before. The preview is correct maybe because you're respecting Exif values when showing it. But the server isn't.
You need to rotate the image according to it's exif rotation:
https://stackoverflow.com/a/20480741/3410697
And only then you should upload it to the server
Call this function where you get path of image
public void setImage(String _path) {
int orientation = CustomImageUtil.getExifOrientation(_path);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, resample);
if (orientation == 90) {
bitmap = CustomImageUtil.rotate(bitmap, 90);
} else if (orientation == 180) {
bitmap = CustomImageUtil.rotate(bitmap, 180);
} else if (orientation == 270) {
bitmap = CustomImageUtil.rotate(bitmap, 270);
}
// use your bitmap here
}
CustomImageUtil.class:
public class CustomImageUtil {
public static String getRealPathFromURI(Context context,Uri contentURI) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 60, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
/**
* getExifOrientation -- Roate the image on the right angel
* #param filepath -- path of the file to be rotated
* #return
*/
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {ex.printStackTrace();
}
if (exif != null) {
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
// We only recognize a subset of orientation tag values.
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees, (float) b.getWidth() / 2,
(float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {ex.printStackTrace();
}
}
return b;
}
}
To convert Bitmap to Uri
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
I try set image into ImageView from gallery.
public class CollageCreateActivity extends AppCompatActivity {
private static final String TAG ="MyLogs" ;
Draw2d draw2d;
static final int GALLERY_REQUEST = 1;
private final int TAKE_PICTURE_CAMERA = 2;
private Uri mOutputFileUri;
ArrayList<CollageView> collageViewList1;
ArrayList<CollageView> collageViewList2;
float width;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage_creator);
collageViewList1 = new ArrayList<>();
collageViewList2 = new ArrayList<>();
Data data = new Data();
draw2d = new Draw2d(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_1);
if (frameLayout != null) {
frameLayout.addView(draw2d);
}
createCollage(data, layout);
if (layout != null) {
layout.bringToFront();
}
click();
}
public void createCollage(Data data, LinearLayout layout) {
ArrayList<Integer> list = new ArrayList<>();
list.add((int) data.getMap().get("mainLayout"));
list.add((int) data.getMap().get("firstLayout"));
list.add((int) data.getMap().get("secondLayout"));
final LinearLayout layout1 = new LinearLayout(this);
final LinearLayout layout2 = new LinearLayout(this);
LinearLayout[] massLay = {layout, layout1, layout2};
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1;
layout1.setLayoutParams(params);
layout2.setLayoutParams(params);
for (int i = 0; i < (int) data.getMap().get("layButt1"); i++) {
final Button button = new Button(this);
button.setLayoutParams(params);
button.setTextSize(50);
button.setId(i);
button.setPadding(16, 16, 16, 16);
button.setText(R.string.plus);
layout1.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout1.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
saveFromGallery();
layout1.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
collageViewList1.add(collageView);
}
});
}
for (int j = 0; j < (int) data.getMap().get("layButt2"); j++) {
Button button2 = new Button(this);
button2.setLayoutParams(params);
button2.setTextSize(50);
button2.setId(j);
button2.setPadding(16, 16, 16, 16);
button2.setText(R.string.plus);
layout2.addView(button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout2.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
layout2.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
width = layout2.getWidth();
collageViewList2.add(collageView);
}
});
}
for (int x = 0; x < list.size(); x++) {
if (list.get(x) == 0) {
massLay[x].setOrientation(LinearLayout.HORIZONTAL);
} else {
massLay[x].setOrientation(LinearLayout.VERTICAL);
}
}
layout.addView(layout1);
layout.addView(layout2);
}
public void click() {
Button button = (Button) findViewById(R.id.butt);
if (button != null) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < collageViewList1.size(); i++) {
collageViewList1.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap1 = Bitmap.createBitmap(collageViewList1.get(i).getDrawingCache());
collageViewList1.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap1);
draw2d.listX.add(collageViewList1.get(i).getX());
draw2d.listY.add(collageViewList1.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
for (int i = 0; i < collageViewList2.size(); i++) {
collageViewList2.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap2 = Bitmap.createBitmap(collageViewList2.get(i).getDrawingCache());
collageViewList2.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap2);
draw2d.listX.add(collageViewList2.get(i).getX() + width);
draw2d.listY.add(collageViewList2.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
draw2d.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(draw2d.getDrawingCache());
draw2d.setDrawingCacheEnabled(false);
draw2d.invalidate();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
InputStream imageStream = null;
CollageView collageView = new CollageView(CollageCreateActivity.this);
switch(requestCode) {
case GALLERY_REQUEST:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
imageStream=getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap= BitmapFactory.decodeStream(imageStream);
Log.d(TAG, "сетим з галереї1");
collageView.setImageBitmap(bitmap);
Log.d(TAG, "сетим з галереї");
}
break;
case TAKE_PICTURE_CAMERA:
if (data != null) {
if (data.hasExtra("data")) {
Bitmap thumbnailBitmap = data.getParcelableExtra("data");
collageView.setImageBitmap(thumbnailBitmap);
}
} else {
collageView.setImageURI(mOutputFileUri);
}
}
}
private void saveFromGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
}
When i try set image from folder "drawrable" it's work, but if i try load image and set from gallery it's don't work, all i have "W/EGL_genymotion: eglSurfaceAttrib not implemented" in logs
In this case you will have to create a content provider which will use to share your local (Application's internal) file to the camera activity.when you try to take picture from camera
try this code:
Content provider class
public class MyFileContentProvider extends ContentProvider {
public static final Uri CONTENT_URI =
Uri.parse("content://com.example.camerademo/");
private static final HashMap<String, String> MIME_TYPES = new
HashMap<String, String>();
static {
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
}
#Override
public boolean onCreate() {
try {
File mFile = new File(getContext().getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
mFile.createNewFile();
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return (true);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public String getType(Uri uri) {
String path = uri.toString();
for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
File f = new File(getContext().getFilesDir(), "newImage.jpg");
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_WRITE));
}
throw new FileNotFoundException(uri.getPath());
}
#Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
throw new RuntimeException("Operation not supported");
}
#Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
#Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
}
Home.java:
public class Home extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
Button button1;
ImageView imageView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
imageView1 = (ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(this);
}
public void onClick(View v) {
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available",
Toast.LENGTH_LONG).show();
} }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(Tag, "Receive the camera result");
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
File out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
imageView1.setImageBitmap(mBitmap);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
imageView1 = null;
}
}
hope it will help you,otherwise u will contact me my email
id:daminimehra28#gmail.com
I have a book-App, where I scan a book with barcodescanner and retrieving the information from googlebooksapi.
At the moment I can save the general bookinfos, title, author, date, rating and shelf (where i want to display the book) in my SQLite database
Now I want to save the bookcover, which comes with the googleapi, too.
Can you tell me how I can save the image in my SQlite Database. By looking for solution I realized that I have to blob the image. but I dont know how.
Following my activties.
ScanActivity.java -> at the end of the code, I save the book data into sql db
public class ScanActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn, previewBtn, linkBtn, addBookBtn, librarybtn;
public TextView authorText, titleText, descriptionText, dateText, ratingCountText;
public EditText shelfText;
private LinearLayout starLayout;
private ImageView thumbView;
private ImageView[] starViews;
private Bitmap thumbImg;
public BookDBHelper bookDBHelper;
public SQLiteDatabase sqLiteDatabase1;
public Context context1 = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
//Fonts
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Button myButtonViewScan = (Button) findViewById(R.id.scan_button);
myButtonViewScan.setTypeface(myTypeface);
TextView myWheretoSaveTextView = (TextView) findViewById(R.id.textView_wheretosave);
myWheretoSaveTextView.setTypeface(myTypeface);
//Scanbutton
scanBtn = (Button) findViewById(R.id.scan_button);
scanBtn.setOnClickListener(this);
//Preview Button
previewBtn = (Button) findViewById(R.id.preview_btn);
previewBtn.setVisibility(View.GONE);
previewBtn.setOnClickListener(this);
//Weblink Button
linkBtn = (Button) findViewById(R.id.link_btn);
linkBtn.setVisibility(View.GONE);
linkBtn.setOnClickListener(this);
/* //AddBookBtn
addBookBtn= (Button)findViewById(R.id.btn_savebook);
addBookBtn.setVisibility(View.GONE);
addBookBtn.setOnClickListener(this);
//LibraryButton
librarybtn = (Button) findViewById(R.id.btn_maps);
librarybtn.setVisibility(View.GONE);
librarybtn.setOnClickListener(this);
*/
authorText = (TextView) findViewById(R.id.book_author);
titleText = (TextView) findViewById(R.id.book_title);
descriptionText = (TextView) findViewById(R.id.book_description);
dateText = (TextView) findViewById(R.id.book_date);
starLayout = (LinearLayout) findViewById(R.id.star_layout);
ratingCountText = (TextView) findViewById(R.id.book_rating_count);
thumbView = (ImageView) findViewById(R.id.thumb);
shelfText = (EditText) findViewById(R.id.editText_wheretosave);
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
} else if (v.getId() == R.id.link_btn) {
//get the url tag
String tag = (String) v.getTag();
//launch the url
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(Uri.parse(tag));
startActivity(webIntent);
} else if (v.getId() == R.id.preview_btn) {
String tag = (String) v.getTag();
Intent intent = new Intent(this, EmbeddedBook.class);
intent.putExtra("isbn", tag);
startActivity(intent);
//launch preview
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
//check we have a valid result
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
//get format name of data scanned
String scanFormat = scanningResult.getFormatName();
previewBtn.setTag(scanContent);
if (scanContent != null && scanFormat != null && scanFormat.equalsIgnoreCase("EAN_13")) {
String bookSearchString = "https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + scanContent + "&key=AIzaSyDminlOe8YitHijWd51n7-w2h8W1qb5PP0";
new GetBookInfo().execute(bookSearchString);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Not a valid scan!", Toast.LENGTH_SHORT);
toast.show();
}
Log.v("SCAN", "content: " + scanContent + " - format: " + scanFormat);
} else {
//invalid scan data or scan canceled
Toast toast = Toast.makeText(getApplicationContext(),
"No book scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private class GetBookInfo extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... bookURLs) {
StringBuilder bookBuilder = new StringBuilder();
for (String bookSearchURL : bookURLs) {
HttpClient bookClient = new DefaultHttpClient();
try {
HttpGet bookGet = new HttpGet(bookSearchURL);
HttpResponse bookResponse = bookClient.execute(bookGet);
StatusLine bookSearchStatus = bookResponse.getStatusLine();
if (bookSearchStatus.getStatusCode() == 200) {
HttpEntity bookEntity = bookResponse.getEntity();
InputStream bookContent = bookEntity.getContent();
InputStreamReader bookInput = new InputStreamReader(bookContent);
BufferedReader bookReader = new BufferedReader(bookInput);
String lineIn;
while ((lineIn = bookReader.readLine()) != null) {
bookBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bookBuilder.toString();
}
protected void onPostExecute(String result) {
try {
previewBtn.setVisibility(View.VISIBLE);
JSONObject resultObject = new JSONObject(result);
JSONArray bookArray = resultObject.getJSONArray("items");
JSONObject bookObject = bookArray.getJSONObject(0);
JSONObject volumeObject = bookObject.getJSONObject("volumeInfo");
try {
titleText.setText(volumeObject.getString("title"));
} catch (JSONException jse) {
titleText.setText("");
jse.printStackTrace();
}
StringBuilder authorBuild = new StringBuilder("");
try {
JSONArray authorArray = volumeObject.getJSONArray("authors");
for (int a = 0; a < authorArray.length(); a++) {
if (a > 0) authorBuild.append(", ");
authorBuild.append(authorArray.getString(a));
}
authorText.setText(authorBuild.toString());
} catch (JSONException jse) {
authorText.setText("");
jse.printStackTrace();
}
try {
dateText.setText(volumeObject.getString("publishedDate"));
} catch (JSONException jse) {
dateText.setText("");
jse.printStackTrace();
}
try {
descriptionText.setText("DESCRIPTION: " + volumeObject.getString("description"));
} catch (JSONException jse) {
descriptionText.setText("");
jse.printStackTrace();
}
try {
double decNumStars = Double.parseDouble(volumeObject.getString("averageRating"));
int numStars = (int) decNumStars;
starLayout.setTag(numStars);
starLayout.removeAllViews();
for (int s = 0; s < numStars; s++) {
starViews[s].setImageResource(R.drawable.star);
starLayout.addView(starViews[s]);
}
} catch (JSONException jse) {
starLayout.removeAllViews();
jse.printStackTrace();
}
try {
ratingCountText.setText(volumeObject.getString("ratingsCount") + " ratings");
} catch (JSONException jse) {
ratingCountText.setText("");
jse.printStackTrace();
}
try {
boolean isEmbeddable = Boolean.parseBoolean
(bookObject.getJSONObject("accessInfo").getString("embeddable"));
if (isEmbeddable) previewBtn.setEnabled(true);
else previewBtn.setEnabled(false);
} catch (JSONException jse) {
previewBtn.setEnabled(false);
jse.printStackTrace();
}
try {
linkBtn.setTag(volumeObject.getString("infoLink"));
linkBtn.setVisibility(View.VISIBLE);
} catch (JSONException jse) {
linkBtn.setVisibility(View.GONE);
jse.printStackTrace();
}
try {
JSONObject imageInfo = volumeObject.getJSONObject("imageLinks");
new GetBookThumb().execute(imageInfo.getString("smallThumbnail"));
} catch (JSONException jse) {
thumbView.setImageBitmap(null);
jse.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
titleText.setText("NOT FOUND");
authorText.setText("");
descriptionText.setText("");
dateText.setText("");
starLayout.removeAllViews();
ratingCountText.setText("");
thumbView.setImageBitmap(null);
previewBtn.setVisibility(View.GONE);
shelfText.setText("");
}
}
}
private class GetBookThumb extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... thumbURLs) {
try {
URL thumbURL = new URL(thumbURLs[0]);
URLConnection thumbConn = thumbURL.openConnection();
thumbConn.connect();
InputStream thumbIn = thumbConn.getInputStream();
BufferedInputStream thumbBuff = new BufferedInputStream(thumbIn);
thumbImg = BitmapFactory.decodeStream(thumbBuff);
thumbBuff.close();
thumbIn.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
thumbView.setImageBitmap(thumbImg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showMaps(View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
//HERE I SAVE THE RETRIEVED DATA
public void saveBook(View view) { //Click on save Book
String title = titleText.getText().toString();
String author = authorText.getText().toString();
String date = dateText.getText().toString();
String rating = ratingCountText.getText().toString();
String shelf = shelfText.getText().toString();
bookDBHelper = new BookDBHelper(context1);
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}
}
BookDBHelper.java
public class BookDBHelper extends SQLiteOpenHelper{
private static final String DATABASE_BOOKS_NAME = "BookINFO.DB";
private static final int DATABASE_BOOKS_VERS = 2;
private static final String CREATE_QUERY_BOOKS =
"CREATE TABLE "
+ BookContent.NewBookInfo.TABLE_NAME_BOOKS
+"("
+ BookContent.NewBookInfo.BOOK_ID + "INTEGER PRIMARY KEY, "
+ BookContent.NewBookInfo.BOOK_IMAGE +" BLOB, "
+ BookContent.NewBookInfo.BOOK_IMAGE_TAG +" TEXT, "
+ BookContent.NewBookInfo.BOOK_TITLE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_AUTHOR+" TEXT, "
+ BookContent.NewBookInfo.BOOK_DATE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_RATING+" TEXT, "
+ BookContent.NewBookInfo.BOOK_SHELF+" TEXT);";
public BookDBHelper(Context context){
super(context, DATABASE_BOOKS_NAME, null, DATABASE_BOOKS_VERS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase bookdb) {
bookdb.execSQL(CREATE_QUERY_BOOKS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase bookdb, int oldVersion, int newVersion) {
bookdb.execSQL(" DROP TABLE IS EXISTS " + BookContent.NewBookInfo.TABLE_NAME_BOOKS);
onCreate(bookdb);
}
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
public Cursor getInformations(SQLiteDatabase bookdb){
Cursor cursor2;
String[] projections = {
BookContent.NewBookInfo.BOOK_TITLE,
BookContent.NewBookInfo.BOOK_AUTHOR,
BookContent.NewBookInfo.BOOK_DATE,
BookContent.NewBookInfo.BOOK_RATING,
BookContent.NewBookInfo.BOOK_SHELF};
cursor2 = bookdb.query(BookContent.NewBookInfo.TABLE_NAME_BOOKS, projections,null, null, null, null, null);
return cursor2;
}
Afterwards the infos will be displayed in a liestview.
BookDataListActivity
public class BookDataListActivity extends Activity {
public ListView booklistView;
private EditText inputSearch = null;
public SQLiteDatabase sqLiteDatabaseBooks = null;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
public final static String EXTRA_MSG1 = "title";
public final static String EXTRA_MSG2 = "author";
public final static String EXTRA_MSG3 = "date";
public final static String EXTRA_MSG4 = "rating";
public final static String EXTRA_MSG5 = "shelf";
public TextView editTextBooktitle;
public TextView editTextBookauthor;
public TextView editTextBookdate;
public TextView editTextBookrating;
public TextView editTextBookshelf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView) findViewById(R.id.book_list_view);
inputSearch = (EditText) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(), R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
//onItemClickListener
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), BookInfoActivity.class);
editTextBooktitle = (TextView) view.findViewById(R.id.text_book_title);
String book_title = editTextBooktitle.getText().toString();
intent.putExtra(EXTRA_MSG1, book_title);
editTextBookauthor = (TextView) view.findViewById(R.id.text_book_author);
String bookauthor = editTextBookauthor.getText().toString();
intent.putExtra(EXTRA_MSG2, bookauthor);
editTextBookdate = (TextView) view.findViewById(R.id.text_book_date);
String bookdate = editTextBookdate.getText().toString();
intent.putExtra(EXTRA_MSG3, bookdate);
editTextBookrating = (TextView) view.findViewById(R.id.text_book_rating);
String bookrating = editTextBookrating.getText().toString();
intent.putExtra(EXTRA_MSG4, bookrating);
editTextBookshelf = (TextView) view.findViewById(R.id.text_book_shelf);
String bookshelf = editTextBookshelf.getText().toString();
intent.putExtra(EXTRA_MSG5, bookshelf);
startActivity(intent);
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if (cursor2.moveToFirst()) {
do {
String booktitle, bookauthor, bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
} while (cursor2.moveToNext());
}
}
}
And I think you will need the DataAdapter
DataListDataAdapter
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public SQLiteDatabase sqLiteDatabaseBooks;
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
BookDataProvider:
public class BookDataProvider {
private Bitmap bookimage;
private String booktitle;
private String bookauthor;
private String bookdate;
private String bookrating;
private String bookshelf;
public Bitmap getBookimage() {
return bookimage;
}
public void setBookimage(Bitmap bookimage) {
this.bookimage = bookimage;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getBookauthor() {
return bookauthor;
}
public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor;
}
public String getBookdate() {
return bookdate;
}
public void setBookdate(String bookdate) {
this.bookdate = bookdate;
}
public String getBookrating() {
return bookrating;
}
public void setBookrating(String bookrating) {
this.bookrating = bookrating;
}
public String getBookshelf() {
return bookshelf;
}
public void setBookshelf(String bookshelf) {
this.bookshelf = bookshelf;
}
public BookDataProvider ( Bitmap bookimage, String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf)
{
this.bookimage = bookimage;
this.booktitle = booktitle;
this.bookauthor = bookauthor;
this.bookdate = bookdate;
this.bookrating = bookrating;
this.bookshelf = bookshelf;
}
}
BookContent
public class BookContent {
public static abstract class NewBookInfo{ //Tabllenspalten deklaration
public static final String BOOK_IMAGE = "book_image";
public static final String BOOK_IMAGE_TAG ="image_tag";
public static final String BOOK_TITLE = "book_title";
public static final String BOOK_AUTHOR = "book_author";
public static final String BOOK_DATE = "book_date";
public static final String BOOK_RATING = "book_rating";
public static final String BOOK_SHELF = "book_shelf";
public static final String TABLE_NAME_BOOKS = "book_info";
public static final String BOOK_ID = "_id";
}
}
If I get your question right, you need to convert your image to a blob.
Well, blob is a byte array, so the following code would help you to convert your Bitmap to a byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, thumbImg);
byte[] blob = stream.toByteArray();
You can also get the whole implementation from another question here:
how to store Image as blob in Sqlite & how to retrieve it?
EDIT:
Of course, you have to edit your BookDBHelper.addInformations function and add one additional parameter for your image:
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, byte[] image, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
contentValues.put(YOUR_IMAGE_CONSTANT, image);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
Now you can save your Book through ScanActivity.saveBook:
public void saveBook(View view) { //Click on save Book
// ...
BitmapDrawable bitmapDrawable = (BitmapDrawable) thumbView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] blob = stream.toByteArray();
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, blob, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}
I have a class that is currently extending Activity and I have methods like onCreate(),OnBackPress() etc. I want to turn it into an independent class but all the above methods become undefined. What is the problem? Shouldn't importing the classes be enough? For eg, I import android.view.View for findViewById but it still makes no difference. Please advise.
File_Explore
public class File_Explorer extends Activity {
// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;
String aDataRow = "";
static StringBuilder aBuffer = new StringBuilder();
String aBuffer1="";
private static final String TAG = "F_PATH";
static long fileSizeInMB;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 0;
static String fileExtension="";
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.ic_launcher);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.ic_launcher;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Back", R.drawable.ic_launcher);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablePadding(
fileList[position].icon);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("Back") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
fileExtension
= MimeTypeMap.getFileExtensionFromUrl(sel.toString());
// Toast.makeText(getApplication(), fileExtension, Toast.LENGTH_LONG).show();
long fileSizeInBytes = sel.length();
fileSizeInMB = fileSizeInBytes/(1024*1024);
Toast.makeText(getApplication(), String.valueOf(fileSizeInMB).toString(), Toast.LENGTH_LONG).show();
if(fileSizeInMB >1){
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
}
else{
try{
// ArrayList<String> MyFiles = new ArrayList<String>();
FileInputStream fIn = new FileInputStream(sel);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer.append(aDataRow.toString()).append("\n");
}
// aBuffer1 = aBuffer.toString();
myReader.close();
}catch (FileNotFoundException e)
{e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
finish();
}
}
aBuffer.delete(0, aBuffer.length());
// aBuffer1=null;
}
}
);
break;
}
dialog = builder.show();
return dialog;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i= new Intent(this, File_Selecter.class);
startActivity(i);
}
}