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);
}
}
}
Related
Im trying to develope a function so i can upload pictures into my intern database in Android Studios. Has somebody an idea how i can solve this?
Well , first thing you need to add two button to select picture and to submit upload picture something like ..
Button Buttonlog;
Button Buttonbro;
ProgressBar progressBar;
private TextView messageText;
private TextView file-token-name;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
private ImageView imageview;
private static final int PICK_IMAGE_GALLERY = 1;
#SuppressLint("ClickableViewAccessibility")
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main15);
file-token-name=findViewById(R.id.filename);
file-token-name.setVisibility(View.GONE);
Buttonbro = findViewById(R.id.button_selectpic);
Buttonbro.setVisibility(View.VISIBLE);
Buttonbro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity15.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity15.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_IMAGE_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
loadGallery();
}
});
progressBar = findViewById(R.id.progress);
imageview = findViewById(R.id.imageView_pic);
upLoadServerUri = "https://www.yoursite.net/upljsonfile.php";
Buttonlog.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
final String file1;
file1=file-token-name.getText().toString();
//Start ProgressBar first (Set visibility VISIBLE)
progressBar.setVisibility(View.VISIBLE);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//Starting Write and Read data with URL
//Creating array for parameters
String[] field = new String[1];
field[0] = "file1";
//Creating array for data
final String[] data = new String[1];
data[0] = file1;
if (!isFinishing()) {
PutData putData = new PutData("https://www.yorwebsite.net/post-to-database-file-name.php", "POST", field, data);
if (putData.startPut()) {
if (putData.onComplete()) {
progressBar.setVisibility(View.GONE);
String result = putData.getResult();
//End ProgressBar (Set visibility to GONE
if (result.equals("Post Succssefl")) {
if (!file1.equals("")) {
dialog = ProgressDialog.show(MainActivity15.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
// dialog = new ProgressDialog(MainActivity15.this);
// dialog.setMessage("Uploading File");
// dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setIndeterminate(true);
dialog.setMax(100);
dialog.show();
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
if (isFinishing()) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
isFinishing();
}
}
}
}); //End Write and Read data with URL
}
});
}
And then our loadGallery() func
private void loadGallery() {
Intent choose = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choose, PICK_IMAGE_GALLERY);
}
after that you have to allow permission take your image select path something like ..
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressLint("Recycle")
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
if (requestCode == PICK_IMAGE_GALLERY) {// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
} //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#SuppressLint({"SetTextI18n", "NewApi"})
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_GALLERY && data != null && resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
assert selectedImageUri != null;
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
String uriString = selectedImageUri.toString();
File myFile = new File(uriString);
String displayName;
if (uriString.startsWith("content://")) {
try (Cursor cursor = getContentResolver().query(selectedImageUri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
file-token-name.setText(displayName);
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
file-token-name.setText(displayName);
}
}
}
now we add our upload file func something like ..
#SuppressLint("LongLogTag")
public void uploadFile(String sourceFileUri) {
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
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("file", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
int sentBytes=0;
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
sentBytes += bufferSize;
int progres =(bytesRead * 100 / bytesAvailable);
new Thread(
// do your stuff
new publishProgress(progres)
).start();
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" C:/xamp/wamp/fileupload/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity15.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity15.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity15.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
} // End else block
}
fainaly .. our tow php file one to upload our file"upljsonfile.php",And second to post our file name to database "post-to-database-file-name.php", like code bellow ..
the first file "upljsonfile.php" :
<?php
$response = array();
if (empty($_FILES) || $_FILES['file']['error']) {
$response["code"] = 2;
$response["message"] = "failed to move uploaded file";
echo json_encode($response);
}
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = "uploadfiles/$fileName";
// Open temp file
$out = #fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = #fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open input Stream error occurred.";
echo json_encode($response);
#fclose($in);
#fclose($out);
#unlink($_FILES['file']['tmp_name']);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open output error occurred.";
echo json_encode($response);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$response["code"] = 2;
$response["message"] = "successfully uploaded";
echo json_encode($response);
?>
and the second file "post-to-database-file-name.php :
<?php
require "databasemob.php";
$db = new DataBase();
if (isset($_POST['file1']) ) {
if ($db->dbConnect()) {
if ($db->filenamepost("filename", $_POST['file1'])) {
echo "Post Succssefl";
} else echo "Some error !";
} else echo "Error: Database connection";
} else echo "All fields are required";
?>
and the databasemob.php :
<?php
require "DataBaseConfig.php";
class DataBase
{
public $connect;
public $data;
private $sql;
protected $servername;
protected $username;
protected $password;
protected $databasename;
public function __construct()
{
$this->connect = null;
$this->data = null;
$this->sql = null;
$dbc = new DataBaseConfig();
$this->servername = $dbc->servername;
$this->username = $dbc->username;
$this->password = $dbc->password;
$this->databasename = $dbc->databasename;
}
function dbConnect()
{
$this->connect = mysqli_connect($this->servername, $this->username, $this->password, $this->databasename);
return $this->connect;
}
function prepareData($data)
{
return mysqli_real_escape_string($this->connect, stripslashes(htmlspecialchars($data)));
}
function filenamepost($table, $file1)
{
$file1 = $this->prepareData($file1);
$ssq="SET NAMES 'utf8mb4';";
mysqli_query($this->connect,$ssq);
$this->sql =
"INSERT INTO " . $table . " (`file1`) VALUES ('" . $file1 . "')";
if (mysqli_query($this->connect, $this->sql)) {
return true;
} else return false;
}
}
?>
last file DataBaseConfig.php :
<?php
class DataBaseConfig
{
public $servername;
public $username;
public $password;
public $databasename;
public function __construct()
{
$this->servername = 'localhost';
$this->username = 'username';
$this->password = 'pass#';
$this->databasename = 'filename';
}
}
?>
this way its work by take ur file name from file Uri from phone and prosses for tow way by uploading file and post file to your database ,, hope it help you :)
I'm trying to write a code I can write all the results values from accelerometer sensor into a .txt file. I can't write all the data in somehow. I think there is a problem in my loop. It is just reading about 10 to 15 samples.
How can I write all the values of the sensor into that file until I toggle off the button to stop? here is the code I wrote.
Thanks in advance!
public class MainActivity extends Activity implements SensorEventListener {
public SensorManager sm;
Sensor accelermeter;
private static final String DEBUG = "LogAccelermeter";
ToggleButton OnStore;
Button OffStore;
Button btnOn, btnOff;
TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
TextView sensorText;
// String for MAC address
private static String address;
private GestureDetectorCompat mDetector;
FileOutputStream fileOutputStream;
double TotalAccelerate;
ArrayList<Double> list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<Double>();
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
//for Accelermeter
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorText = (TextView) findViewById(R.id.sensor);
accelermeter = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelermeter, SensorManager.SENSOR_DELAY_NORMAL);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStorageDirectory();
File dir = new File(Root.getAbsolutePath() + "/MyApp");
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, "MyMessage.txt");
try {
fileOutputStream = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "SDcard not found", Toast.LENGTH_LONG).show();
}
OnStore = (ToggleButton) findViewById(R.id.onStore);
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
// System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
// fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}if (!OnStore.isChecked()){
try {
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
list.clear();
Collections.synchronizedList(list);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
String sensor1 = recDataString.substring(6, 10); //same again...
String sensor2 = recDataString.substring(11, 15);
String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V"); //update the textviews with sensor values
sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
}//end OnCreate Method
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
//Find peak values.
public static ArrayList<Double> findPeaks(List<Double> points) {
ArrayList<Double> peaks = new ArrayList<Double>();
if (points == null || points.size() < 1)
return peaks;
Double x1_n_ref = 0.0;
int alpha = 0; //0=down, 1=up.
int size = points.size();// -1)/100;
for (int i = 0; i < size; i += 5) {
Double IndexValues = points.get(i);
if (IndexValues > 9) {
Double delta = (x1_n_ref - IndexValues);
if (delta < 0) {
x1_n_ref = IndexValues;
alpha = 1;
} else if (alpha == 1 && delta > 0) {
peaks.add(x1_n_ref);
alpha = 0;
}
} else if (alpha == 0) {
x1_n_ref = IndexValues;
}
}
return peaks;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onDown(MotionEvent event) {
Log.d(DEBUG_TAG, "onDown: " + event.toString());
Toast.makeText(getApplication(), "OnDown Touch Occur", Toast.LENGTH_LONG).show();
if (event.getX() > 0) {
mConnectedThread.write("1");
}
return true;
}
#Override
public void onLongPress(MotionEvent event) {
Log.d(DEBUG_TAG, "onLongPress: " + event.toString());
mConnectedThread.write("0");
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
#Override
public void onPause() {
super.onPause();
try {
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
Could you try this for the toggle button onClick callback? It should write all the data when it's unchecked.
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
// should do nothing
} else if (!OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
To regulate the code to start/stop listen to the sensor event, add the following variable somewhere in this class:
private boolean isListening = false;
And make the following modifications to your existing code:
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
//
// set listening flag to true
//
isListening = true;
} else if (!OnStore.isChecked()){
//
// set listening flag to false
//
isListening = false;
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
//
// regulate
//
if (isListening) {
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
}
I am new in android so, if you found any mistake please tell me.Now come to the point what i got the problem we click on image view then one popup will come and choose from where you want to upload the image so when we click on gallery then.
mProfileImageView.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
new AlertDialog.Builder(ProfileActivity.this)
.setTitle("Profile Picture")
.setMessage("change your profile picture with")
.setPositiveButton(R.string.capture_image, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// continue with delete
captureImage();
}
})
*//*.setNegativeButton(R.string.choose_image, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
chooseImage();
}
})*//*
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
public void chooseImage() {
try {
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, IMAGE_QUALITY_LOW);
i.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, 0);
i.putExtra(MediaStore.EXTRA_SIZE_LIMIT, IMAGE_MAX_SIZE);
i.setType("image/*");
//i.setAction(Intent.ACTION_GET_CONTENT);
/*i.putExtra("crop", "true");
i.putExtra("aspectX", 0);
i.putExtra("aspectY", 0);
i.putExtra("outputX", 400);
i.putExtra("outputY", 400);
i.putExtra("return-data", true);*/
startActivityForResult(Intent.createChooser(i, "Complete action using"), GALLERY_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Oops - your device doesn't have gallery!";
Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_LONG).show();
}
}
When we are scrollingG 10-20 gallery images and going for upload at that time it's crashing i don't know why?
try this:
java code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int SELECT_PICTURE = 100;
private static final String TAG = "MainActivity";
CoordinatorLayout coordinatorLayout;
FloatingActionButton btnSelectImage;
AppCompatImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find the views...
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
btnSelectImage = (FloatingActionButton) findViewById(R.id.btnSelectImage);
imgView = (AppCompatImageView) findViewById(R.id.imgView);
btnSelectImage.setOnClickListener(this);
}
/* Choose an image from Gallery */
void openImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
imgView.setImageURI(selectedImageUri);
}
}
}
}
/* Get the real path from the URI */
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
#Override
public void onClick(View v) {
openImageChooser();
}
}
Add Permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.AppCompatImageView
android:id="#+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/activity_horizontal_margin" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/btnSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_menu_gallery" />
</android.support.design.widget.CoordinatorLayout>
You are receiving an OutOfMemoryException since you are talking about several images. Here are your options:
Request a larger heap from the virtual machine by adding the following line into your AndroidManifest.xml in the application section: android:largeHeap="true"
Try to use images as small as possible for your gallery. Remeber: each image is stored uncompressed into your applications heap
Recycle images that are not visible at the moment using Bitmap.recycle() to free new memory.
Try this java code it works. I used it recently in my android app
Pop up
PopupWindow popup;
private void initiatePopupWindow() {
// TODO Auto-generated method stub
try {
LayoutInflater inflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.change_profileimg, null);
popup = new PopupWindow(layout, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
Button imagefromgallery = (Button) layout
.findViewById(R.id.imagefromgallery);
RelativeLayout relPopup = (RelativeLayout) layout.findViewById(R.id.relativeLayoutMainPopup);
Button captureimage = (Button) layout
.findViewById(R.id.captureimage);
imagefromgallery.setTypeface(Typeface.createFromAsset(getAssets(),
"fonts/OpenSans-Regular.ttf"));
captureimage.setTypeface(Typeface.createFromAsset(getAssets(),
"fonts/OpenSans-Regular.ttf"));
imagefromgallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
galleryPick();
popup.dismiss();
}
});
captureimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// takePhoto();
callCameraApp();
popup.dismiss();
}
});
relPopup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
}
});
popup.setOutsideTouchable(true);
popup.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
popup.dismiss();
return true;
}
return false;
}
});
popup.showAtLocation(layout, Gravity.BOTTOM, 0, 0);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Gallery pick
private void galleryPick() {
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gintent, "Select Picture"), PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
Call camera app
private void callCameraApp() {
Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
String fileName = "new-photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, fileName);
values.put(ImageColumns.DESCRIPTION, "Image captured by camera");
// imageUri is the current activity attribute, define and save it for
// later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
fileName = getPath(imageUri);
} catch (Exception e) {
// TODO: handle exception
}
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, PICK_Camera_IMAGE1);
}
then to get the bitmap
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"XYZ_");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("errorrr", "Oops! Failed create "
+ "XYZ_" + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
return mediaFile;
}
String filePath;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImageUri = null;
Uri selectedImagepicUri = null;
filePath = null;
switch (requestCode) {
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImageUri = imageUri;
/*
* Bitmap mPic = (Bitmap) data.getExtras().get("data");
* selectedImageUri =
* Uri.parse(MediaStore.Images.Media.insertImage
* (getContentResolver(), mPic,
* getResources().getString(R.string.app_name),
* Long.toString(System.currentTimeMillis())));
*/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
}
break;
case PICK_Camera_IMAGE1:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImagepicUri = imageUri;
/*
* Bitmap mPic = (Bitmap) data.getExtras().get("data");
* selectedImageUri =
* Uri.parse(MediaStore.Images.Media.insertImage
* (getContentResolver(), mPic,
* getResources().getString(R.string.app_name),
* Long.toString(System.currentTimeMillis())));
*/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
}
break;
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
selectedImagepicUri = data.getData();
}
}
if (selectedImagepicUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImagepicUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImagepicUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile1(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
if (selectedImageUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 512;
// 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;
bitmap = BitmapFactory.decodeFile(filePath, o2);
/**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/
if (bitmap == null) {
Toast.makeText(getApplicationContext(), "Please select image",
Toast.LENGTH_SHORT).show();
} else {
ivr.setImageBitmap(bitmap);
ivrIn.setImageBitmap(bitmap);
// new ImageGalleryTask().execute();
}
}
public void decodeFile1(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 512;
// 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;
bitmap = BitmapFactory.decodeFile(filePath, o2);
/**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/
if (bitmap == null) {
Toast.makeText(getApplicationContext(), "Please select image",
Toast.LENGTH_SHORT).show();
} else {
ivr.setImageBitmap(bitmap);
ivrIn.setImageBitmap(bitmap);
// new ImageGalleryTask().execute();
}
}
Async task to upload image
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressDialog = new ProgressDialog(Profile.this);
//progressDialog.setTitle("Fetching data");
progressDialog.setMessage("Uploading profile pic, Please Wait....");
progressDialog.show();
progressDialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
System.out.println("progress update "+progress[0]);
// progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
// progressBar.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
int count;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
URL url = new URL("url");
System.out.println("url "+url);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + filePath + "\"" + lineEnd);
Log.e("chhuuuh", filePath + System.currentTimeMillis());
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
responseString = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
InputStream is = null;
try {
is = connection.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
return sb.toString();
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
is.close();
}
}
}
catch (Exception ex)
{
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
String result1 = result;
Log.e("respons form server", "response from server: " + result);
if(progressDialog.isShowing())
{
progressDialog.dismiss();
}
try {
JSONObject json = new JSONObject(result);
int response = json.getInt("status_code");
if(response == 1)
{
if (result1.contains("null")) {
Toast.makeText(getApplicationContext(), "You didn't change the image, please choose an image from gallery or click from the camera.", 2000).show();
} else {
JSONObject arr = json.getJSONObject("details");
String erer = arr.getString("error");
String message = arr.getString("message");
Toast.makeText(getApplicationContext(), message, 1000).show();
}
}
else
{
showAlert("Error Uploading Image, Please try again!!!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPostExecute(result);
}
}
get the correct path
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
Permissions for 6.0 and above versions
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d("", "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initialize the map with both permissions
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CALL_PHONE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Log.d("", " permission granted");
// process the normal flow
//else any one or both the permissions are not granted
} else {
Log.d("", "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
// shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
showDialogOK("This app have camera functionality so Camera and Write External Storage Permission required for this app",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
Toast.makeText(getApplicationContext(), "Please go to settings and enable permissions.", 2000).show();
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
private boolean checkAndRequestPermissions() {
int permissionCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int permissionWriteExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionCallPhone = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
List<String> listPermissionsNeeded = new ArrayList<String>();
if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionCallPhone != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
I know this code is too long to read but this is exactly what you want
I'm in trouble with this android java class.
The goal that I'm trying to reach with this activity is:
start camera-->take photo-->recognize text-->(tts and recognized text in the edittext)
TTS would had to start automatically after the text recognition. But it didn't. The recognized text also must appear in the edit text (and it's work)
I'm ok with the three first steps. TTS gives me an issue: "speak failed: not bound to TTS engine". I'm trying to understand where is the problem. I also followed some guide to use tts, I think the problem is about stop or shutdown of tts. Any idea? Thanks a lot
Code
public class CameraActivity extends Activity {
public TextToSpeech tts1;
public String voce;
public String text;
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/OcrTesiDiLaurea/";
public static final String lingua= Locale.getDefault().getISO3Language();
public static final String lang = lingua;
private static final String TAG = MainActivity.class.getName();
protected Button _button;
protected EditText _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "foto catturata";
#Override
public void onDestroy(){
if(tts1 !=null){
tts1.stop();
tts1.shutdown();
}
super.onDestroy();
}
#Override
public void onCreate(Bundle savedInstanceState) {
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, "ERRORE: creazione directory " + path + " in memoria fallita");
return;
} else {
Log.v(TAG, "creazione directory " + path + " eseguita con successo");
}
}
}
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transferimento dati
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "file " + lang + " copiato con successo in traineddata");
} catch (IOException e) {
Log.e(TAG, "impossibile copiare " + lang + " traineddata " + e.toString());
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
_field = (EditText) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = DATA_PATH + "/ocr.jpg";
tts1=new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts1.setLanguage(Locale.getDefault());
}
}
});
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
Log.v(TAG, "avvio fotocamera");
startCameraActivity();
}
}
// http://labs.makemachine.net/2010/03/simple-android-photo-capture/
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "resultCode: " + resultCode);
if (resultCode == -1) {
onPhotoTaken();
} else {
Log.v(TAG, "User cancelled");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraActivity.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG, "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(CameraActivity.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
protected void onPhotoTaken() {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.v(TAG, "Orient: " + exifOrientation);
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;
}
Log.v(TAG, "Rotation: " + rotate);
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
Log.e(TAG, "Couldn't correct orientation: " + e.toString());
}
Log.v(TAG, "Inizio utilizzo librerie tesseract");
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
_field.getText().clear();
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if ( lang.equalsIgnoreCase("eng") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
if ( lang.equalsIgnoreCase("ita") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
recognizedText = recognizedText.trim();
if ( recognizedText.length() != 0 ) {
_field.setText(_field.getText().toString().length() == 0 ? recognizedText : _field.getText() + " " + recognizedText);
_field.setSelection(_field.getText().toString().length());
}
voce=recognizedText;
}
public void convertTextToSpeech() {
text = voce;
if (null == text || "".equals(text)) {
text = "NON POSSO PRONUNCIARE NESSUNA PAROLA, MANCA IL TESTO";
}
tts1.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
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);
}
}