Mock Gps Not working - java

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);
}
}

Related

JVMTI_ERROR_THREAD_NOT_ALIVE error using multiple activites and OpenWeatherMap API

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.

Handle stream of data sensor

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);
}
}

How can a user search parsed Xml and display output

I have successfully created an Xml Parser which outputs the whole Xml in a TextView. However I can't find a way for a user to input their search, so the Xml can be searched for their input before outputting the answer in TextView. Can anyone help?
public void Species() {
Common = "Not set";
Latin = "Not set";
Where = "Not set";
Kingdom = "Not set";
Phylum = "Not set";
Class = "Not set";
Order = "Not set";
Family = "Not set";
Genus = "Not set";
Scientific = "Not set";
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
//private XmlPullParser parser;
private EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
search = (EditText) findViewById(R.id.editText);
search.setOnClickListener(this);
}
private void Xmlreader() {
try {
//parser = Xml.newPullParser();
//InputStream in_s = getApplicationContext().getAssets().open("classification.xml");
XmlPullParser parser = getResources().getXml(R.xml.classification);
//Toast.makeText(MainActivity.this, "Xml opened for Parsing", Toast.LENGTH_SHORT).show();
//parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
//Toast.makeText(MainActivity.this, "XXXXXXXXXXXXXXXXX", Toast.LENGTH_SHORT).show();
//parser.setInput(in_s, null);
parseXml(parser);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void parseXml(XmlPullParser parser) throws
XmlPullParserException, IOException {
//Toast.makeText(MainActivity.this, "parseXml", Toast.LENGTH_SHORT).show();
ArrayList<Species> classification = null;
int eventType = parser.getEventType();
Species currentSpecies = null;
//Toast.makeText(MainActivity.this, "got first event type", Toast.LENGTH_SHORT).show();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
String temp = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
//Toast.makeText(MainActivity.this, "Document Started", Toast.LENGTH_SHORT).show();
classification = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
temp = "Name found: " + name;
//Toast.makeText(MainActivity.this, temp, Toast.LENGTH_SHORT).show();
if (name.trim().equalsIgnoreCase("species")) {
//Toast.makeText(MainActivity.this, "New species", Toast.LENGTH_SHORT).show();
currentSpecies = new Species();
} else if (currentSpecies != null) {
if (name.trim().equalsIgnoreCase("Common")) {
currentSpecies.Common = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Latin")) {
currentSpecies.Latin = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Where")) {
currentSpecies.Where = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Kingdom")) {
currentSpecies.Kingdom = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Phylum")) {
currentSpecies.Phylum = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Class")) {
currentSpecies.Class = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Order")) {
currentSpecies.Order = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Family")) {
currentSpecies.Family = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Genus")) {
currentSpecies.Genus = parser.nextText();
} else if (name.trim().equalsIgnoreCase("Scientific")) {
currentSpecies.Scientific = parser.nextText();
}
//Toast.makeText(MainActivity.this, "1st Sequence of Xml Parsed", Toast.LENGTH_SHORT).show();
}
break;
case XmlPullParser.END_TAG:
//Toast.makeText(MainActivity.this, "End Tag", Toast.LENGTH_SHORT).show();
//name = parser.getName();
//if (name.equalsIgnoreCase("species") && currentSpecies != null) {
if (currentSpecies != null) {
//Toast.makeText(MainActivity.this, "Adding Species", Toast.LENGTH_SHORT).show();
classification.add(currentSpecies);
}
}
eventType = parser.next();
}
printClassification(classification);
}
private void printClassification(ArrayList<Species> classification) {
//Toast.makeText(MainActivity.this, "Print Classification", Toast.LENGTH_SHORT).show();
String content = "";
Iterator<Species> it = classification.iterator();
while (it.hasNext()) {
Species currSpecies = it.next();
content = content + "Common Name: " + currSpecies.Common + "\n\n";
content = content + "Latin Name: " + currSpecies.Latin + "\n\n";
content = content + "Where: " + currSpecies.Where + "\n\n";
content = content + "Kingdom: " + currSpecies.Kingdom + "\n\n";
content = content + "Phylum: " + currSpecies.Phylum + "\n\n";
content = content + "Class: " + currSpecies.Class + "\n\n";
content = content + "Order: " + currSpecies.Order + "\n\n";
content = content + "Family: " + currSpecies.Family + "\n\n";
content = content + "Genus: " + currSpecies.Genus + "\n\n";
content = content + "Scientific: " + currSpecies.Scientific + "\n\n";
}
TextView display = (TextView) findViewById(R.id.info);
EditText search = (EditText) findViewById(R.id.editText);
search.getText();
display.setText(content);
}
#Override
public void onClick(View view) {
Xmlreader();
}
}

FileNotFoundException when upload multiple images to FTP server

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);
}
}
}

OCR with text to speech

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);
}
}

Categories