I am working on an Android navigation application for blind people. So naturally no use of displaying map on the screen. My code for now gets the path by building an url and then parsing the html document. I want to make this live i.e. i want to handle the case when he/she goes off the path or goes in the wrong direction, i want my app to alert him.
Is such a thing possible using a Google Maps feature? If possible please give details about that feature or if no such feature exists then is it possible to use existing feature and use it in some way to help solve the problem.
This is my present code:
public class GPSTracking extends Activity implements
TextToSpeech.OnInitListener
{
protected static final int RESULT_SPEECH_start = 1;
protected static final int RESULT_SPEECH_end = 2;
protected static final int RESTART_ALL = 3;
//total distance travelled till last turn
Float totalDistance;
//distance to be travelled from present point to the next point
Float obtainedDistance;
//upper button
Button btnShowLocation;
//bottom button
Button btnShowLocationNo;
//to narate what user should do.
TextToSpeech tts;
//used to get name of current location
Geocoder geocoder;
//used to find positioning feature
GPS gps;
//start and position of the journey
String startPosition=null, endPosition=null;
//strings containing the path.
String[] string = null;
//vibrate the mobile
Vibrator viberator;
//indexing the present value of string which contains the path
int i = 0;
//to maintain proper order of events
int steps=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button on top
btnShowLocation = (Button) findViewById(R.id.trueButton);
//button on the lower side
btnShowLocationNo = (Button) findViewById(R.id.falseButton);
//initialising the text to speech
tts = new TextToSpeech(this, this);
//initialising the vibrator.
viberator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//to know what the current location
btnShowLocation.setOnClickListener(new View.OnClickListener() {
//to avoid start of multiple threads
boolean mytaskStarted=false;
String str=null;
#Override
public void onClick(View v) {
if(steps==0){
//to make sure values are reset
totalDistance=(float)0;
obtainedDistance=(float)0;
mytaskStarted=false;
string=null;
str=null;
i=0;
//only ask for initial position if not set
if(startPosition == null){
speakOut("Please enter the start position");
//takes the input using speech to text
intentGenerator(RESULT_SPEECH_start);
}
else{
//to enter the destination
speakOut("press the button again");
steps=1;
}
}
else if(steps==1){
//to enter the destination
speakOut("Please enter the destination");
intentGenerator(RESULT_SPEECH_end);
}
else if(steps==2){
//for a impatient user
speakOut("please wait");
//to avoid start of many asynchronous task
if(!mytaskStarted){
mytaskStarted=true;
//asynchronous task to find the path to be followed
new GetPath().execute();
}
}
else if(steps==3){
if (string != null && i < string.length) {
if(gps!=null && gps.isGpsEnabled()){
speakOut(i + 1 + " " + string[i]);
if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" m ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" m ")+3);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" km ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" km ")+4);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
obtainedDistance*=1000;
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i==0 ){
i++;
}
}
else if(gps!=null){
gps.resetDistance();
gps.stopUsingGPS();
//if gps not working.
speakOut(i + 1 + " " + string[i]);
i++;
}
else{
speakOut(i + 1 + " " + string[i]);
i++;
}
} else if (string != null && i >= string.length) {
i = 0;
}
}
}
});
//to get present location
btnShowLocation.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if(gps==null){
gps = new GPS(AndroidGPSTrackingActivity.this);
}
if (gps.canGetLocation()) {
double longitude = gps.getLongitude();
double latitude = gps.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
//obtain the address of present location
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
if (listAddresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < listAddresses.size(); i++){
Address address = listAddresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
if(address.getAddressLine(x)!=null){
result.append(address.getAddressLine(x));
result.append(",");
}
}
if(address.getLocality()!=null){
result.append(address.getLocality());
result.append("\n\n");
}
}
//if position accurate
if(gps.isGpsEnabled()){
speakOut(result.toString()+" is Your current location");
startPosition=result.toString();
Toast.makeText(
getApplicationContext(),startPosition,
Toast.LENGTH_LONG).show();
} else if(gps.isNetworkEnabled()){
speakOut(result.toString()+" is Your current approximate location. You have to give input of your present location on your own.");
Toast.makeText(
getApplicationContext(),result.toString(),
Toast.LENGTH_LONG).show();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
startPosition=null;
speakOut(" please turn on gps");
}
return false;
}
});
//to know what the previous direction string
btnShowLocationNo.setOnClickListener(new View.OnClickListener() {
int j=0;
#Override
public void onClick(View arg0) {
if(string!=null && j<string.length){
speakOut(j + 1 + " " + string[j]);
j++;
}
else if(string!=null && j>=string.length){
j=0;
}
}
});
//to reset all values for fresh start
btnShowLocationNo.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
speakOut("Values reset");
steps=0;
string=null;
i=0;
startPosition=null;
gps.stopUsingGPS();
gps=null;
endPosition=null;
return false;
}
});
}
//function to handle he text obtained from speech to text.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//set the start
case RESULT_SPEECH_start:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
startPosition = text.get(0);
steps=1;
//speakOut("please press button again");
}
else{
steps=0;
}
break;
//to set the end
case RESULT_SPEECH_end:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
endPosition = text.get(0);
steps=2;
}
else{
steps=1;
}
break;
}
}
//function to generate intent to take speech input
public void intentGenerator(int code) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, code);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
speakOut("Opps! Your device doesn't support Speech to Text");
}
}
//mobile gives instruction.
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
while (tts.isSpeaking()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//asynchronous task to get the path. THIS IS USED TO AVOID OVERLOAD THE MAIN THRED AND AVOID FORCE CLOSE OF THE APPLICATION
private class GetPath extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
string=null;
String html="";
//forming url
URL net = new URL(("http://maps.google.com/maps?saddr="+startPosition+" &daddr= "+endPosition).replaceAll(" ","%20"));
URLConnection netConnection = null;
netConnection = net.openConnection();
//to take the input from google maps
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(netConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
html+=inputLine;
}
//jsoup parser to parse the document obtained from google maps
Document doc = Jsoup.parse(html);
//obtain necessary part of the document
Elements el = doc.getElementsByClass("dir-mrgnr");
//to remove html tags
String str = el.text();
str = str.replaceAll("[0-9]+[.] ", "\n");
string = str.split("\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//so that on press of button again mobile can read the directions to users
steps=3;
}
}
#Override
public void onDestroy() {
//shutdown
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
protected void onStart() {
gps = new GPS(AndroidGPSTrackingActivity.this);
super.onStart();
}
#Override
protected void onStop() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
if(gps!=null){
gps.stopUsingGPS();
}
super.onStop();
}
#Override
public void onInit(int status) {
//initialising the text to speech
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
btnShowLocation.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
}
Related
I am developing an app in which I want to use transliteration from Hindi to English via speech input. for that, I am using google STT API. Everything works when my voice input is short, but when I give long voice input, Dialog gets stuck at "Try Saying Something..." and I don't get results a well.
This is my Main Activity:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original and recognized Text
TextView Original,result;
// Request Code for STT
private final int SST_REQUEST_CODE = 101;
// Conversion Table Object...
ConversionTable conversionTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
result = findViewById(R.id.Recognized_Text);
RecordBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// For 30 Sec it will Record...
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Off line Recognition Engine only...
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
// Use Hindi Speech Recognition Model...
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
try {
startActivityForResult(intent, SST_REQUEST_CODE);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.error),
Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SST_REQUEST_CODE:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> getResult = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Original.setText(getResult.get(0));
conversionTable = new ConversionTable();
String Transformed_String = conversionTable.transform(getResult.get(0));
result.setText(Transformed_String);
}
break;
}
}
}
My ConversationTable.class :-
package android.example.com.conversion;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
public class ConversionTable
{
private String TAG = "Conversation Table";
private Hashtable<String,String> unicode;
private void populateHashTable()
{
unicode = new Hashtable<>();
// unicode
unicode.put("\u0901","rha"); // anunAsika - cchandra bindu, using ~ to // *
unicode.put("\u0902","n"); // anusvara
unicode.put("\u0903","ah"); // visarga
unicode.put("\u0940","ee");
unicode.put("\u0941","u");
unicode.put("\u0942","oo");
unicode.put("\u0943","rhi");
unicode.put("\u0944","rhee"); // * = Doubtful Case
unicode.put("\u0945","e");
unicode.put("\u0946","e");
unicode.put("\u0947","e");
unicode.put("\u0948","ai");
unicode.put("\u0949","o");
unicode.put("\u094a","o");
unicode.put("\u094b","o");
unicode.put("\u094c","au");
unicode.put("\u094d","");
unicode.put("\u0950","om");
unicode.put("\u0958","k");
unicode.put("\u0959","kh");
unicode.put("\u095a","gh");
unicode.put("\u095b","z");
unicode.put("\u095c","dh"); // *
unicode.put("\u095d","rh");
unicode.put("\u095e","f");
unicode.put("\u095f","y");
unicode.put("\u0960","ri");
unicode.put("\u0961","lri");
unicode.put("\u0962","lr"); // *
unicode.put("\u0963","lree"); // *
unicode.put("\u093E","aa");
unicode.put("\u093F","i");
// Vowels and Consonants...
unicode.put("\u0905","a");
unicode.put("\u0906","a");
unicode.put("\u0907","i");
unicode.put("\u0908","ee");
unicode.put("\u0909","u");
unicode.put("\u090a","oo");
unicode.put("\u090b","ri");
unicode.put("\u090c","lri"); // *
unicode.put("\u090d","e"); // *
unicode.put("\u090e","e"); // *
unicode.put("\u090f","e");
unicode.put("\u0910","ai");
unicode.put("\u0911","o");
unicode.put("\u0912","o");
unicode.put("\u0913","o");
unicode.put("\u0914","au");
unicode.put("\u0915","k");
unicode.put("\u0916","kh");
unicode.put("\u0917","g");
unicode.put("\u0918","gh");
unicode.put("\u0919","ng");
unicode.put("\u091a","ch");
unicode.put("\u091b","chh");
unicode.put("\u091c","j");
unicode.put("\u091d","jh");
unicode.put("\u091e","ny");
unicode.put("\u091f","t"); // Ta as in Tom
unicode.put("\u0920","th");
unicode.put("\u0921","d"); // Da as in David
unicode.put("\u0922","dh");
unicode.put("\u0923","n");
unicode.put("\u0924","t"); // ta as in tamasha
unicode.put("\u0925","th"); // tha as in thanks
unicode.put("\u0926","d"); // da as in darvaaza
unicode.put("\u0927","dh"); // dha as in dhanusha
unicode.put("\u0928","n");
unicode.put("\u0929","nn");
unicode.put("\u092a","p");
unicode.put("\u092b","ph");
unicode.put("\u092c","b");
unicode.put("\u092d","bh");
unicode.put("\u092e","m");
unicode.put("\u092f","y");
unicode.put("\u0930","r");
unicode.put("\u0931","rr");
unicode.put("\u0932","l");
unicode.put("\u0933","ll"); // the Marathi and Vedic 'L'
unicode.put("\u0934","lll"); // the Marathi and Vedic 'L'
unicode.put("\u0935","v");
unicode.put("\u0936","sh");
unicode.put("\u0937","ss");
unicode.put("\u0938","s");
unicode.put("\u0939","h");
// represent it\
// unicode.put("\u093c","'"); // avagraha using "'"
// unicode.put("\u093d","'"); // avagraha using "'"
unicode.put("\u0969","3"); // 3 equals to pluta
unicode.put("\u014F","Z");// Z equals to upadhamaniya
unicode.put("\u0CF1","V");// V equals to jihvamuliya....but what character have u settled for jihvamuliya
/* unicode.put("\u0950","Ω"); // aum
unicode.put("\u0958","κ"); // Urdu qaif
unicode.put("\u0959","Κ"); //Urdu qhe
unicode.put("\u095A","γ"); // Urdu gain
unicode.put("\u095B","ζ"); //Urdu zal, ze, zoe
unicode.put("\u095E","φ"); // Urdu f
unicode.put("\u095C","δ"); // Hindi 'dh' as in padh
unicode.put("\u095D","Δ"); // hindi dhh*/
unicode.put("\u0926\u093C","τ"); // Urdu dwad
unicode.put("\u0924\u093C","θ"); // Urdu toe
unicode.put("\u0938\u093C","σ"); // Urdu swad, se
}
ConversionTable()
{
populateHashTable();
}
public String transform(String s1)
{
StringBuilder transformed = new StringBuilder();
int strLen = s1.length();
ArrayList<String> shabda = new ArrayList<>();
String lastEntry = "";
for (int i = 0; i < strLen; i++)
{
char c = s1.charAt(i);
String varna = String.valueOf(c);
Log.d(TAG, "transform: " + varna + "\n");
String halant = "0x0951";
if (VowelUtil.isConsonant(varna))
{
Log.d(TAG, "transform: " + unicode.get(varna));
shabda.add(unicode.get(varna));
shabda.add(halant); //halant
lastEntry = halant;
}
else if (VowelUtil.isVowel(varna))
{
Log.d(TAG, "transform: " + "Vowel Detected...");
if (halant.equals(lastEntry))
{
if (varna.equals("a"))
{
shabda.set(shabda.size() - 1,"");
}
else
{
shabda.set(shabda.size() - 1, unicode.get(varna));
}
}
else
{
shabda.add(unicode.get(varna));
}
lastEntry = unicode.get(varna);
} // end of else if is-Vowel
else if (unicode.containsKey(varna))
{
shabda.add(unicode.get(varna));
lastEntry = unicode.get(varna);
}
else
{
shabda.add(varna);
lastEntry = varna;
}
} // end of for
for (String string: shabda)
{
transformed.append(string);
}
//Discard the shabda array
shabda = null;
return transformed.toString(); // return transformed;
}
}
My ViewUtil Class:-
package android.example.com.conversion;
public class VowelUtil {
protected static boolean isVowel(String strVowel) {
// Log.logInfo("came in is_Vowel: Checking whether string is a Vowel");
return strVowel.equals("a") || strVowel.equals("aa") || strVowel.equals("i") || strVowel.equals("ee") ||
strVowel.equals("u") || strVowel.equals("oo") || strVowel.equals("ri") || strVowel.equals("lri") || strVowel.equals("e")
|| strVowel.equals("ai") || strVowel.equals("o") || strVowel.equals("au") || strVowel.equals("om");
}
protected static boolean isConsonant(String strConsonant) {
// Log.logInfo("came in is_consonant: Checking whether string is a
// consonant");
return strConsonant.equals("k") || strConsonant.equals("kh") || strConsonant.equals("g")
|| strConsonant.equals("gh") || strConsonant.equals("ng") || strConsonant.equals("ch") || strConsonant.equals("chh") || strConsonant.equals("j")
|| strConsonant.equals("jh") || strConsonant.equals("ny") || strConsonant.equals("t") || strConsonant.equals("th") ||
strConsonant.equals("d") || strConsonant.equals("dh") || strConsonant.equals("n") || strConsonant.equals("nn") || strConsonant.equals("p") ||
strConsonant.equals("ph") || strConsonant.equals("b") || strConsonant.equals("bh") || strConsonant.equals("m") || strConsonant.equals("y") ||
strConsonant.equals("r") || strConsonant.equals("rr") || strConsonant.equals("l") || strConsonant.equals("ll") || strConsonant.equals("lll") ||
strConsonant.equals("v") || strConsonant.equals("sh") || strConsonant.equals("ss") || strConsonant.equals("s") || strConsonant.equals("h") ||
strConsonant.equals("3") || strConsonant.equals("z") || strConsonant.equals("v") || strConsonant.equals("Ω") ||
strConsonant.equals("κ") || strConsonant.equals("K") || strConsonant.equals("γ") || strConsonant.equals("ζ") || strConsonant.equals("φ") ||
strConsonant.equals("δ") || strConsonant.equals("Δ") || strConsonant.equals("τ") || strConsonant.equals("θ") || strConsonant.equals("σ");
}
}
Outputs :-
for Short voice input :-
for Long voice Input, it stuck and can't get the result:-
The Problem is in Google's Implementation. I was facing the same type of difficulty and tried all the things, but did not work on anything.
So, i went on another way to solve this problem and the solution is implementing listeners by yourself. Here is my code for the same, it never popup the Inbuilt dialog (You can implement your custom dialog), but it works like charm.
Here is how you can do it :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original
TextView Original;
// SpeechRecognizer Object...
private SpeechRecognizer speechRecognizer;
// For TAG
private String TAG = getClass().getName();
// RecognizerIntent
private Intent recognizerIntent;
// Request Code for Permission
private static final int REQUEST_CODE_RECORD_AUDIO = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, R.string.record);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
}
// For 30 Sec it will Record...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Hindi Speech Recognition Model...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
// Permission Dialog
Askpermission();
RecordBtn.setOnClickListener(this);
}
private void Askpermission() {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_CODE_RECORD_AUDIO);
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_RECORD_AUDIO: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Operation();
} else {
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Log.d(TAG, "onClick: ");
if (checkPermission()) {
if (IsAvailable(this)) {
Log.d(TAG, "Speech Recognition Service Available...");
speechRecognizer.startListening(recognizerIntent);
} else {
Toast.makeText(this, "Speech Recognition Service not Available on your device...",
Toast.LENGTH_SHORT)
.show();
}
} else {
Askpermission();
}
break;
}
}
// Check if Speech recognition Service is Available on the Smartphone...
private boolean IsAvailable(Context context) {
return SpeechRecognizer.isRecognitionAvailable(context);
}
#Override
protected void onDestroy() {
super.onDestroy();
speechRecognizer.destroy();
}
// Check Audio Permission
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED;
}
// Start Operation
private void Operation() {
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "Audio Service is connected to Servers....");
Log.d(TAG, "You can now start your speech...");
}
#Override
public void onBeginningOfSpeech() {
Log.d(TAG, "User has started speech...");
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
Log.d(TAG, "User has Finished... speech...");
}
#Override
public void onError(int error) {
Log.d(TAG, "onError: " + error);
switch (error){
case SpeechRecognizer.ERROR_AUDIO:
Toast.makeText(MainActivity.this, "Error Recording Audio...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_CLIENT:
Toast.makeText(MainActivity.this, "Client Side Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
Toast.makeText(MainActivity.this, "Insufficient permissions...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK:
Toast.makeText(MainActivity.this, "Network Related Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NO_MATCH:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
Toast.makeText(MainActivity.this, "Recognition Busy...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SERVER:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
Toast.makeText(MainActivity.this, "Speech Timeout...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
Toast.makeText(MainActivity.this, "Network Timeout Error...", Toast
.LENGTH_SHORT).show();
}
}
#Override
public void onResults(Bundle results) {
ArrayList<String> Results = results.getStringArrayList(SpeechRecognizer
.RESULTS_RECOGNITION);
if (Results != null) {
Original.setText(Results.get(0));
}
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
I am facing a Null pointer Exception while calling Create report (which in turns calls its Asynctask "createReportTask" situated inside the Activity) But the application crashes giving NPE in the other fragment's Asynsc task (situated inside fragment) , I have tried passing context in constructor etc getContext(), getAcitivity() etc but all in vain. I am attaching Logs and Code please help!!
Logs:
05-24 12:56:11.505 14632-14632/com.example.aiousecurityapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aiousecurityapplication, PID: 14632
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.widget.Toast.<init>(Toast.java:121)
at android.widget.Toast.makeText(Toast.java:291)
at android.widget.Toast.makeText(Toast.java:281)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:439)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:377)
at android.os.AsyncTask.finish(AsyncTask.java:727)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:744)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Create Report Code:
public class CreateReport extends AppCompatActivity {
public EditText eventDate;
public EditText eventTime;
EditText reporterName;
EditText reporterCnic;
int flag = 0;
public static Calendar userCalendar;
private String Lat, Long;
private static final String[] BLOCK = new String[]{"Block 1", "Block 2", "Block 3", "Block 4", "Block 5"};
private static final String[] sampleDesc = new String[]{"Aag Lagi ha", "Darwaza Khula h", "Tala Ni Laga", "Lights / Fan On hain"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_report);
Button createReport = (Button) findViewById(R.id.createReport);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ActionBar ab = getSupportActionBar();
ab.setTitle("Create Report");
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Lat = bundle.getString("lat");
Toast.makeText(getContext(), "Latitude" + Lat, Toast.LENGTH_LONG).show();
Long = bundle.getString("Long");
}
createReport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (eventDescription.getText().toString().length() < 3) {
eventDescription.setError("Minimum 5 Letters");
Toast.makeText(getApplicationContext(),
"Please some Description", Toast.LENGTH_SHORT)
.show();
} else {
// creating new product in background thread
String blockname = blockName.getSelectedItem().toString().trim();
String eventEsc = eventEsclation.getSelectedItem().toString().trim();
String eventdesc = eventDescription.getText().toString().trim();
String cnic = reporterCnic.getText().toString().trim();
String userLat = Lat;
String userLong = Long;
String date = eventDate.getText().toString().trim();
String time = eventTime.getText().toString().trim();
new createReportTask().execute(blockname, eventEsc, eventdesc, cnic, userLat, userLong, date, time);
}
}
});
}
public class createReportTask extends AsyncTask<String, String, JSONObject> {
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Creating Report", "in Pre Execute");
pDialog = new ProgressDialog(CreateReport.this);
pDialog.setMessage("Creating Report");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
pDialog.dismiss();
Toast.makeText(CreateReport.this, "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 2) {
Toast.makeText(CreateReport.this, message, Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Creating product
*/
protected JSONObject doInBackground(String... args) {
String blockName = args[0] != null ? args[0] : "";
String eventEscalation = args[1];
String eventDesc = args[2];
String userCnic = args[3];
String userLat = args[4];
String userLong = args[5];
String date = args[6];
String time = args[7];
if (blockName.trim().length() != 0 && eventEscalation.trim().length() != 0
&& eventDesc.trim().length() != 0 && userCnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
//db field name in value side
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("page", "datasync"));
params.add(new BasicNameValuePair("blockName", blockName));
params.add(new BasicNameValuePair("eventEscalation", eventEscalation));
params.add(new BasicNameValuePair("eventDesc", eventDesc));
params.add(new BasicNameValuePair("userCnic", userCnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
// getting JSON Object
// Note that create product url accepts POST method
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} else {
return null;
}
}
}
}
Fragment Code:
public class EventsReportFragment extends Fragment {
static final int REQUEST_AUTHORIZATION = 1001;
private RecyclerView recyclerView;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private boolean mAlreadyStartedService = false;
private TextView mMsgView;
View rootView;
String latitude;
String longitude;
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm:ss";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
public EventsReportFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mMsgView = (TextView) rootView.findViewById (R.id.msgView);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateReport.class);
intent.putExtra("lat", latitude);
intent.putExtra("long", longitude);
startActivity(intent);
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
startStep1();
}
/**
* Step 1: Check Google Play services
*/
private void startStep1() {
//Check whether this user has installed Google play service which is being used by Location updates.
if (isGooglePlayServicesAvailable()) {
//Passing null to indicate that it is executing for the first time.
startStep2(null);
} else {
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
}
}
/**
* Step 2: Check & Prompt Internet connection
*/
private Boolean startStep2(DialogInterface dialog) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
promptInternetConnect();
return false;
}
if (dialog != null) {
dialog.dismiss();
}
if (checkPermissions()) { //Yes permissions are granted by the user. Go to the next step.
startStep3();
} else { //No user has not granted the permissions yet. Request now.
requestPermissions();
}
return true;
}
/**
* Show A Dialog with button to refresh the internet state.
*/
private void promptInternetConnect() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("title_alert_no_intenet");
builder.setMessage("msg_alert_no_internet");
String positiveText = "Refresh Button";
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Block the Application Execution until user grants the permissions
if (startStep2(dialog)) {
//Now make sure about location permission.
if (checkPermissions()) {
//Step 2: Start the Location Monitor Service
//Everything is there to start the service.
startStep3();
} else if (!checkPermissions()) {
requestPermissions();
}
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Step 3: Start the Location Monitor Service
*/
private void startStep3() {
//And it will be keep running until you close the entire application from task manager.
//This method will executed only once.
if (!mAlreadyStartedService && mMsgView != null) {
mMsgView.setText("Location_service_started");
//Start location sharing service to app server.........
Intent intent = new Intent(getContext(), LocationMonitoringService.class);
getActivity().startService(intent);
mAlreadyStartedService = true;
//Ends................................................
}
}
/**
* Return the availability of GooglePlayServices
*/
public boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(getContext());
if (status != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(getActivity(), status, 2404).show();
}
return false;
}
return true;
}
/**
* Return the current state of the permissions needed.
*/
private boolean checkPermissions() {
int permissionState1 = ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
int permissionState2 = ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;
}
/**
* Start permissions requests.
*/
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
boolean shouldProvideRationale2 =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION);
// Provide an additional rationale to the img_user. This would happen if the img_user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale || shouldProvideRationale2) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale,
android.R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
});
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the img_user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
/**
* Shows a {#link Snackbar}.
*
* #param mainTextStringId The id for the string resource for the Snackbar text.
* #param actionStringId The text of the action item.
* #param listener The listener associated with the Snackbar action.
*/
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(
rootView.findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If img_user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission granted, updates requested, starting location updates");
startStep3();
} else {
showSnackbar(R.string.permission_denied_explanation,
R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
#Override
public void onDestroy() {
//Stop location sharing service to app server.........
getActivity().stopService(new Intent(getActivity(), LocationMonitoringService.class));
mAlreadyStartedService = false;
//Ends................................................
super.onDestroy();
}
public class MakeRequestTask extends AsyncTask<String, String, JSONObject> {
private Exception mLastError = null;
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
public MakeRequestTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
String cnic = args[0];
String userLat = args[1];
String userLong = args[2];
String date = args[3];
String time = args[4];
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (cnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
params.add(new BasicNameValuePair("page", "locationUpdate"));
params.add(new BasicNameValuePair("cnic", cnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
}
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} catch (Exception e) {
e.printStackTrace();
mLastError = e;
cancel(true);
return null;
}
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
Toast.makeText(getContext(), "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 1) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
} else if (success == 2){
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCancelled() {
}
}
}``
In onPostExecute check for activity is running before doing any work.
because onPostExecute may be called if activity was running not more
Try this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
//your remaining code here
}
Use following line:
String message = result.optString("message");
// it will returns the empty string ("") if the key you specify doesn't exist
instead of using
String message = result.getString("message");
// it will throws exception if the key you specify doesn't exist
replace getContext() with getActivity() inside your fragment
e.g replace
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
with
`Toast.makeText(getActivity(), "no_google_playservice_available", Toast.LENGTH_LONG).show();`
and
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
with
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
and so on if any.
I want to know how to send my coordinates via SMS by clicking a button. I have the following code that a message is sent, as sending the coordinates.
public class MainActivity extends AppCompatActivity {
Button Enviar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Enviar = (Button)findViewById(R.id.btnEnviar);
Enviar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EnviarMensaje("cell phone number","message");
}
});
}
private void EnviarMensaje (String Numero, String Mensaje){
try {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(Numero,null,Mensaje,null,null);
Toast.makeText(getApplicationContext(), "Mensaje Enviado.", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Mensaje no enviado, datos incorrectos.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
Follow these steps
String msg_txt ="";
// Declare as global variable
Enviar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(ComposeThreadsActivity.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Handle after selecting place
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (data != null) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s",
place.getName());
String address = String.valueOf(place.getAddress());
String placeName = String.valueOf(place.getName());
LatLng latLong = place.getLatLng();
String lat = String.valueOf(latLong.latitude);
String lon = String.valueOf(latLong.longitude);
StringBuilder sb = new StringBuilder();
if (!TextUtils.isEmpty(placeName)) {
if (placeName.contains(lat)) {
sb.append("http://maps.google.com/?q=" + lat + ","
+ lon);
} else {
sb.append("Place: " + placeName);
if (!TextUtils.isEmpty(address)) {
sb.append("\nAddress: " + address);
}
sb.append("\nLink: http://maps.google.com/?q="
+ lat + "," + lon);
}
msg_txt = sb.toString();
EnviarMensaje("cell phone number", msg_txt);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
it is giving me very strange output.On my first input the map camera shows the toast msg "address not found" and on my second input it takes me to my first location...and by continuing this process i am given the exception stated above...any hints , helps ,links would be highly appreciated...thankx..`
public void geolocation(View v) throws IOException {
if (check_connection()==false)
{
alert_user();
}
hidesoftkeyboard(v);
EditText et = (EditText) findViewById(R.id.edit_text1);
location= et.getText().toString();
gc = new Geocoder(this);
new my_second_thread().execute();
if (list == null )
{
Toast.makeText(this,"address not found",Toast.LENGTH_SHORT).show();
return;
}
else if ( list.size() > 0)
{
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this,"moving..", Toast.LENGTH_SHORT).show();
double latitude = add.getLatitude();
double longitude = add.getLongitude();
gotoloc(latitude, longitude, zoom);
add_markers(latitude, longitude, locality);
}
}
//the above function uses asyntask which is:
class my_second_thread extends AsyncTask<String, String, List<Address>>{
#Override
protected List<Address> doInBackground(String... params) {
try {
return gc.getFromLocationName(location, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Address> result) {
list = result;
}
}``
I am currently working on a project which requires me to enter and store user's input. Is there any way that I could do so that I can retrieve the previous records as well rather than the current record?
Code
package com.example;
// imports
public class Testing extends Activity {
String tag = "Testing";
EditText amount;
Uri rResult = null;
int request_Code = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testyourself);
amount = (EditText) findViewById(R.id.etUserInput);
Button saveButton = (Button) findViewById(R.id.btnSave);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.example.Result");
Bundle extras = new Bundle();
extras.putString("amount", amount.getText().toString());
intent.putExtras(extras);
startActivityForResult(intent, request_Code);
}
});
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
saveAsText(); // Step E.1
Log.d(tag, "In the onPause() event");
}
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
retrieveText(); // Step E.1
Log.d(tag, "In the onResume() event");
}
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
public void saveAsText() {
String line = amount.getText().toString();
if (rResult != null)
line += "|" + rResult;
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter pw = null;
try {
String path = Environment.getExternalStorageDirectory().getPath();
fw = new FileWriter(path + "/exercise.txt");
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
pw.println(line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pw != null)
pw.close();
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}// saveAsText
public void retrieveText() {
FileReader fr = null;
BufferedReader br = null;
try {
String line;
String path = Environment.getExternalStorageDirectory().getPath();
fr = new FileReader(path + "/exercise.txt");
br = new BufferedReader(fr);
line = br.readLine();
StringTokenizer st = new StringTokenizer(line, "|");
pullup.setText(st.nextToken());
bench.setText(st.nextToken());
String rResult;
if (st.hasMoreTokens())
rResult = st.nextToken();
else
rResult = "";
Log.d(tag, "readAsText: " + line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Results Page
public class Result extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
Bundle bundle = getIntent().getExtras();
int amount = Integer.parseInt(bundle.getString("amount"));
TextView ResultView = (TextView) findViewById(R.id.userInput);
ResultView.setText(String.valueOf(amount));
}
}
Instead of writing to a file you can use SharedPreferences which allows you to store information such as user inputs or statistics until explicitly removed. Even if you close your app and re-open it the information that you save using SharedPreferences will remain.
The selected answer for this question is a great example of creating a helper class for SharedPreferences that will allow you to easily save, retrieve, and delete information.
Assuming that you want to save an int value.
If your save and retrieve methods in your helper class are:
public void saveAmount(String key, int amount) {
_prefsEditor.putInt(key,amount);
_prefsEditor.commit();
}
public int getAmount(String key) {
return _sharedPrefs.getInt(key,0); //returns 0 if nothing is found
}
and you have an ArrayList of ints like so:
ArrayList<int> arrayList = new ArrayList<int>();
arrayList.add(123);
arrayList.add(231);
arrayList.add(312); //These are just placeholder values.
then you can create a loop to save:
private AppPreferences _appPrefs;
.
.
.
for(int i = 0; i < arrayList.size(); i++) {
_appPrefs.saveAmount(i,arrayList.get(i));
}
Note that in the above method the keys for the elements are just the indices of the elements within the array.
In order to retrieve the information and recreate the ArrayList you need to first save the length of the ArrayList in shared preferences as well.
public void saveLength(int length) {
_prefsEditor.putInt("length", length);
_prefsEditor.commit();
}
public int getLength() {
return _sharedPrefs.getInt("length",0);
}
then you can create a loop to retrieve:
ArrayList<int> arrayList = new ArrayList<int>();
.
.
.
for(int i = 0; i < _appPrefs.getLength(); i++) {
arrayList.add(getAmount("" + i));
}