Android Studio - Speech Recognizer - onResults - java

Any thoughts why doesnt this code invoke the onResults method ?
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextToSpeech myTTS;
private SpeechRecognizer mySpeechRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,3);
mySpeechRecognizer.startListening(intent);
}
});
initializeTextToSpeech();
initializeSpeechRecognizer();
}
private void initializeSpeechRecognizer() {
if(SpeechRecognizer.isRecognitionAvailable(this)){
mySpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mySpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
speak("im here");
List<String> result = results.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION
);
processResult(result.get(0));
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
private void initializeTextToSpeech() {
myTTS=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size()==0) {
Toast.makeText(MainActivity.this, "There's no TTS engine on this device", Toast.LENGTH_LONG).show();
finish();
}
else{
myTTS.setLanguage(Locale.US);
speak("Hello Im ready");
}
}
});
}
private void speak(String message){
if(Build.VERSION.SDK_INT>=21){
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,null,null);
}
else
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void processResult(String command){
command=command.toLowerCase();
speak(command);
}S
#Override
protected void onPause(){
super.onPause();
myTTS.shutdown();
}
}
-in my AndroidManifest.xml I got the uses-permission I really dont know whats wrong any opinion is welcomed, It seems like the app is somehow skipping initializeSpeechRecognizer();. The app is only supposed to repeat what I said so thats why my processResult method contains only speak("command");

The problem was that my virtual device for some reason didn't cooperate with PC mic, on real machine it works.

Related

Cannot resolve symbol "GooglePlayServicesClient"

In Google play service 10.0.1, for the following code, when building it I get the error:
“GooglePlayServicesClient” cannot resolve the symbol
Any idea how to resolve this?
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationRequest;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.asyncTasks.EmployeeSerchResult;
import com.shuan.Project.asyncTasks.GetEmployeeSerach;
import com.shuan.Project.employer.PostViewActivity;
import java.util.List;
import java.util.Locale;
public class EmplyeeSearchActivity extends AppCompatActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private Toolbar toolbar;
private Common mApp;
private Boolean flag = false;
private LocationClient mLocationClient;
private ProgressDialog pDialog;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
private ProgressBar progressBar;
private ListView list;
private AutoCompleteTextView preferSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
mApp = (Common) getApplicationContext();
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
setTheme(R.style.Junior);
} else {
setTheme(R.style.Senior);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emplyee_search);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
toolbar.setBackgroundColor(getResources().getColor(R.color.junPrimary));
} else {
toolbar.setBackgroundColor(getResources().getColor(R.color.senPrimary));
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
mLocationRequest = new LocationRequest();
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
list = (ListView) findViewById(R.id.ser_res);
preferSearch = (AutoCompleteTextView) findViewById(R.id.prefered_serach);
new GetEmployeeSerach(EmplyeeSearchActivity.this, progressBar, preferSearch).execute();
preferSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_SEARCH){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
preferSearch.dismissDropDown();
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, preferSearch.getText().toString(),
"all").execute();
}
return false;
}
});
preferSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
TextView txt = (TextView) view.findViewById(R.id.display);
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
preferSearch.setText(txt.getText().toString());
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, txt.getText().toString(),
txt1.getText().toString()).execute();
}
});
preferSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
list.setAdapter(null);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
Intent in = new Intent(getApplicationContext(), PostViewActivity.class);
in.putExtra("jId", txt.getText().toString());
in.putExtra("apply", "no");
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.emp_search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.gps) {
flag = gpsStatus();
if (flag) {
new displayCurrentLocation().execute();
} else {
showGpsAlert();
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public class displayCurrentLocation extends AsyncTask<String, String, String> {
String location;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EmplyeeSearchActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Searching");
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Location currentLocation = mLocationClient.getLastLocation();
Geocoder geocoder = new Geocoder(EmplyeeSearchActivity.this, Locale.getDefault());
Location loc = currentLocation;
List<android.location.Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
final android.location.Address address = addresses.get(0);
location = address.getLocality();
}
} catch (Exception e) {
}
return location;
}
#Override
protected void onPostExecute(final String s) {
super.onPostExecute(s);
pDialog.cancel();
Intent in = new Intent(getApplicationContext(), EmployeeSearchResultActivity.class);
in.putExtra("loc", s);
startActivity(in);
}
}
private void showGpsAlert() {
AlertDialog.Builder build = new AlertDialog.Builder(EmplyeeSearchActivity.this);
build.setTitle("Alert")
.setMessage("Turn On your GPS! Find the Jobs & companies")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);
dialog.cancel();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "Can't Find Employer", Toast.LENGTH_SHORT).show();
}
}).show();
}
private Boolean gpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStus) {
return true;
} else {
return false;
}
}
}
as mentioned in this answer i guess GooglePlayServiceClient and has become outdated so remove it and use GoogleApiClientinstead.Also LocationServices.API, and FusedLocationProviderApi were introduced.
Usage of GoogleApiClient :
To use GoogleApiClient the first thing to change is the interface, the activity or service is implementing
//old code of GooglePlayServiceClient :
public class LocationMonitoringService extends Service implements GooglePlayServicesClient.ConnectionCallbacks
//replace the above ^ code with this: new code for GoogleApiClient
public class LocationMonitoringService extends Service implements GoogleApiClient.ConnectionCallbacks
in GooglePlayServiceClient, mLocationClient was just a regular class constructor.
inGoogleApiClient a Builder is used like :
//old code of GooglePlayServiceClient :
LocationClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
replace it^ with new builder code of GoogleApiClient :
GoogleApiClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationClient.connect();
}
Examples :
Requesting location :
Old code was just a simple call like
mLocationClient.requestLocationUpdates(mLocationRequest, locationListener);
in GoogleApiClient we use FusedLocatonApi like :
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, locationListener);
This post shows you a implementation of most of the methods like :onConnected onConnectionFailed onConnectionSuspended etc.

Android: why my onResume() DialogInterface keeps looping non stop?

May I ask why my onResume() DialogInterface keeps looping non stop? I have reference the onResume() from this website: http://pulse7.net/android/android-delete-sms-message-from-inbox-in-android/
#Override
protected void onResume() {
super.onResume(); int i=0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if(i==0) {
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMain_txt.this);
builder.setMessage("This app is not set as your default messaging app. Do you want to set it as default?")
.setCancelable(false)
.setTitle("Alert!")
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#TargetApi(19)
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);
dialog.dismiss();
}
});
builder.show();
i++;}
}
}
But when I add this part of the code, the DialogInterface for "setPositiveButton" keeps looping non-stop. I am trying to set my application to become the default message application, so I will be able to delete messages. As now it is not set to become the default application, I am unable to delete any messages successfully. Any help will be deeply appreciated. Thanks in advance.
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.provider.Telephony;
import com.example.apple.qs.Activity.db.Constant;
import com.example.apple.qs.Activity.db.DatabaseHandler_txt;
import com.example.apple.qs.Activity.fragment.ContactFragment;
import com.example.apple.qs.Activity.fragment.FragmentAdapter;
import com.example.apple.qs.Activity.fragment.MessageFragment;
import com.example.apple.qs.Activity.db.model.Message;
import com.example.apple.qs.Activity.db.Store.ContactStore;
import com.example.apple.qs.Activity.db.Store.MessageStore;
import java.util.ArrayList;
import com.example.apple.qs.Activity.R;
import java.util.List;
public class ActivityMain_txt extends AppCompatActivity {
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar toolbar;
private DrawerLayout drawerLayout;
public static MessageFragment f_message;
private ContactFragment f_contact;
public FloatingActionButton fab;
private Toolbar searchToolbar;
private boolean isSearch = false;
private ViewPager viewPager;
private DatabaseHandler_txt db;
public ContactStore contacsStore;
public MessageStore messageStore;
public static List<Message> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_txt);
setupDrawerLayout();
db = new DatabaseHandler_txt(getApplicationContext());
toolbar = (Toolbar) findViewById(R.id.toolbar_viewpager);
searchToolbar = (Toolbar) findViewById(R.id.toolbar_search);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ActivityNewMessage_txt.class);
startActivity(i);
}
});
//initToolbar();
prepareActionBar(toolbar);
contacsStore = new ContactStore(getApplicationContext());
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
closeSearch();
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0) {
fab.show();
} else {
fab.hide();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// for system bar in lollipop
Window window = this.getWindow();
if (Constant.getAPIVerison() >= 5.0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
}
}
private void setupViewPager(ViewPager viewPager) {
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
if (f_message == null) {
f_message = new MessageFragment();
}
if (f_contact == null) {
f_contact = new ContactFragment();
}
adapter.addFragment(f_message, "MESSAGE");
adapter.addFragment(f_contact, "CONTACT");
viewPager.setAdapter(adapter);
}
private void prepareActionBar(Toolbar toolbar) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(getResources().getColor(isSearch ? android.R.color.darker_gray : R.color.colorPrimary));
}
if (!isSearch) {
settingDrawer();
}
}
private void settingDrawer() {
mDrawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close ) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(mDrawerToggle);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.nav_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
actionDrawerMenu(menuItem.getItemId());
return true;
}
});
}
private void actionDrawerMenu(int itemId) {
switch (itemId) {
case R.id.nav_notif:
Intent i = new Intent(getApplicationContext(), ActivityNotificationSettings_txt.class);
startActivity(i);
break;
case R.id.nav_rate:
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
break;
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About");
builder.setMessage(getString(R.string.about_text));
builder.setNeutralButton("OK", null);
builder.show();
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (!isSearch) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(isSearch ? R.menu.menu_search_toolbar_txt : R.menu.menu_main_txt, menu);
if (isSearch) {
//Toast.makeText(getApplicationContext(), "Search " + isSearch, Toast.LENGTH_SHORT).show();
final SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setIconified(false);
if (viewPager.getCurrentItem() == 0) {
search.setQueryHint("Search message...");
} else {
search.setQueryHint("Search contact...");
}
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter(s);
} else {
f_contact.mAdapter.getFilter().filter(s);
}
return true;
}
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
closeSearch();
return true;
}
});
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search: {
isSearch = true;
searchToolbar.setVisibility(View.VISIBLE);
prepareActionBar(searchToolbar);
supportInvalidateOptionsMenu();
return true;
}
case android.R.id.home:
closeSearch();
return true;
case R.id.action_refresh: {
if(viewPager.getCurrentItem()==0){
new RefreshMessage().execute("");
}else{
new RefreshContact().execute("");
}
}
default:
return super.onOptionsItemSelected(item);
}
}
private void closeSearch() {
if (isSearch) {
isSearch = false;
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter("");
} else {
f_contact.mAdapter.getFilter().filter("");
}
prepareActionBar(toolbar);
searchToolbar.setVisibility(View.GONE);
supportInvalidateOptionsMenu();
}
}
private ChangeObserver changeObserver;
// wil update only when there a change
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
try{
if(!loadRunning) {
loadRunning = true;
changeLoad = new ChangeLoad();
changeLoad.execute("");
}
}catch (Exception e){
}
}
}
private ChangeLoad changeLoad;
private boolean loadRunning = false;
private class ChangeLoad extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
messageStore.update();
return null;
}
#Override
protected void onPostExecute(String s) {
loadRunning = false;
messageList = messageStore.getAllconversation();
f_message.bindView();
super.onPostExecute(s);
}
}
public class RefreshMessage extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_message.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(100);
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_message.onStopRefreshLoading();
super.onPostExecute(s);
}
}
private class RefreshContact extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_contact.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(10);
db.truncateDB();
contacsStore = new ContactStore(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_contact.onStopRefreshLoading();
super.onPostExecute(s);
}
}
String myPackageName= getPackageName();
#Override
protected void onResume() {
super.onResume(); int i=0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if(i==0) {
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMain_txt.this);
builder.setMessage("This app is not set as your default messaging app. Do you want to set it as default?")
.setCancelable(false)
.setTitle("Alert!")
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#TargetApi(19)
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);
dialog.dismiss();
}
});
builder.show();
i++;}
}
}
}
}
You are using the variable i as a flag, but whenever you open your app the value of i will be 0 again. You should store your flag in a persistent database. Either use SQLite to set i or use any other method like create a file when the user says yes to your question and then check if the file exists or not. If you don't understand what I've told you, I can send you some code snippets.
OK, I assume you are using i as a flag to check if user has set your app as default or not, so I suggest you to use SharedPreferences to store the value of i so that later on you can check the value of i in a better manner. Add the following code in your onResume function:
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
Instead of i++ use:
editor.putInt(i, 1);
editor.commit();
And to check if i==0 use:
int check =sharedprferences.getInt(i);
if(check == 0) {...........}

Configuring Braintree

I am trying to accept BrainTree on my app. I don't understand the Async HTTP Client part.
Where do I place this in my app? Currently, I have it in the MainActivity and it is giving me errors for 'get', 'TextHttpResponseHandler' as well as 'clientToken'.
Any ideas?
package com.example.android.payments;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.loopj.android.http.*;
import com.braintreepayments.api.dropin.BraintreePaymentActivity;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://your-server/client_token", new TextHttpResponseHandler() {
#Override
public void onSuccess(String clientToken) {
this.clientToken = clientToken;
}
});
public void onBraintreeSubmit(View v) {
Intent intent = new Intent(context, BraintreePaymentActivity.class);
intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);
// REQUEST_CODE is arbitrary and is only used within this activity.
startActivityForResult(intent, REQUEST_CODE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Your call to client.get() is not in a method body, so your code is not syntactically valid. Try putting it in a method (or constructor or initializer block - but it's a bad idea to do work in either of those places).
For example, you could put that statement in a new method called fetchClientToken():
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) { ... }
AsyncHttpClient client = new AsyncHttpClient();
public void fetchClientToken() {
client.get("https://your-server/client_token", new TextHttpResponseHandler() {
#Override
public void onSuccess(String clientToken) {
this.clientToken = clientToken;
}
});
}
public void onBraintreeSubmit(View v) { ... }
#Override public boolean onCreateOptionsMenu(Menu menu) { ... }
#Override public boolean onOptionsItemSelected(MenuItem item) { ... }
}
You then need to invoke fetchClientToken somehow, just like you would with any other method.

Person Detail App

I am quite new to programming Android (7 months), and I am having a problem with creating an app.
What I am trying to do is create a "Person Detail" test app for my own Android learning, by having EditText on the Main Activity with TextViews next to them (displaying default values at first), open up another activity called EditData (with a button on the main) which displays the values the user entered into the EditText (via Parcelable), return back to the Main Activty (via another button) and have those entered values displayed in the TextViews next to the EditText (upon a "Update Info" button click) instead of the default ones. I have managed to get everything working right except for displaying the changed values. Everything checks out, no errors in LogCat, but when the user / I clicks the update button, what shows are the default values. Can someone help me?
Here is my Main Activity code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
final Person firstPerson = new Person();
TextView displayName, displayAge, displayHeight, displayWeight;
EditText editName, editAge, editHeight, editWeight;
Button editActivity, update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
instantiateUi();
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayName.setText(firstPerson.getPersonName());
displayAge.setText(String.valueOf(firstPerson.getPersonAge()));
// String.valueOf is needed to set int for TextViews
displayHeight.setText(String.valueOf(firstPerson.getPersonHeight()));
displayWeight.setText(String.valueOf(firstPerson.getPersonWeight()));
}
});
}
private void instantiateUi() {
editName = (EditText)findViewById(R.id.edit_name);
editAge = (EditText)findViewById(R.id.edit_age);
editHeight = (EditText)findViewById(R.id.edit_height);
editWeight = (EditText)findViewById(R.id.edit_weight);
displayName = (TextView)findViewById(R.id.display_name);
displayAge = (TextView)findViewById(R.id.display_age);
displayHeight = (TextView)findViewById(R.id.display_height);
displayWeight = (TextView)findViewById(R.id.display_weight);
editActivity = (Button)findViewById(R.id.edit_activity);
update = (Button)findViewById(R.id.update_info);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
My EditData activity code:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class EditData extends ActionBarActivity {
TextView changedName, changedAge, changedHeight, changedWeight;
Button MainActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
Person incomingObject = getIntent().getParcelableExtra("First_Person_Data");
instantiateUi();
changedName.setText(incomingObject.getPersonName());
changedAge.setText(String.valueOf(incomingObject.getPersonAge()));
changedHeight.setText(String.valueOf(incomingObject.getPersonHeight()));
changedWeight.setText(String.valueOf(incomingObject.getPersonWeight()));
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
EditData.this.startActivity(EditActivity);
}
});
}
private void instantiateUi() {
changedName = (TextView)findViewById(R.id.changed_name);
changedAge = (TextView)findViewById(R.id.changed_age);
changedHeight = (TextView)findViewById(R.id.changed_height);
changedWeight = (TextView)findViewById(R.id.changed_weight);
MainActivity = (Button)findViewById(R.id.main_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_data_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my Parcelable class used for transferring data values:
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
String personName;
int personAge, personHeight, personWeight;
public Person(){
personName = "No Name!";
personAge = 0;
personHeight = 0;
personWeight = 0;
}
public Person(String pName, int pAge, int pHeight, int pWeight) {
personName = pName;
personAge = pAge;
personHeight = pHeight;
personWeight = pWeight;
}
public Person(Parcel in) {
personName = in.readString();
personAge = in.readInt();
personHeight = in.readInt();
personWeight = in.readInt();
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
public int getPersonHeight() {
return personHeight;
}
public void setPersonHeight(int personHeight) {
this.personHeight = personHeight;
}
public int getPersonWeight() {
return personWeight;
}
public void setPersonWeight(int personWeight) {
this.personWeight = personWeight;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(personName);
dest.writeInt(personAge);
dest.writeInt(personHeight);
dest.writeInt(personWeight);
}
public static final Parcelable.Creator<Person> CREATOR =
new Parcelable.Creator<Person>() {
#Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Sorry if there are problems, this is my first question and I would very much appreciate what help you can give to a noob C0D3R :P
You shouldn't start variable names with capital letters. Your button MainActivity is very confusing. Better name it something like btMainActivity or something like that.
It think your problem is, that you forget to put an extra to your MainActivity, like you did when starting EditData:
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
// put your extra here
EditData.this.startActivity(EditActivity);
}
});
For what you want, you could also use startActivityForResult. Take a look at it! You should also check out AndroidAnnotations. It can safe you a lot of code and time. I can't imagine making an Android app without it anymore.

<s3dReadConfigFile:75>: Can't open file for reading error

I'm recieving an error when running on my galaxy s3 called ": Can't open file for reading" twice in my LogCat.
Here is my code:
package com.example.speechrecognizertest;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public static final String TAG = null;
private ListView wordList;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById(R.id.word_list);
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
if (!mIslistening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> suggestedWords = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
wordList.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.word, suggestedWords));
}
#Override
public void onRmsChanged(float rmsdB){}}
}
My LogCat is displaying idsactly what I described. Would really appreciate a fix guys!
I've seen this for a number of months on my S3 and it's never appeared to cause any problems. The answer here sounds probable to me.

Categories