Related
Almost everything in my activity is working fine, except for wherever TAG is referenced. TAG gets a red line and says: 'TAG' has private access in 'android.support.v4.app.FragmentActivity'.
MainActivity (without imports)-
public class MainActivity extends AppCompatActivity {
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/MainActivity";
public static final String lang = "eng";
protected Button _button;
protected ImageView _image;
protected TextView _field;
protected String _path;
protected boolean _taken;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
_image = ( ImageView ) findViewById( R.id.image );
_field = ( TextView ) findViewById( R.id.field );
_button = ( Button ) findViewById( R.id.button );
_button.setOnClickListener( new ButtonClickHandler() );
_path = Environment.getExternalStorageDirectory() + "/Login Data.jpg";
}
public class ButtonClickHandler implements View.OnClickListener
{
public void onClick( View view ){
startCameraActivity();
}
}
protected void startCameraActivity()
{
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, 0 );
}
protected void onPhotoTaken()
{
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile( _path, options );
_image.setImageBitmap(bitmap);
_field.setVisibility( View.GONE );
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap & convert to ARGB_8888, required by tess
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
}
#Override
protected void onSaveInstanceState( Bundle outState ) {
outState.putBoolean( MainActivity.PHOTO_TAKEN, _taken );
}
#Override
protected void onRestoreInstanceState( Bundle savedInstanceState)
{
Log.i( "MakeMachine", "onRestoreInstanceState()");
if( savedInstanceState.getBoolean( MainActivity.PHOTO_TAKEN ) ) {
onPhotoTaken();
}
}
You should define a constant for your tag in MainActivity:
private static final String TAG = "MainActivity"
try the following
private static final String TAG = MainActivity.class.getSimpleName();
You can use this field in your any Activity or Fragment.
Well that's just an Android's way of telling us that we haven't defined TAG. To define the TAG in the current file, we can go to MainActivity Class and type "logt", you will get some auto code suggestions from Android studio, press enter there and you will get following code
private static final String TAG = "MainActivity";
Once you add this to your code, your error will be gone
Practical note: following is the better approach
private static final String TAG = MainActivity.class.getSimpleName();
as compared to:
private static final String TAG = "MainActivity";
After selecting multiple images from a gallery, I want to upload them to an ftp server. During the upload, I get the following error:
"java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20150724_220209.jpg /storage/emulated/0/DCIM/Screenshots/Screenshot_2015-08-04-14-47-38.png "
Can anyone help?
public class MainActivity extends Activity implements View.OnClickListener{
private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE =1;
static final String FTP_HOST = "";
static final String FTP_USER = "";
static final String FTP_PASS = "";
String j;
Uri uri;
String[] th;
String str;
String picturepath,currentpath;
Button b;
String r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lnrImages = (LinearLayout)findViewById(R.id.lnrImages);
btnAddPhots = (Button)findViewById(R.id.btnAddPhots);
btnSaveImages = (Button)findViewById(R.id.btnSaveImages);
b=(Button)findViewById(R.id.btnSaveImages1);
btnAddPhots.setOnClickListener(this);
btnSaveImages.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddPhots:
Intent intent = new Intent(MainActivity.this,CustomPhotoGalleryActivity.class);
startActivityForResult(intent,PICK_IMAGE_MULTIPLE);
break;
case R.id.btnSaveImages:
if(imagesPathList !=null){
if(imagesPathList.size()>=1) {
File f = new File("" + r);
Log.e("File", "" + f);
doFileUpload(f);
Log.d("saveimages", "" + imagesPathList);
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of image are selected", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this," no images are selected", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void doFileUpload(File f) {
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST, 21);
Log.e("clientconnect", "" + client);
client.login(FTP_USER, FTP_PASS);
Log.e("clientlogin", "" + client);
client.setType(FTPClient.TYPE_BINARY);
Log.e("clienttype", "" + client);
client.changeDirectory("/real/");
Log.i("", "$$$$$$$$$$$$$$$$$" + ("/real/"));
// int reply = client.getReplyCode();
client.upload(f, new MyTransferListener());
// Log.e("filenameupload", "" + photoFile);
Log.e("clientupload", "" + client);
// Log.e("file",""+fileName);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
// btn.setVisibility(View.GONE);
// Transfer started
Toast.makeText(getApplicationContext(), " Upload Started ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" Upload Started ...");
}
public void transferred(int length) {
// Yet other length bytes has been transferred since the last time
// this
// method was called
Toast.makeText(getApplicationContext(),
" transferred ..." + length, Toast.LENGTH_SHORT).show();
// System.out.println(" transferred ..." + length);
}
public void completed() {
// btn.setVisibility(View.VISIBLE);
// Transfer completed
Toast.makeText(getApplicationContext(), " completed ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" completed ..." );
}
public void aborted() {
// btn.setVisibility(View.VISIBLE);
// Transfer aborted
Toast.makeText(getApplicationContext(),
" transfer aborted , please try again...",
Toast.LENGTH_SHORT).show();
// System.out.println(" aborted ..." );
}
public void failed() {
// btn.setVisibility(View.VISIBLE);
// Transfer failed
System.out.println(" failed ...");
}
// Jibble.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode ==Activity.RESULT_OK
&& null != data) {
//uri=data.getData();
// System.out.println("Current image Path is ----->" + getRealPathFromURI(uri));
imagesPathList = new ArrayList<String>();
String[] imagesPath = data.getStringExtra("data").split("\\|");
try{
lnrImages.removeAllViews();
}catch (Throwable e){
e.printStackTrace();
}
for (int i=0;i<imagesPath.length;i++){
Log.e("imagesPath can", ""+imagesPath);
imagesPathList.add(imagesPath[i]);
Log.w("imagesPathList are", ""+imagesPathList);
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
Log.d("yourbitmap is", ""+yourbitmap);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
lnrImages.addView(imageView);
String listString = "";
for (String s : imagesPathList)
{
listString += s + "\t";
}
j=listString.toString();
uri=Uri.parse(j);
r=uri.toString();
Log.d("mnmnmnmnmnmnmhjjuigyigsuiagducfuducgfasicfgds", ""+r);
Log.d("anananananananananananananananananananananannananand", ""+uri);
}
}
}
private void decodeFile(String picturePath) {
// TODO Auto-generated method stub
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
yourbitmap = BitmapFactory.decodeFile(picturePath, o2);
}}
Public class MainActivity extends Activity implements View.OnClickListener {
private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE = 1;
static final String FTP_HOST = "";
static final String FTP_USER = "";
static final String FTP_PASS = "";
String j;
Uri uri;
String str;
String picturepath, currentpath;
Button b;
String r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lnrImages = (LinearLayout) findViewById(R.id.lnrImages);
btnAddPhots = (Button) findViewById(R.id.btnAddPhots);
btnSaveImages = (Button) findViewById(R.id.btnSaveImages);
b = (Button) findViewById(R.id.btnSaveImages1);
btnAddPhots.setOnClickListener(this);
btnSaveImages.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddPhots:
Intent intent = new Intent(MainActivity.this,
CustomPhotoGalleryActivity.class);
startActivityForResult(intent, PICK_IMAGE_MULTIPLE);
break;
case R.id.btnSaveImages:
//upload multiple images
if (imagesPathList != null) {
if (imagesPathList.size() >= 1) {
for (int i = 0; i < imagesPath.length; i++) {
String strImg = imagesPath[i];
File f = new File("" + strImg);
Log.e("File", "" + f);
doFileUpload(f);
Log.d("saveimages", "" + imagesPathList);
}
Toast.makeText(
MainActivity.this,
imagesPathList.size()
+ " no of images are selected",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
MainActivity.this,
imagesPathList.size() + " no of image are selected",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, " no images are selected",
Toast.LENGTH_SHORT).show();
}
break;
}
}
public void doFileUpload(File f) {
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST, 21);
Log.e("clientconnect", "" + client);
client.login(FTP_USER, FTP_PASS);
Log.e("clientlogin", "" + client);
client.setType(FTPClient.TYPE_BINARY);
Log.e("clienttype", "" + client);
client.changeDirectory("/ramesh2/");
Log.i("", "$$$$$$$$$$$$$$$$$" + ("/ramesh2/"));
// int reply = client.getReplyCode();
client.upload(f, new MyTransferListener());
// Log.e("filenameupload", "" + photoFile);
Log.e("clientupload", "" + client);
// Log.e("file",""+fileName);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
// btn.setVisibility(View.GONE);
// Transfer started
Toast.makeText(getApplicationContext(), " Upload Started ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" Upload Started ...");
}
public void transferred(int length) {
// Yet other length bytes has been transferred since the last time
// this
// method was called
Toast.makeText(getApplicationContext(),
" transferred ..." + length, Toast.LENGTH_SHORT).show();
// System.out.println(" transferred ..." + length);
}
public void completed() {
// btn.setVisibility(View.VISIBLE);
// Transfer completed
Toast.makeText(getApplicationContext(), " completed ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" completed ..." );
}
public void aborted() {
// btn.setVisibility(View.VISIBLE);
// Transfer aborted
Toast.makeText(getApplicationContext(),
" transfer aborted , please try again...",
Toast.LENGTH_SHORT).show();
// System.out.println(" aborted ..." );
}
public void failed() {
// btn.setVisibility(View.VISIBLE);
// Transfer failed
System.out.println(" failed ...");
}
// Jibble.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_MULTIPLE
&& resultCode == Activity.RESULT_OK && null != data) {
// uri=data.getData();
// System.out.println("Current image Path is ----->" +
// getRealPathFromURI(uri));
imagesPathList = new ArrayList<String>();
imagesPath = data.getStringExtra("data").split("\\|");
try {
lnrImages.removeAllViews();
} catch (Throwable e) {
e.printStackTrace();
}
for (int i = 0; i < imagesPath.length; i++) {
Log.e("imagesPath can", "" + imagesPath);
imagesPathList.add(imagesPath[i]);
Log.w("imagesPathList are", "" + imagesPathList);
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
Log.d("yourbitmap is", "" + yourbitmap);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
lnrImages.addView(imageView);
String listString = "";
for (String s : imagesPathList) {
listString += s + "\t";
}
j = listString.toString();
uri = Uri.parse(j);
r = uri.toString();
Log.d("mnmnmnmnmnmnmhjjuigyigsuiagducfuducgfasicfgds", "" + r);
Log.d("anananananananananananananananananananananannananand",
"" + uri);
}
}
}
I am working on an Andorid application in which I would like the user to take a picture and then to save it I am sending it over to the server. Now, I am sending the picture as a byte-array to the server. When I try to save the byte-array to a file as a PNG file, and then try to open the file, the image-viewer complains that the PNG has errors and cannot be displayed. The PNG file size was 122Kb.
When I tried to use Scalr library to resize the image, it says the image source cannot be null. Directly saving the byte-array is causing a corrupt PNG. How should I convert and send the file properly to server, so there are no errors.
Here is the code for camera which I am using and sending it over.
public class AddPhotoForUser extends DrawerLoader {
private static final int CAMERA_PIC_REQUEST = 22;
Button BtnSelectImage;
private ImageView ImgPhoto;
private static volatile Bitmap photo;
private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();
final PersonServiceImpl personService = new PersonServiceImpl();
private String[] navMenuTitles;
private TypedArray navMenuIcons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_user_photo);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.INVISIBLE);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
uploadImage();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
startActivity(intent);
finish();
}
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(AddPhotoForUser.this, Login.class);
startActivity(intent);
finish();
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode == RESULT_OK) {
try {
photo = (Bitmap) data.getExtras().get("data");
if (!(photo == null)) {
ImgPhoto.setImageBitmap(photo);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void uploadImage() {
if (!(photo == null)) {
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
personService.addUserProfilePhoto(byteArray);
}
}
}
Here is the server side code to save the image to disk :
#Override
public Boolean updateProfilePhoto(byte[] photo) {
Person person = getCurrentlyAuthenticatedPerson();
try{
InputStream in = new ByteArrayInputStream(photo);
BufferedImage image = ImageIO.read(in);
image = Scalr.resize(image, Scalr.Method.QUALITY, 100, 100);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
baos.flush();
File file = new File(userImagePath);
if (file.exists() && file.isDirectory()) {
OutputStream outputStream = new FileOutputStream(new File(userImagePath + person.getUserId()+".png"));
outputStream.write(baos.toByteArray());
outputStream.close();
} else {
File file1 = new File(userImagePath+person.getUserId()+".png");
if (file1.exists()) {
try {
OutputStream outputStream = new FileOutputStream(file1);
outputStream.write(baos.toByteArray());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
boolean result = file1.createNewFile();
System.out.println("Result of file1 creation is "+result);
OutputStream outputStream = new FileOutputStream(file1);
outputStream.write(baos.toByteArray());
outputStream.close();
}
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
If I don't use the Scalr library, there are no errors, but its a corrupt file. Here is the Scalr error log :
java.lang.IllegalArgumentException: src cannot be null
at org.imgscalr.Scalr.resize(Scalr.java:1564)
at org.imgscalr.Scalr.resize(Scalr.java:1415)
at com.journaldev.spring.service.PersonServiceImpl.updateProfilePhoto(PersonServiceImpl.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy51.updateProfilePhoto(Unknown Source)
at com.journaldev.spring.Controller.PersonController.addProfilePhotoForUser(PersonController.java:100)
Any help would be nice. Thanks a lot. :-)
Updated code
public class AddPhotoForUser extends DrawerLoader {
Button BtnSelectImage;
private ImageView ImgPhoto;
private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();
final PersonServiceImpl personService = new PersonServiceImpl();
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
Bitmap reducedSizeBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_user_photo);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.INVISIBLE);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
uploadImage();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
startActivity(intent);
finish();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 12000000; // 12MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(AddPhotoForUser.this, Login.class);
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage() {
if(!(reducedSizeBitmap == null)){
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.personService.addUserProfilePhoto(byteArray);
}
}
}
If you use Bundle extras = data.getExtras(); in your onActivityResult() then it will return thumbnail image not actual image.
Here is code I have used for Capturing and Saving Camera Image then display it to ImageView. You can use according to your need.
You have to save Camera image to specific location then fetch from that location then convert it to byte-array.
Here is method for opening capturing camera image activity.
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
then your onActivityResult() method should be like this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
EDIT:
Here is method for uploading image to server.
/**
* Upload Image to server
*
* #param file image to be saved
* #param compressorQuality quality of image
* #return path of uploaded image in server
*/
private String uploadImage(Bitmap file, int compressorQuality) {
String final_upload_filename = "demo_image.png";
String response = null;
HttpURLConnection conn = null;
try {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------14737809831466499882746641449";
URL url = new URL("image_upload_url");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", final_upload_filename);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes(lineEnd);
file.compress(CompressFormat.PNG, compressorQuality, dos);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
byte[] bytes = new byte[1024];
while ((bytesRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytesRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
response = new String(bytesReceived);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
You need to make upload script in backend server to store image data in particular folder.
I hope it helps!
At first you need to create a file and save image on it and here's a code.
//method to save image in internal or external storage
private void storeImage(Bitmap image,String imageName) {
File pictureFile = getOutputMediaFile(imageName);
if (pictureFile == null) {
Log.d(TAG,"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
//method to create file to save image on it
private File getOutputMediaFile(String imageName){
//create folder with name FoursquareAPI
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/FoursquareAPI");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
File mediaFile;
String mImageName= imageName +".png";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
I am building my own camera app using the android camera api. I have a working app but the preview is not as sharp as the default camera app. Why is this the case? Here is my code below.
public class showCamera extends SurfaceView implements SurfaceHolder.Callback {
private static final int PICTURE_SIZE_MAX_WIDTH =640;
private static final int PREVIEW_SIZE_MAX_WIDTH = 640;
//private Camera theCamera;
private SurfaceHolder holdMe;
private Camera theCamera;
int h;
int w;
public showCamera (Context context,Camera camera,int w,int h)
{
super(context);
theCamera = camera;
holdMe = getHolder();
holdMe.addCallback(this);
this.h=h;
this.w=w;
}
public showCamera(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
theCamera.setPreviewDisplay(holder);
//setDisplayOrientation(theCamera,90);
if( (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ))
{ theCamera.setDisplayOrientation(90);
}
Camera.Parameters parameters = theCamera.getParameters();
Log.d(" " , " THIS IS THE FLASH MODE = " + parameters.getFlashMode()) ;
List<String> g= parameters.getSupportedFocusModes();
for(int j=0;j<g.size();j++)
{
Log.d(" " , " THIS IS focus modes =" + g.get(j)) ;
}
Size bestPreviewSize = determineBestPreviewSize(parameters);
Size bestPictureSize = determineBestPictureSize(parameters);
parameters.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height);
parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
theCamera.setParameters(parameters);
theCamera.startPreview();
} catch (IOException e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
theCamera.stopPreview();
theCamera.release();
// TODO Auto-generated method stub
}
protected void setDisplayOrientation(Camera camera, int angle){
Method downPolymorphic;
try
{
downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (downPolymorphic != null)
downPolymorphic.invoke(camera, new Object[] { angle });
}
catch (Exception e1)
{
}
}
private Size determineBestPreviewSize(Camera.Parameters parameters) {
List<Size> sizes = parameters.getSupportedPreviewSizes();
return determineBestSize(sizes, PREVIEW_SIZE_MAX_WIDTH);
}
private Size determineBestPictureSize(Camera.Parameters parameters) {
List<Size> sizes = parameters.getSupportedPictureSizes();
return determineBestSize(sizes, PICTURE_SIZE_MAX_WIDTH);
}
protected Size determineBestSize(List<Size> sizes, int widthThreshold) {
Size bestSize = null;
for (Size currentSize : sizes) {
boolean isDesiredRatio = (currentSize.width / 4) == (currentSize.height / 3);
boolean isBetterSize = (bestSize == null || currentSize.width > bestSize.width);
boolean isInBounds = currentSize.width <= PICTURE_SIZE_MAX_WIDTH;
if (isDesiredRatio && isInBounds && isBetterSize) {
bestSize = currentSize;
}
}
if (bestSize == null) {
return sizes.get(0);
}
return bestSize;
}
AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
Log.i("tag","this ran sdfgfhgjkldxbvnm,jhgfdkmn" );
}
};
}
MainActivity
public class MainActivity extends Activity implements OnClickListener {
private Camera cameraObject;
private showCamera showCamera;
int h;
int w = 1080;
LinearLayout Top, Buttom;
Button b;
public static Camera isCameraAvailiable() {
Camera object = null;
try {
object = Camera.open();
object.getParameters();
} catch (Exception e) {
}
return object;
}
AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
Log.i("tag", "this ran sdfgfhgjkldxbvnm,jhgfdkmn");
}
};
private PictureCallback capturedIt = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if (bitmap == null) {
Toast.makeText(getApplicationContext(), "not taken",
Toast.LENGTH_SHORT).show();
} else {
File pictureFile = MediaOutput();
if (pictureFile == null) {
Log.d("",
"Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, "testing ", "");
Toast.makeText(getApplicationContext(), "taken",
Toast.LENGTH_SHORT).show();
fos.close();
} catch (FileNotFoundException e) {
Log.d("", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("", "Error accessing file: " + e.getMessage());
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camlay);
Top = (LinearLayout) findViewById(R.id.top_bar);
Buttom = (LinearLayout) findViewById(R.id.but_bar);
b = (Button) findViewById(R.id.but_pic);
b.setOnClickListener(this);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
h = (int) Math.round(0.8 * height);
Log.d(" ", " height " + h);
Log.d(" ", " width " + width);
Top.setLayoutParams(new LinearLayout.LayoutParams(width, (int) Math
.round(0.10 * height)));
Buttom.setLayoutParams(new LinearLayout.LayoutParams(width, (int) Math
.round(0.10 * height)));
cameraObject = isCameraAvailiable();
showCamera = new showCamera(this, cameraObject, width, h);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(showCamera, new FrameLayout.LayoutParams(width, h));
// preview.addView(showCamera);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.but_pic:
// cameraObject.takePicture(null, null,capturedIt);
// parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
Camera.Parameters parameters = cameraObject.getParameters();
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
cameraObject.setParameters(parameters);
cameraObject.autoFocus(autoFocusCallback);
// cameraObject.stopPreview();
break;
}
}
private static File MediaOutput() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
If you can point me in the right direction that would be great.
Did you ever tried to increase these values in your showCamera class:
private static final int PICTURE_SIZE_MAX_WIDTH = 640;
private static final int PREVIEW_SIZE_MAX_WIDTH = 640;
I created an application for outdoor navigation. But to demonstrate I used mock GPS. But it's ot working now. In my application this class has 2 buttons. When user select pause button it auto display as start. Then again user select start button then it will generate exception. This is the code i try to develop:
public class PathRecorderPauseActivity extends Activity implements
TextToSpeech.OnInitListener, OnLongClickListener, OnClickListener,
OnUtteranceCompletedListener {
private Button btnPause;
private TextView text;
private LocationManager manager;
private Button btnStop;
private boolean stop = true;
private LocationListener listener;
private boolean triger = true;
private boolean isIn = false;
private SQLiteOpenHelper dbHelper;
#SuppressWarnings("unused")
private Button btnShowDetails;
private MockGpsProvider mMockGpsProviderTask = null;
private Integer mMockGpsProviderIndex = 0;
private static final int MY_DATA_CHECK_CODE = 1234;
public static final String LOG_TAG = "MockGpsProviderActivity";
private static final String MOCK_GPS_PROVIDER_INDEX = "GpsMockProviderIndex";
// vibrator
//private Vibrator myVib;
private String speechText = "";
private TextToSpeech tts;
private ShakeListener mShaker;
private static final int REQUEST_CODE = 1234;
private static final String TAG = "VoiceRecognition";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pathrecorderpause);
Display display = getWindowManager().getDefaultDisplay();
int height = display.getHeight();
int width = display.getWidth();
if (savedInstanceState instanceof Bundle) {
mMockGpsProviderIndex = savedInstanceState.getInt(
MOCK_GPS_PROVIDER_INDEX, 0);
}
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
dbHelper = new DbConnect(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
/*
* db.execSQL("DROP TABLE tblPathInfo");
* db.execSQL("DROP TABLE tblPath");
*/
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ "tblPath(pathId INTEGER PRIMARY KEY," + "source VARCHAR, "
+ "destination VARCHAR, " + "startTime VARCHAR, "
+ "endTime VARCHAR, " + "distance DOUBLE);");
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ "tblPathInfo(infoId INTEGER PRIMARY KEY,"
+ "pathId INTERGER, " + "lat DOUBLE, " + "lon DOUBLE, "
+ "curLocation VARCHAR);");
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String curentDateandTime = sdf.format(new Date());
Log.d("Time", curentDateandTime);
db.execSQL("INSERT INTO tblPath (pathId,distance,startTime) VALUES ((SELECT max(pathId) FROM tblPath) + 1 ,0,'"
+ curentDateandTime + "')");
db.close();
btnPause = (Button) findViewById(R.id.btnPause);
btnPause.setOnLongClickListener(this);
btnPause.setOnClickListener(this);
// btnPause.setOnTouchListener(this);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnLongClickListener(this);
btnStop.setOnClickListener(this);
// btnStop.setOnTouchListener(this);
// vibration
/*myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
int dot = 200;
int long_gap = 100;
long[] pattern = { 0, // Start immediately
dot, long_gap, dot, long_gap, dot, long_gap, dot, long_gap
};*/
// Only perform this pattern one time (-1 means "do not repeat")
//myVib.vibrate(pattern, -1);
// vibration closed
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
public void onShake() {
if (tts.isSpeaking()) {
tts.stop();
}
}
});
final TextView tv = (TextView) findViewById(R.id.textView7);
tv.setText(String.valueOf(height) + "X" + String.valueOf(width));
View vw = (View) findViewById(R.id.view1); // middle one
vw.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_MOVE) {
Log.d("TouchTest", "ACTION_MOVE");
tv.setText(String.valueOf(event.getX()) + " X "
+ String.valueOf(event.getY()));
if ((event.getX() >= 15 && event.getX() <= 305)
&& (event.getY() >= 60 && event.getY() <= 224)) {
if (isIn == false) {
PathRecorderActivity.tts.speak("Stop",
TextToSpeech.QUEUE_FLUSH, null);
isIn = true;
}
}
else if ((event.getX() >= 15 && event.getX() <= 310)
&& (event.getY() >= 245 && event.getY() <= 403)) {
if (isIn == false) {
PathRecorderActivity.tts.speak("Pause",
TextToSpeech.QUEUE_FLUSH, null);
isIn = true;
}
}
else {
isIn = false;
}
}
return true;
}
});
if (AppConstants.VoiceOrTouch.vot == 1) {
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
// startVoiceRecognitionActivity();
}
}
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new LocationListener() {
private JSONObject currentLocJSON;
private String currentLocationInfo;
private String locationName;
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Log.i("currentLocationInfo -- ", location.getLatitude() + " : "
+ location.getLongitude());
/*
* text = (TextView) findViewById(R.id.textView7);
*
* text.setText("Latitude : " + location.getLatitude() +
* "X Longitude : " + location.getLongitude());
*/
currentLocationInfo = MapConstants.GetConstantLocationInfo(
location.getLatitude(), location.getLongitude());
//if (currentLocationInfo == null) {
// currentLocJSON = getLocationInfoAsJSON(
// location.getLatitude(), location.getLongitude());
// currentLocationInfo = getLocationInfo(currentLocJSON);
//}
Log.i("currentLocationInfo -- ", currentLocationInfo);
Toast.makeText(getApplicationContext(), currentLocationInfo,
Toast.LENGTH_SHORT).show();
insertLocationDatailsToDB(location, currentLocationInfo);
}
private void insertLocationDatailsToDB(Location location,
String currentLocationInfo) {
double latOld = 0;
double lonOld = 0;
double newDistance;
text.setText("Current Location = " + currentLocationInfo
+ " | Latitude = " + location.getLatitude()
+ " | Longitude = " + location.getLongitude());
// Log.i("insertLocationDatailsToDB", "4");
SQLiteDatabase db = dbHelper.getWritableDatabase();
// Log.i("insertLocationDatailsToDB", "5");
// check if there a source name inserted pathTbl
if (triger == true) {
// Log.i("insertLocationDatailsToDB", "6");
db.execSQL("UPDATE tblPath SET source = '"
+ currentLocationInfo
+ "' WHERE pathId = (SELECT max(pathId) FROM tblPath);");
db.execSQL("INSERT INTO tblPathInfo (infoId,pathId,lat,lon,curLocation) VALUES ((SELECT max(infoId) FROM tblPathInfo) + 1 ,"
+ "(SELECT max(pathId) FROM tblPath),"
+ location.getLatitude()
+ ", "
+ location.getLongitude()
+ ",'"
+ currentLocationInfo + "' )");
triger = false;
} else {
// Log.i("insertLocationDatailsToDB", "7");
db.execSQL("INSERT INTO tblPathInfo (infoId,pathId,lat,lon,curLocation) VALUES ((SELECT max(infoId) FROM tblPathInfo) + 1 ,"
+ "(SELECT max(pathId) FROM tblPath),"
+ location.getLatitude()
+ ", "
+ location.getLongitude()
+ ",'"
+ currentLocationInfo + "' )");
Cursor cur = db
.rawQuery(
"SELECT lat,lon,pathId FROM tblPathInfo WHERE pathId = (SELECT max(pathId) FROM tblPath) AND "
+ "infoId=((SELECT max(infoId) FROM tblPathInfo) - 1);",
null);
if (cur.moveToNext()) {
latOld = cur.getDouble(0);
lonOld = cur.getDouble(1);
AppConstants.DataConstants.SELECTED_PATH_ID = cur
.getString(2);
}
Location oldLoc = new Location("oldLocation");
oldLoc.setLatitude(latOld);
oldLoc.setLongitude(lonOld);
newDistance = location.distanceTo(oldLoc);
db.execSQL("UPDATE tblPath SET distance = distance + "
+ newDistance
+ " WHERE pathId = (SELECT max(pathId) FROM tblPath);");
}
db.close();
}
/**
*
* #param currentLocJSON
* this is JSON object which contains the location
* details according to the passed Latitude & Longitude
* value..
* #return String result which should be the location name which we
* requested and returned as JSON from google api's We split
* the most suitable result from the JSON request
*/
private String getLocationInfo(JSONObject currentLocJSON) {
JSONArray jArray = null;
try {
jArray = currentLocJSON.getJSONArray("results");
// Check is there any details available by checking the JSON
// request
if (jArray.length() != 0) {
for (int i = 0; i < jArray.length(); i++) {
locationName = jArray.getJSONObject(0)
.getJSONArray("address_components")
.getJSONObject(i).getString("long_name");
if (locationName != null) {
Toast.makeText(getApplicationContext(),
locationName, Toast.LENGTH_SHORT)
.show();
break;
}
}
}
} catch (JSONException e) {
text.setText("JSONException");
e.printStackTrace();
}
return locationName;
}
/**
*
* #param latitude
* #param longitude
* #return JSON Object This function get latitude & longitude and
* pass them in to the maps.googleapis.com server and get
* location details as JSON result
*/
private JSONObject getLocationInfoAsJSON(double latitude,
double longitude) {
StringBuilder stringBuilder = new StringBuilder();
try {
HttpPost httppost = new HttpPost(
"http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latitude + "," + longitude
+ "&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
text.setText("ClientProtocolException");
} catch (IOException e) {
text.setText("IOException");
} catch (Exception e) {
text.setText("Exception");
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
text.setText("JSONException");
e.printStackTrace();
}
return jsonObject;
}
};
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
listener);
} else if (!manager
.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
manager.addTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER, false,
false, false, false, true, false, false, 0, 5);
manager.setTestProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER,
true);
}
if (manager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
manager.requestLocationUpdates(MockGpsProvider.GPS_MOCK_PROVIDER,
0, 0, listener);
try {
List<String> data = new ArrayList<String>();
Log.d("LeeInuka", "1");
InputStream is = getAssets().open("mock_gps_data.csv");
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
Log.d("LeeInuka", "2");
String line = null;
while ((line = reader.readLine()) != null) {
data.add(line);
// Log.d("Lee", line);
Log.d("LeeInuka", "3");
}
Log.d("LeeInuka", "4");
String[] coordinates = new String[data.size()];
data.toArray(coordinates);
mMockGpsProviderTask = new MockGpsProvider();
mMockGpsProviderTask.execute(coordinates);
} catch (Exception e) {
Log.d("MOKE", "........");
}
}
// manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10,
// listener);
/***
* Pause/Start Recording Button
*/
btnPause = (Button) findViewById(R.id.btnPause);
/***
* Stop Recording Button
*/
btnStop = (Button) findViewById(R.id.btnStop);
btnShowDetails = (Button) findViewById(R.id.button1);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// store where we are before closing the app, so we can skip to the
// location right away when restarting
savedInstanceState.putInt(MOCK_GPS_PROVIDER_INDEX,
mMockGpsProviderIndex);
super.onSaveInstanceState(savedInstanceState);
}
// Tharika changed vibration
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPause:
tts.speak("Pause", TextToSpeech.QUEUE_FLUSH, null);
// myVib.vibrate(100);
break;
case R.id.btnStop:
tts.speak("Stop", TextToSpeech.QUEUE_FLUSH, null);
// myVib.vibrate(100);
break;
default:
break;
}
}
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.btnPause:
if (stop) {
stop = false;
// Log.d("btn_stop", "Path Recording has been Paused");
btnPause.setBackgroundResource(R.drawable.btn_start);
tts.speak("Path Recording has been Paused",
TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(),
"Path Recording has been Paused", Toast.LENGTH_LONG)
.show();
manager.removeUpdates(listener);
}
else {
manager.requestLocationUpdates(
MockGpsProvider.GPS_MOCK_PROVIDER, 0, 0, listener);
btnPause.setBackgroundResource(R.drawable.btn_pause);
tts.speak("Path Recording has been started",
TextToSpeech.QUEUE_FLUSH, null);
stop = true;
}
break;
case R.id.btnStop:
Toast.makeText(getApplicationContext(),
"Path Recording has been Stoped", Toast.LENGTH_LONG).show();
tts.speak("Path Recording has been Stoped",
TextToSpeech.QUEUE_FLUSH, null);
try {
mMockGpsProviderTask.cancel(true);
mMockGpsProviderTask = null;
} catch (Exception e) {
}
try {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager
.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER);
} catch (Exception e) {
}
manager.removeUpdates(listener);
SQLiteDatabase db = dbHelper.getWritableDatabase();
SimpleDateFormat sdf_1 = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String curentEndDateandTime = sdf_1.format(new Date());
db.execSQL("UPDATE tblPath SET destination = (SELECT curLocation FROM tblPathInfo WHERE infoId = (SELECT max(infoId) FROM tblPathInfo) ) , endTime = '"
+ curentEndDateandTime
+ "' WHERE pathId = (SELECT max(pathId) FROM tblPath);");
db.close();
db = dbHelper.getReadableDatabase();
Cursor cu2 = db.rawQuery("SELECT max(pathId) FROM tblPath;", null);
if (cu2.moveToNext()) {
AppConstants.DataConstants.SELECTED_PATH_ID = cu2.getString(0);
}
db.close();
startActivity(new Intent(PathRecorderPauseActivity.this,
ShortCutPathActivity.class));
Toast.makeText(getApplicationContext(),
"Path has been recorded successfully", Toast.LENGTH_LONG);
finish();
break;
case R.id.button1:
String testData = "";
String testData1 = "";
db = dbHelper.getReadableDatabase();
Cursor cu = db
.rawQuery(
"SELECT * FROM tblPathInfo WHERE pathId = (SELECT max(pathId) FROM tblPath);",
null);
while (cu.moveToNext()) {
testData = testData + " ********** currentLoc : "
+ cu.getString(4) + " & lat : " + cu.getString(2)
+ " & lon : " + cu.getString(3);
}
Toast.makeText(getApplicationContext(), testData,
Toast.LENGTH_SHORT).show();
Cursor cu1 = db
.rawQuery(
"SELECT * FROM tblPath WHERE pathId = (SELECT max(pathId) FROM tblPath);",
null);
if (cu1.moveToNext()) {
testData1 = cu1.getString(0) + " | " + cu1.getString(1) + " | "
+ " | " + cu1.getString(2) + " | " + cu1.getString(3)
+ " | " + cu1.getString(4) + " | " + cu1.getString(5);
}
Toast.makeText(getApplicationContext(), testData1,
Toast.LENGTH_LONG).show();
db.close();
default:
break;
}
return true;
}
public void onInit(int status) {
if (AppConstants.VoiceOrTouch.vot == 0) {
tts.speak(
"Service is runing.Panel 3.It has two buttons.First button is Stop"
+ "It is top on the screen.Second button is Pause.It is bottom on the screen."
+ "If you choose stop it will stop the recording."
+ "And if you choose Pause it will temporally stop the recording."
+ "Please touch or give single tap to identify the buttons."
+ "Please long press the button that you want to navigate.",
TextToSpeech.QUEUE_FLUSH, null);
}
else if (AppConstants.VoiceOrTouch.vot == 1) {
speechText = "Panel 3.It has two options as stop and paues."
+ "Please say stop to stop the recording path."
+ "Please say pause to pause the recording path.";
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "ourVoice");
tts.setOnUtteranceCompletedListener(this);
tts.speak(speechText, TextToSpeech.QUEUE_FLUSH, hm);
}
if (status == TextToSpeech.SUCCESS) {
if (tts.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
tts.setLanguage(Locale.US);
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
}
else if (requestCode == REQUEST_CODE && resultCode == RESULT_OK
&& AppConstants.VoiceOrTouch.vot == 1) {
// Log.d("Here", "Here");
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for (String bestMatch : matches) {
if (bestMatch.contains("stop") || bestMatch.contains("sup")
|| bestMatch.contains("pop")
|| bestMatch.contains("map")) {
Intent my = new Intent(getApplicationContext(),
RecordingDetailsActivity.class);
startActivityForResult(my, 0);
break;
}
else if (bestMatch.contains("Pause")
|| bestMatch.contains("false")
|| bestMatch.contains("fox")
|| bestMatch.contains("post")
|| bestMatch.contains("font")) {
// Intent my = new Intent(getApplicationContext(),
// PathRecorderPause.class);
// startActivityForResult(my, 0);
break;
}
else {
// Log.i(TAG, "COMMAND_NOT_MATCHING");
}
}
}
else if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA) {
// missing data, install it
Intent installIntent = new Intent();
installIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
super.onActivityResult(requestCode, resultCode, data);
}
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.stop();
tts.shutdown();
}
try {
mMockGpsProviderTask.cancel(true);
mMockGpsProviderTask = null;
} catch (Exception e) {
Log.d("mMockGpsProviderTask", e.getMessage());
}
try {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager
.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER);
} catch (Exception e) {
Log.d("LocationManager", e.getMessage());
}
}
#Override
public void onResume() {
mShaker.resume();
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onResume();
}
#Override
public void onPause() {
mShaker.pause();
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onPause();
try {
mMockGpsProviderTask.cancel(true);
mMockGpsProviderTask = null;
} catch (Exception e) {
}
try {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager
.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER);
} catch (Exception e) {
}
}
private class MockGpsProvider extends AsyncTask<String, Integer, Void> {
public static final String LOG_TAG = "GpsMockProvider";
public static final String GPS_MOCK_PROVIDER = "GpsMockProvider";
/** Keeps track of the currently processed coordinate. */
public Integer index = 0;
#Override
protected Void doInBackground(String... data) {
for (String str : data) {
if (index < mMockGpsProviderIndex) {
index++;
continue;
}
publishProgress(index);
Double latitude = null;
Double longitude = null;
Double altitude = null;
try {
String[] parts = str.split(",");
latitude = Double.valueOf(parts[0]);
longitude = Double.valueOf(parts[1]);
altitude = Double.valueOf(parts[2]);
} catch (NullPointerException e) {
break;
} catch (Exception e) {
continue;
}
Location location = new Location(GPS_MOCK_PROVIDER);
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setAltitude(altitude);
location.setTime(System.currentTimeMillis());
Log.d(LOG_TAG + "-Inuka", location.toString());
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.setTestProviderLocation(GPS_MOCK_PROVIDER,
location);
try {
Log.d(LOG_TAG + "_Traed", "22222");
Thread.sleep(5000);
Log.d(LOG_TAG + "_Traed", "22222w");
if (Thread.currentThread().isInterrupted())
throw new InterruptedException("");
} catch (InterruptedException e) {
Log.d(LOG_TAG + "_Traed", "Exception " + e.getMessage());
break;
}
index++;
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
Log.d(LOG_TAG + "-2Inuka", "onProgressUpdate(): " + values[0]);
mMockGpsProviderIndex = values[0];
}
}
public void onUtteranceCompleted(String utteranceId) {
Log.d("TTS", "On Finish()");
startVoiceRecognitionActivity();
tts.shutdown();
tts = null;
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "");
startActivityForResult(intent, REQUEST_CODE);
}
}