Related
I am making an weather app, on the main screen app shows current weather for a city that is chosen and on the second activity screen you can find weather for next 3 days. I have WeatherInfoTask.java that is used to get JSON for MainActivity and MultipleWeatherTask.java that is used to get JSON for MultipleDays (activity)
so the MainActivity works fine and I get JSON and all of the info is shown on the screen just as it should be, but when I click on the button that should redirect me to the screen of the MultipleDays, I am redirected and just a plain screen is shown without data and this error is shown:
E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
These are my files:
public class MainActivity extends AppCompatActivity {
public static String cityName;
Handler handler;
TextView titleText;
TextView temperatureText;
TextView descriptionText;
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isNetworkAvailable()){
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing the App")
.setMessage("No Internet Connection, check your settings")
.setPositiveButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
handler = new Handler();
titleText = (TextView) findViewById(R.id.titleText);
temperatureText = (TextView) findViewById(R.id.temperatureText);
descriptionText = (TextView) findViewById(R.id.descriptionText);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Find City");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
cityName = place.getName().toString();
updateWeather(cityName);
/*Log.i(TAG, "Place: " + place.getName());*/
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("MainActivity", "An error occurred: " + status);
}
});
}
private void updateWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = WeatherInfoTask.getJSON(MainActivity.this, city);
if(json == null){
Toast.makeText(MainActivity.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
SetWeather(json);
}
});
}
}
}.start();
}
private void SetWeather(JSONObject json){
try {
/*cityField.setText(json.getString("name").toUpperCase(Locale.US) +
", " +
json.getJSONObject("sys").getString("country"));*/
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main"); /*"main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15}*/
titleText.setText(R.string.title + cityName);
descriptionText.setText( /*"description":"light intensity drizzle"*/
details.getString("description") +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + " hPa");
temperatureText.setText(
String.format("%.2f", main.getDouble("temp"))+ " ℃");
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data");
}
}
public void MultipleDays(View view){
Intent intent = new Intent(this, MultipleDays.class);
startActivity(intent);
}
}
Next one:
public class WeatherInfoTask {
private static final String OpenWeatherAPI =
"http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
Next one:
public class MultipleDays extends AppCompatActivity {
Handler handler;
TextView day1;
TextView day2;
TextView day3;
Integer dayCounter = 1;
Date comparisonDate;
Date currentDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Float dailyMin;
Float dailyMax;
Float currMin;
Float currMax;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple_days);
handler = new Handler();
day1 = (TextView) findViewById(R.id.day1);
day2 = (TextView) findViewById(R.id.day2);
day3 = (TextView) findViewById(R.id.day3);
updateMultipleWeather(MainActivity.cityName);
}
private void updateMultipleWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = MultipleWeatherTask.getJSON(MultipleDays.this, city);
if(json == null){
Toast.makeText(MultipleDays.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
setWeather(json);
}
});
}
}
}.start();
}
private void setWeather(JSONObject json){
try {
JSONArray list = json.getJSONArray("list");
for (int i=0; i < list.length() ; i++){
if(i == 0) {
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
comparisonDate = formatter.parse(string.replace("",""));
dailyMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
dailyMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
}
else if ( dayCounter <=3 ){
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
currentDate = formatter.parse(string.replace("","")); //datum u obliku "yy-MM-dd"
if ( comparisonDate == currentDate ){ //ako smo i dalje na istom danu
currMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
currMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
if( dailyMin > currMin ) dailyMin = currMin;
if( dailyMax < currMax ) dailyMax = currMax;
}
else {
switch (dayCounter){
case 1: day1.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 2: day2.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 3: day3.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
}
}
}
}
Next one:
public class MultipleWeatherTask {
private static final String OpenWeatherAPI =
"api.openweathermap.org/data/2.5/forecast?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
}
}
File ---> Invalidate Caches / Restart will help you.
when i am doing offline login my app is crashing...and showing the error
Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
In Online it is working fine no issues but in offline it is crashing not at all giving where the issue is please help me in this
public class MainActivity extends AppCompatActivity {
**// Initializing variables**
EditText login;
EditText password;
String statusRes;
String id;
String projectName;
String loginValue;
String stockPoint;
JSONObject myRespObject = null;
public static final String Passkey = "passKey";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("LOGIN");
setContentView(R.layout.login);
login = (EditText) findViewById(R.id.loginname);
password = (EditText) findViewById(R.id.Password);
final Button saveme = (Button) findViewById(R.id.save);
**SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
saveme.setOnClickListener(new Button.OnClickListener() {
public URL url;
public void onClick(android.view.View v) {
if (!CheckNetwork.isInternetAvailable(MainActivity.this){
if (!validate()) {
onLoginFailed();
return;
}
SharedPreferences prefs = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
String loginValue = prefs.getString(AppConstants.LOGIN_VALUE, "");
String Passkey = prefs.getString(AppConstants.PASS_KEY, "");
String Internet = prefs.getString("Internet", "false");
String projectName = prefs.getString(AppConstants.PROJECT_NAME, "");
String stockPoint = prefs.getString(String.valueOf(AppConstants.STOCK_POINT),"");
String id = prefs.getString(AppConstants.ID, "");
Intent profactivity = new Intent(MainActivity.this, View.class);
profactivity.putExtra("Internet", false);
profactivity.putExtra("loginValue", loginValue);
profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", stockPoint);
startActivity(profactivity);
**Toast.makeText(MainActivity.this, "Offline Login ", Toast.LENGTH_SHORT).show();
finish();
}
****for the above code, here it is throughing the error**
try {
final String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
final String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
try {
new Thread(new Runnable() {
**//Thread to stop network calls on the UI thread**
public void run() {
//Request the HTML
ArrayList<String> list = null;
try {
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
String ROOT_URL = getResources().getString(R.string.ROOT_URL) + "/api/v1/user/signIn?loginName=" + loginValue + "&password=" + passValue;
Log.i("httpget", "################" + ROOT_URL);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ROOT_URL);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String server_response = EntityUtils.toString(response.getEntity());
myRespObject = new JSONObject(server_response);
//Do something with the response
//Toast.makeText(getBaseContext(),server_response,Toast.LENGTH_LONG).show();
statusRes = myRespObject.getString("status");
JSONObject respObject = myRespObject.getJSONObject("response");
id = respObject.getString("_id");
AppConstants._ID = id;
projectName = respObject.getString("projectName");
Actors actor = new Actors();
list = new ArrayList<>();
JSONArray jsonArray = respObject.getJSONArray("stockPoint");
Intent i = getIntent();
Serializable subject = i.getSerializableExtra("stockPoint");
if (jsonArray != null) {
int len = jsonArray.length();
for (int k = 0; k < len; k++)
list.add(jsonArray.get(k).toString());
}
actor.setStockPoint(list);
AppConstants.STOCK_POINT = stockPoint;
stockPoint = respObject.getString("stockPoint");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
final ArrayList<String> finalList = list;
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
statusRes = myRespObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
if (statusRes.equalsIgnoreCase("success")) {
SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(AppConstants.LOGIN_VALUE, loginValue);
editor.putString(AppConstants.PASS_KEY, passValue);
editor.putString("Internet", "true");
editor.putString(AppConstants.ID, id);
editor.putString(AppConstants.PROJECT_NAME, projectName);
editor.putString(String.valueOf(AppConstants.STOCK_POINT), String.valueOf(stockPoint));
editor.commit();
**//Here move to next screen or home screen**
Intent profactivity = new Intent(MainActivity.this, View.class); profactivity.putExtra("Internet", true); profactivity.putExtra("loginValue", loginValue); profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", finalList);
startActivity(profactivity);
Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_LONG).show();
finish();
} else if (statusRes.equalsIgnoreCase("failed")) {
if (!validate()) {
onLoginFailed();
return;
}
}
}
});
}
}).start();
//return data;
} catch (Exception e) {
Log.i("httpget", "################Error1 -->" + e.getStackTrace());
**Toast.makeText(getBaseContext(), "ERROR : " + e.getMessage(), Toast.LENGTH_LONG).show();**
}
} catch (UnsupportedEncodingException ex) {
finish();
}
}
});
}
public boolean validate() {
boolean valid = true;
String email = login.getText().toString();
String passwor = password.getText().toString();
if (email.isEmpty() || email.length() < 2 || email.length() > 10) {
login.setError("enter valid username");
valid = false;
} else {
login.setError("Invalid username");
}
if (passwor.isEmpty() || passwor.length() < 2 || passwor.length() > 10) {
password.setError("enter valid password");
valid = false;
} else {
password.setError("Invalid password");
}
return valid;
}
public void onLoginFailed() {
**Toast.makeText(getBaseContext(), "Invalid login", Toast.LENGTH_LONG).show();**
}
}
--------------------------------------------------------------------------------
The error that you have mentioned says you have error on following line.
projectName = respObject.getString("projectName");
"responseObject" is null, hence you are getting NullPointerException.
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'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);
}
}