Adding Yandex Translator to Fragment leads to "App Crashes" - android

I'm Using Yandex Translator in my app, it works great if i'm using Activity, But when i add it to fragment , the app crashes before the launch.
Also no errors shown in the code , like everything is good, what could be the problem :
I looked for similar answers here, but i got nothing, no one had this issue before using fragments.
And here is the code for fragment :
public class FavoritesFragment extends Fragment implements TextToSpeech.OnInitListener{
private TextView header, toText, toLabel, fromLabel;
private ImageView micFrom, volFrom, volTo, reverse;
private EditText fromText;
private CircleButton convertBTN;
private CircleButton convertLayout;
private final int REQ_CODE_SPEECH_INPUT = 100;
private final int SR_CODE = 123;
private String ENGLISH_CONSTANT = "";
private String TURKISH_CONSTANT = "";
private String ENGLISH_CONVERT = "";
private String TURKISH_CONVERT = "";
private String TURKISH_CODE = "";
private String currentFrom = "";
TextToSpeech ttsEnglish, ttsTURKISH;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_favorites, container, false);
setUpInitialConstants();
setUpInteraction();
setUpSpeakingListeners();
setUpListeners();
return v;
}
private void setUpInitialConstants() {
ENGLISH_CONSTANT = ("ENGLISH");
TURKISH_CONSTANT = ("TURKISH");
ENGLISH_CONVERT = ("en") + "-" + ("tr");//"en-zh";
TURKISH_CONVERT = ("tr") + "-" + ("en");
//"zh-en";
TURKISH_CODE = ("tr");
currentFrom = ENGLISH_CONSTANT;
}
private void setUpSpeakingListeners() {
ttsEnglish = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = ttsEnglish.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
ttsTURKISH = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
Locale locale = new Locale("tr-TR");
int result = ttsTURKISH.setLanguage(locale);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
}
#SuppressLint("ClickableViewAccessibility")
private void setUpListeners() {
convertLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
callReverse();
}
});
micFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
askSpeechInput(currentFrom);
}
});
volFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
ConvertTextToSpeech(currentFrom, fromText.getText().toString());
}
});
volTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
}
});
convertBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
});
toText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (copyToClipboard(getContext().getApplicationContext(), toText.getText().toString())) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
Toast.makeText(getContext().getApplicationContext(), ("copied"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext().getApplicationContext(), (" copied successfully "), Toast.LENGTH_SHORT).show();
}
}
}
});
fromText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fromText.setFocusableInTouchMode(true);
return false;
}
});
}
private String reverseCurrentFrom(String currentFrom) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
return TURKISH_CONSTANT;
} else return ENGLISH_CONSTANT;
}
private void callReverse() {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
currentFrom = TURKISH_CONSTANT;
//header.setText(getString(R.string.convertHeaderR));
fromLabel.setText(("TURKISH"));
fromText.setHint(("push to talk"));
toLabel.setText(("English"));
toText.setText(("Click translate Button to get English text"));
} else {
currentFrom = ENGLISH_CONSTANT;
//header.setText(getString(R.string.convertHeader));
fromLabel.setText(("English"));
fromText.setHint(("Speak or type text here"));
toLabel.setText(("TURKISH"));
toText.setText(("click to translate"));
}
fromText.setText("");
fromText.setFocusable(false);
}
private void setUpInteraction() {
this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toText = getView().findViewById(R.id.toText);
toLabel = getView().findViewById(R.id.toLabel);
fromLabel = getView().findViewById(R.id.fromLabel);
micFrom = getView().findViewById(R.id.micFrom);
volFrom = getView().findViewById(R.id.volFrom);
volTo = getView().findViewById(R.id.toVol);
convertBTN = getView().findViewById(R.id.convertBTN);
fromText = getView().findViewById(R.id.fromText);
convertLayout = getView().findViewById(R.id.swapLanguage);
fromText.setFocusable(false);
currentFrom = TURKISH_CONSTANT;
callReverse();
}
private void ConvertTextToSpeech(String lang_type, String text) {
if (text == null || "".equals(text)) {
if (lang_type.equals(ENGLISH_CONSTANT)) {
text = ("Content not available");
} else {
text = ("something wrong !");
}
}
if (lang_type.equals(ENGLISH_CONSTANT)) {
ttsEnglish.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} else {
ttsTURKISH.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
private void askSpeechInput(String lang_type) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
if (lang_type.equals(ENGLISH_CONSTANT)) {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Hi speak something");
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} else {
//Specify language
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_RESULTS, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ("speak please"));
startActivityForResult(intent, SR_CODE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
fromText.setText(result.get(0));
}
break;
}
case SR_CODE: {
if (resultCode == RESULT_OK) {
if (data != null) {
ArrayList<String> nBestList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String bestResult = nBestList.get(0);
fromText.setText(bestResult);
}
}
break;
}
}
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
} else {
Log.e("TTS", "Initialization failed");
}
}
String text_to_return = "";
private String translateText(final String text, final String lang) {
class getQData extends AsyncTask<String, String, String> {
ProgressDialog loading;
String ROOT_URL = "https://translate.yandex.net";
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build();
APICalls api = adapter.create(APICalls.class);
#Override
protected void onPreExecute() {
super.onPreExecute();
showPD();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... params) {
text_to_return = "";
String key = translator_Constants.MY_KEY;
Call<TranslateResponse> call = api.translate(key, text, lang);
call.enqueue(new Callback<TranslateResponse>() {
#Override
public void onResponse(retrofit.Response<TranslateResponse> response, Retrofit retrofit) {
//loading.dismiss();
hidePD();
Log.d("succ", "onResponse:code" + String.valueOf(response.code()));
Log.d("error mesg", String.valueOf(response.message()));
switch (response.code()) {
case 200:
TranslateResponse tr = response.body();
text_to_return = tr.getText().get(0);
toText.setText(text_to_return);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
break;
default:
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Please Try Again"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("again"), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onFailure(Throwable t) {
pd.dismiss();
Log.d("retro error", t.getMessage());
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Failed to Convert!Check Internet Connection"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("no connexion"), Toast.LENGTH_SHORT).show();
}
});
return text_to_return;
}
}
getQData ru = new getQData();
try {
ru.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return text_to_return;
}
ProgressDialog pd;
private void showPD() {
pd = new ProgressDialog(getActivity());
if (currentFrom.equals(ENGLISH_CONSTANT)) {
pd.setMessage(("Patience, We are translating…"));
} else {
pd.setMessage(("translating ..."));
}
pd.show();
}
private void hidePD() {
pd.dismiss();
}
public boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("copy", text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
}

Call setupInteraction() from onViewCreated(), not from onCreateView(). You are trying to use getView(), which will not work until onCreateView() returns.

Related

Why dialog for enabling dangerous android permissions is shown 2 times?

I am developing an app where I am using android's dialog for granting dangerous permissions. And when I click button for login on LoginActivity I go to Main activity and dialog is show. But when I press BACK button, again this dialog appears! This is my MainActivity(Just to say that my launcher activity is MAinActivity, not LoginActivity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
Bugsnag.init(this, BUGSNAG_API_KEY);
company_name = (TextView) findViewById(R.id.company_name);
aUsername = (TextView) findViewById(R.id.username);
company_name.setTextColor(ContextCompat.getColor(this, R.color.colorBlue));
// aUsername.setTextColor(ContextCompat.getColor(this, R.color.colorBlack));
toolbarImage = (ImageView) findViewById(R.id.image_id);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
getDataForToolbar();
checkIfServiceWorking();
askingForPermissionInManifest();
alertForEnablingGPS();
logoutWhenCompanyDisabled();
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("FCM", "Fire_base token is: " + token);
readTokenFromSharedPreferences();
initializeInjectorListIcons();
initializeListIcons();
initializeInjector();
initialize();
BottomBar bottomBar = (BottomBar) findViewById(R.id.bottomBar);
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
getFragment(tabId);
}
});
}
public static Context getContx() {
return mContext;
}
private void checkIfServiceWorking() {
mLocationService = new LocationService(getContx());
mServiceIntent = new Intent(getContx(), mLocationService.getClass());
if (!isMyServiceRunning(LocationService.class)){
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true + "");
return true;
}
}
Log.i ("isMyServiceRunning?", false + "");
return false;
}
private void initializeInjector() {
this.accountComponent = DaggerAccountComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.accountModule(new AccountModule())
.build();
}
public void initialize() {
this.getComponent(AccountComponent.class).inject(this);
this.accountPresenter.setView(this);
this.accountPresenter.initialize();
}
public void initializeInjectorListIcons() {
this.accountComponent = DaggerAccountComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.listIconsModule(new ListIconsModule())
.build();
}
public void initializeListIcons() {
this.getComponent(AccountComponent.class).inject(this);
this.listIconsPresenter.initializeListIcons();
}
#Override
public AccountComponent getComponent() {
return accountComponent;
}
#Override
public void viewAccount(AccountModel accountModel) {
if (accountModel != null) {
if (accountModel.getRoles().getName().equals(getResources().getString(R.string.role_team_leader)) || (accountModel.getRoles().getName().equals(getResources().getString(R.string.role_user)))){
Gson account_json = new Gson();
String account = account_json.toJson(accountModel);
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.Account_json), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getResources().getString(R.string.account_json), account);
editor.apply();
List<ButtonModel> arrayListButton = accountModel.getLayout().getButtons();
if (accountModel.getRoles().getName().equals(getResources().getString(R.string.role_user)) || accountModel.getRoles().getName().equals(getResources().getString(R.string.role_team_leader)) && arrayListButton.size() != 0) {
showLanguageSettings();
addFragment(R.id.fragment_container, new DashboardFragment());
goingToFragmentWithNotificationClick();
FirebaseMessaging.getInstance().subscribeToTopic(accountModel.getUuid());
for (CompanyModel com : accountModel.getCompanies()) {
String teamUuid = com.getTeam().getUuid();
String language = com.getLanguage().getCode();
SharedPreferences sharedPreferences1 = getSharedPreferences("language", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sharedPreferences1.edit();
editor1.putString("prefLanguage", language);
editor1.apply();
if (teamUuid != null) {
FirebaseMessaging.getInstance().subscribeToTopic(teamUuid);
}
}
FirebaseMessaging.getInstance().subscribeToTopic(accountModel.getRoles().getUuid());
} else if (arrayListButton.size() == 0 && accountModel.getRoles().getName().equals(getResources().getString(R.string.role_user)) || accountModel.getRoles().getName().equals(getResources().getString(R.string.role_team_leader))) {
addFragment(R.id.fragment_container, new EmptyListButtonFragment());
}
getDataForToolbar();
}
else {
removeTokenAndWrongAccountFromSharedPreferences();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_log_out) {
if (isNetworkConnected()) {
unsubscribingFromFirebase();
removeTokenAndAccountFromSharedPreferences();
shouldRestart = false;
stopService(mServiceIntent);
Log.i("MAIN_ACTIVITY", "Logout!");
Log.d("MAIN_ACTIVITY " , "Internet access ");
}
else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.need_internet), Toast.LENGTH_SHORT).show();
}
}
if (id == R.id.action_fcmToken) {
TextView textView = new TextView(this);
textView.setHeight(300);
textView.setText(FirebaseInstanceId.getInstance().getToken());
textView.setTextIsSelectable(true);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Token");
builder.setView(textView)
.setCancelable(true)
.show();
}
if (id == R.id.versionInfo) {
getCurrentAppVersionInfo();
}
if (id == R.id.LocationInfo){
getLocationInfo();
}
return super.onOptionsItemSelected(item);
}
public void readTokenFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
final String strPref = sharedPreferences.getString(getResources().getString(R.string.token), null);
if (strPref == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
public void removeTokenAndAccountFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
sharedPreferences.edit().remove(getResources().getString(R.string.token)).apply();
final String strPref = sharedPreferences.getString(getResources().getString(R.string.token), null);
SharedPreferences sharedPreferencesAccount = getSharedPreferences(getResources().getString(R.string.Account_json), MODE_PRIVATE);
sharedPreferencesAccount.edit().remove(getResources().getString(R.string.account_json)).apply();
final String accountPref = sharedPreferencesAccount.getString(getResources().getString(R.string.account_json), null);
if (strPref == null && accountPref == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
public void removeTokenAndWrongAccountFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
String strPref;
strPref = sharedPreferences.getString(getResources().getString(R.string.token), null);
SharedPreferences sharedPreferencesAccount = getSharedPreferences(getResources().getString(R.string.Account_json), MODE_PRIVATE);
String accountPref;
accountPref=sharedPreferencesAccount.getString(getResources().getString(R.string.account_json), null);
if(strPref != null || accountPref != null){
sharedPreferences.edit().remove(getResources().getString(R.string.token)).apply();
sharedPreferencesAccount.edit().remove(getResources().getString(R.string.account_json)).apply();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
Toast.makeText(MainActivity.this, getResources().getString(R.string.message_for_roles), Toast.LENGTH_LONG).show();
}
}
public void getFragment(int id) {
switch (id) {
case R.id.tab_menu_dashboard:
addFragment(R.id.fragment_container, new DashboardFragment());
break;
case R.id.tab_menu_messages:
addFragment(R.id.fragment_container, new MessagesFragment());
break;
case R.id.tab_menu_team:
addFragment(R.id.fragment_container, new TeamFragment());
break;
case R.id.tab_menu_incidents:
addFragment(R.id.fragment_container, new IncidentsFragment());
break;
}
}
#Override
protected void onResume() {
readTokenFromSharedPreferences();
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
#Override
protected void onPause() {
super.onPause();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
stopService(mServiceIntent);
Log.i("MAIN_ACTIVITY", "onDestroy!");
}
public void goingToFragmentWithNotificationClick() {
String clickNotification = getIntent().getStringExtra("notification_type");
String clickReportActivity = getIntent().getStringExtra("report_activity");
if (clickNotification != null) {
if (mAccount != null) {
if (mAccount.getRoles().getName().equals(getResources().getString(R.string.role_team_leader))) {
if (clickNotification.equals("incident_notify")) {
addFragment(R.id.fragment_container, new IncidentsFragment());
} else if (clickNotification.equals("chat_message")) {
addFragment(R.id.fragment_container, new MessagesFragment());
}
} else {
if (clickNotification.equals("chat_message")) {
addFragment(R.id.fragment_container, new MessagesFragment());
}
}
}
}
if(clickReportActivity!=null){
addFragment(R.id.fragment_container, new IncidentsFragment());
}
}
public void picassoLoader(Context context, ImageView imageView, String url) {
Picasso.with(context)
.load(url)
.resize(70, 58)
.transform(new RoundedTransformation(8, 0))
.into(imageView);
}
private void getCurrentAppVersionInfo() {
int versionCode = -1;
String versionName = "";
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
versionCode = packageInfo.versionCode;
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String alert1 = "Version Code: " + versionCode;
String alert2 = "Version Name: " + versionName;
builder.setMessage(alert1 + "\n" + alert2).show();
}
#SuppressLint("SetTextI18n")
public void getDataForToolbar() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.Account_json), Context.MODE_PRIVATE);
final String account = sharedPreferences.getString(getResources().getString(R.string.account_json), null);
if (account != null) {
Gson gson = new Gson();
mAccount = gson.fromJson(account, AccountModel.class);
for (CompanyModel com : mAccount.getCompanies()) {
String name = com.getName();
company_name.setText(name);
logo_url = com.getLogo_url();
}
if (logo_url == null || logo_url.isEmpty()) {
Picasso
.with(this)
.load(R.drawable.default_company)
.resize(70, 58)
.transform(new RoundedTransformation(8, 0))
.into(toolbarImage);
} else {
picassoLoader(this, toolbarImage, logo_url);
}
String username = mAccount.getUsername();
if(mAccount.getStatus()){
aUsername.setText(username + "/" + getResources().getString(R.string.on_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorGreen));
}else{
aUsername.setText(username + "/" + getResources().getString(R.string.off_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorWhite));
}
}
}
public void alertForEnablingGPS() {
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(getResources().getString(R.string.enable_location_Service));
builder.setMessage(getResources().getString(R.string.GPS));
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
public void logoutWhenCompanyDisabled() {
String logout = getIntent().getStringExtra("notification_type");
if (logout != null) {
if (logout.equals("company_disabled")) {
unsubscribingFromFirebase();
removeTokenAndAccountFromSharedPreferences();
}
}
}
public void unsubscribingFromFirebase() {
if (mAccount != null) {
if (mAccount.getRoles().getName().equals(getResources().getString(R.string.role_user)) || mAccount.getRoles().getName().equals(getResources().getString(R.string.role_team_leader))) {
FirebaseMessaging.getInstance().unsubscribeFromTopic(mAccount.getUuid());
FirebaseMessaging.getInstance().unsubscribeFromTopic(mAccount.getRoles().getUuid());
for (CompanyModel com : mAccount.getCompanies()) {
String teamUuid = com.getTeam().getUuid();
if (teamUuid != null) {
FirebaseMessaging.getInstance().unsubscribeFromTopic(teamUuid);
}
Log.d("FCM", "UnSubscribed on team Uuid: " + teamUuid);
}
}
}
}
public class RoundedTransformation implements com.squareup.picasso.Transformation {
private final int radius;
private final int margin;
public RoundedTransformation(final int radius, final int margin) {
this.radius = radius;
this.margin = margin;
}
#Override
public Bitmap transform(final Bitmap source) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() - margin, source.getHeight() - margin), radius, radius, paint);
if (source != output) {
source.recycle();
}
return output;
}
#Override
public String key() {
return "rounded";
}
}
private boolean isNetworkConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
public void askingForPermissionInManifest(){
if((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) != PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
}else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("all", "good");
alertForEnablingGPS();
restartActivity();
} else {
Log.d("need location", "need permissions");
}
break;
}
}
}
This is LogIn activity:
public class LoginActivity extends BaseActivity implements HasComponent<LoginComponent>, TokenView {
Credentials credentials;
TextInputEditText username;
TextInputEditText password;
Button login;
Configuration config;
private LoginComponent loginComponent;
#Inject LoginPresenter loginPresenter;
static Context mContext;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
checkLanguage();
username = (TextInputEditText)findViewById(R.id.username);
password = (TextInputEditText)findViewById(R.id.password);
credentials = new Credentials();
login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getUsername = username.getText().toString();
String getPassword = password.getText().toString();
if (getUsername.length()>0 && getPassword.length()>0 ) {
credentials.setUsername(getUsername);
credentials.setPassword(getPassword);
allOperations();
} else {
Toast.makeText(LoginActivity.this, R.string.empty_fields , Toast.LENGTH_LONG).show();
}
}
});
}
private void initializeInjector() {
this.loginComponent = DaggerLoginComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.loginModule(new LoginModule(this.credentials))
.build();
}
public void initialize () {
this.getComponent(LoginComponent.class).inject(this);
this.loginPresenter.setView(this);
this.loginPresenter.initialize(this.credentials);
}
#Override
public void viewToken(TokenModel tokenModel) {
if (tokenModel != null) {
String tokMod = tokenModel.getToken();
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getResources().getString(R.string.token), tokMod);
editor.apply();
Log.d("Token na logovanju je: ", "TokenLogo" + tokMod);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
public void allOperations () {
initializeInjector();
initialize();
}
#Override
public LoginComponent getComponent() {
return loginComponent;
}
#Override
public void showLoading() {
}
#Override
public void hideLoading() {
}
#Override
public void showRetry() {
}
#Override
public void hideRetry() {
}
#Override
public void showError(int message) {
Toast.makeText(LoginActivity.this, message , Toast.LENGTH_LONG).show();
}
#Override
public Context context() {
return null;
}
#Override public void onDestroy() {
super.onDestroy();
if (loginPresenter != null) {
this.loginPresenter.destroy();
}
}
public void checkLanguage(){
SharedPreferences sharedPreferences = getSharedPreferences("language", MODE_PRIVATE);
String language = sharedPreferences.getString("prefLanguage", null);
config = new Configuration(getResources().getConfiguration());
if(language!=null){
if(language.equals("en")){
config.locale = Locale.ENGLISH;
}
if(language.equals("sr")){
config.locale = new Locale("sr");
}
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
onConfigurationChanged(config);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public static void downloadFile(String uRl, String name_image) {
File direct = new File(Environment.getExternalStorageDirectory() + "/icons");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Incident icons for dashboard.")
.setDestinationInExternalPublicDir("/icons", name_image);
mgr.enqueue(request);
}}
Could anyone helps me how to fix this problem, how to get this dialog only when I login into Main activity, not when I click BACK button? Thanks in advance.

listview change to default when keyboard opens

In a list view i have image, text and image contains default image when list load with download complete , every thing works fine but when keyboard opens the downloaded image change to default image.
public class ChatScreen extends Activity implements OnClickListener
{
private void stopTimer()
{
if (mTimer1 != null)
{
mTimer1.cancel();
mTimer1.purge();
}
}
private void startTimer()
{
mTimer1 = new Timer();
mTt1 = new TimerTask()
{
public void run()
{
mTimerHandler.post(new Runnable()
{
public void run()
{
try
{
Date date1 = getDate(time);
Date date2 = getDate(getCurrentTime());
if (date2.getTime() - date1.getTime() == 5000)
{
stopTimer();
try
{
chat.setCurrentState(ChatState.paused,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
else if (date2.getTime() - date1.getTime() > 30000)
{
time = getCurrentTime();
try
{
chat.setCurrentState(ChatState.gone,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
}
catch (ParseException e)
{
e.printStackTrace();
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
}
});
}
};
mTimer1.schedule(mTt1, 00, 5000);
}
#Override
protected void onPause()
{
super.onPause();
chat.setChatFragment(null);
System.out.println("onPasue called");
}
}
}
}
}
}
#Override
protected void onResume()
{
super.onResume();
session.saveCurrentName(this.getLocalClassName());
chat.setChatFragment(ctx);
System.out.println("onResume called");
if(checkForCurfew())
showHideView(true, 0);
else
showHideView(false, 0);
}
public void showHideView(final boolean value, final int type)
{
System.out.println("Called");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if(value)
{
btnSend.setEnabled(value);
btnSend.setAlpha(1.0f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(1.0f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(1.0f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(1.0f);
}
else
{
btnSend.setEnabled(value);
btnSend.setAlpha(0.5f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(0.5f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(0.5f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(0.5f);
}
if(!value && type == 0)
inputMessage.setHint("You can't chat during a curfew");
else if(!value && type == 1)
inputMessage.setHint("Can’t Access Internet");
else
inputMessage.setHint("Enter message here");
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
System.gc();
setContentView(R.layout.activity_fragment_chat);
System.out.println("Chat screen called.");
mcon = ChatScreen.this;
chat = ((RooChat) getApplication()).chat;
Bundle bundle = getIntent().getBundleExtra("bundle_data");
System.out.println("bundle- " + bundle);
chatWithJID = bundle.getString("chat_with");
chatWithName = bundle.getString("kid_name");
FromChatJID = bundle.getString("chat_from");
ChatRoomName = bundle.getString("chat_room");
indexOfChatRoom = Integer.parseInt(bundle.getString("index"));
CopyindexOfChatRoom = indexOfChatRoom;
typeFaceCurseCasual = AppFonts.getFont(mcon, AppFonts.CurseCasual);
typeFaceARLRDBDHand = AppFonts.getFont(mcon, AppFonts.ARLRDBDHand);
back = (Button) findViewById(R.id.back);
sendBtn=(Button)findViewById(R.id.send);
sendBtn.setOnClickListener(this);
erasebtn=(Button)findViewById(R.id.erase);
erasebtn.setOnClickListener(this);
smallers=(Button)findViewById(R.id.small_ers1);
smallers.setOnClickListener(this);
mediumers=(Button)findViewById(R.id.medium_ers1);
mediumers.setOnClickListener(this);
largeers=(Button)findViewById(R.id.large_ers1);
largeers.setOnClickListener(this);
smallline=(Button)findViewById(R.id.small);
smallline.setOnClickListener(this);
mediumline=(Button)findViewById(R.id.medium);
mediumline.setOnClickListener(this);
largeline=(Button)findViewById(R.id.large);
largeline.setOnClickListener(this);
back1=(Button)findViewById(R.id.back1);
back1.setOnClickListener(this);
drawView=(DrawingView)findViewById(R.id.Drawing);
doodle_btn=(Button)findViewById(R.id.doodle_btn);
doodle_btn.setOnClickListener(this);
doodle=(LinearLayout) findViewById(R.id.doodle);
back.setOnClickListener(this);
init();
String available = convertAvailability(chat.getUserAvailability(chatWithJID));
if (chatWithName.equalsIgnoreCase("echo") || chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr"))
{
image.setImageResource(R.drawable.status_active);
}
else if (available.equalsIgnoreCase("offline"))
{
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
}
else
{
// chatState.setText(available);
image.setImageResource(R.drawable.status_active);
}
inputMessage.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (chat.isConnected())
{
try
{
time = getCurrentTime();
}
catch (ParseException e1)
{
e1.printStackTrace();
}
if (isTyping == false)
{
try
{
chat.setCurrentState(ChatState.composing, chatWithJID, FromChatJID);
isTyping = true;
startTimer();
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
else if (isTyping == true)
{
stopTimer();
startTimer();
}
}
/*else
Toast.makeText(getApplicationContext(), "Please wait, connecting to server.", 0).show();
*/
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
inputMessage.setOnFocusChangeListener(new OnFocusChangeListener()
{
#Override
public void onFocusChange(final View v, final boolean hasFocus)
{
if (hasFocus && inputMessage.isEnabled() && inputMessage.isFocusable())
new Runnable()
{
#Override
public void run()
{
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(inputMessage, InputMethodManager.SHOW_IMPLICIT);
}
};
}
});
data = session.getUserDetails();
banned = session.getBannedWord();
System.out.println(banned);
JSONArray jsonArray;
if(!banned.equals(""))
{
try
{
jsonArray = new JSONArray(banned);
strArr = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++)
{
strArr[i] = jsonArray.getString(i);
}
//System.out.println(Arrays.toString(strArr));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
public void reFreshData()
{
indexOfChatRoom = db.getChatRoomIndex(chatWithName);
messages = db.getFriendChat(indexOfChatRoom);
adapter = new ChatMessageAdapter(mcon, messages);
chatList.setAdapter(adapter);
}
private void init()
{
db = new DatabaseHelper(mcon);
ctx = this;
chat.setChatFragment(ctx);
session = new SessionManager(mcon);
chatList = (ListView) findViewById(R.id.chatList);
chatWith = (TextView) findViewById(R.id.chat_with);
doodle_txt = (TextView) findViewById(R.id.doodle_txt);
chatState = (TextView) findViewById(R.id.chat_status);
btnPicture = (TextView) findViewById(R.id.picture);
btnPicture.setOnClickListener(this);
btnSticker = (TextView) findViewById(R.id.sticker);
btnSticker.setOnClickListener(this);
btnExtra = (TextView) findViewById(R.id.extra);
btnExtra.setOnClickListener(this);
btnSend = (TextView) findViewById(R.id.btn_send);
btnSend.setTypeface(typeFaceARLRDBDHand, Typeface.BOLD);
btnSend.setOnClickListener(this);
inputMessage = (EditText) findViewById(R.id.et_message);
inputMessage.setTypeface(typeFaceCurseCasual);
chatWith.setText(chatWithName);
image = (ImageView) findViewById(R.id.img_chat_status);
cross = (ImageView) findViewById(R.id.cross);
cross.setOnClickListener(this);
lay_sticker_main = (LinearLayout) findViewById(R.id.lay_sticker_main);
lay_sticker_child = (FlowLayout) findViewById(R.id.lay_sticker_child);
lay_sticker_group = (FlowLayout) findViewById(R.id.lay_sticker_group);
reFreshData();
chatList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, final int arg2,
long arg3) {
// TODO Auto-generated method stub
final ChatMessage msg=adapter.getItem(arg2);
final ImageView btn = (ImageView) arg1.findViewById(R.id.textView1);
final ImageView imgone = (ImageView)arg1.findViewById(R.id.imagev);
try{
if(!btn.getTag().toString().equals("")){
Log.v("","msg getting:..."+btn.getTag().toString());
DownloadImage di=new DownloadImage(ChatScreen.this, btn.getTag().toString(), new BitmapAsyncTaskCompleteListener() {
#Override
public void onTaskComplete(Bitmap result) {
// TODO Auto-generated method stub
Log.v("Img :",""+result);
imgone.setImageBitmap(result);
String filePath=saveImage(result,msg.getId(),msg.getFrom());
btn.setVisibility(View.GONE);
btn.setTag(filePath);
final int index = chatList.getFirstVisiblePosition();
View v = chatList.getChildAt(0);
final int top = (v == null) ? 0 : v.getTop();
Log.v("", "top :.."+top);
chatList.post(new Runnable() {
#Override
public void run() {
chatList.setSelectionFromTop(index,top);
}
});
}
});
di.execute();
}
}
catch(Exception ex){
btn.setVisibility(View.GONE);
btn.setTag("");
}
}
});
handler = new Handler(Looper.getMainLooper())
{
#Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case REFRESH_CHAT_LIST:
adapter.notifyDataSetChanged();
break;
case REFRESH_CHAT_STATUS:
if(text != null)
{
try
{
if (isNumeric(text))
{
chatState.setText(calculateTime(Long.parseLong(text)));
image.setImageResource(R.drawable.status_offline);
}
else
{
chatState.setText(text);
if (chatWithName.equalsIgnoreCase("echo")
|| chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr")) {
image.setImageResource(R.drawable.status_active);
} else if (text.equalsIgnoreCase("offline")) {
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
} else {
image.setImageResource(R.drawable.status_active);
}
}
}
catch(NumberFormatException e)
{
image.setImageResource(R.drawable.status_offline);
e.printStackTrace();
}
}
break;
case REFRESH_MESSAGE_DELIVERY:
adapter.notifyDataSetChanged();
break;
default:
break;
}
}
};
}String filePath ="";
private String saveImage(Bitmap finalBitmap,int chatWith,String from) {
String fileName = chat.getCurrentDateTime();
//msg = "You got a photo. Display of photo will be added in next version of this app.";
final File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "/roo_kids/images/" + from + "/");
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, fileName + ".png");
if (!myFile.exists())
{
try
{
myFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(myFile);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath= myFile.getAbsolutePath()+"::images::";
Log.v("","filePath after decoding:.."+filePath);
Log.v("","chatWith Id after decoding:.."+chatWith);
Log.v("","from after decoding:.."+from);
db.updateFriendChat(chatWith,filePath);
return filePath;
}
public void getAllFiles(String directoryName)
{
}
public boolean isFileExist(String directoryName, String filename)
{
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.picture:
openGallery();
break;
case R.id.extra:
break;
case R.id.btn_send:
sendMessageAndValidate();
break;
case R.id.back:
onBackPressed();
break;
default:
break;
}
}
private void openGallery()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
//intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(intent, SELECT_PICTURE);
}
private String encodeFileToBase64Binary(String path)throws IOException, FileNotFoundException
{
}
String cond="";
public class ExecuteImageSharingProcess extends AsyncTask<String, Integer, String>
{
String base64 = "";
ProgressDialog pd = null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(ChatScreen.this);
pd.setCancelable(false);
pd.setMessage("Please wait..");
pd.show();
}
#Override
protected String doInBackground(String... params)
{
try
{
//base64 = encodeFileToBase64Binary(params[0]);
Log.v("", "params[0].."+params[0]);
byte[] data = params[0].getBytes("UTF-8");
base64= new String(data);
Log.v("", "base64.."+base64);
return "yes";
}
catch (IOException e)
{
e.printStackTrace();
return "no";
}
catch(NullPointerException e)
{
return "no";
}
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(result.equals("yes"))
{
if(chat.isConnected())
{
String prefix = chat.generateRandomChar()+"imagePrefixEnd";
System.out.println("prefix-> "+prefix);
ctx.moveMessagetoXMPP(prefix + base64 + "::images::", 1);
base64 = "";
bitmap = null;
}
}
else
{
Toast.makeText(ctx, "File not found.", Toast.LENGTH_LONG).show();
}
try
{
if ((this.pd != null) && this.pd.isShowing())
{
this.pd.dismiss();
}
} catch (final IllegalArgumentException e)
{
} catch (final Exception e)
{
} finally
{
this.pd = null;
}
}
}
String imgDecodableString = null;
String imgbase64="";
AlertManager alert_dialog;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent i)
{
super.onActivityResult(requestCode, resultCode, i);
try
{
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data)
{
String urlofimage=""; // here i send base64 image to server and it will returns url of image that is send in ExecuteImageSharingProcess method.
new ExecuteImageSharingProcess().execute(urlofimage);
}
});
ucIA.execute();
}
}
else if (resultCode == Activity.RESULT_CANCELED)
{
bitmap = null;
}
} catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
private void sendMessageAndValidate()
{
String msg=inputMessage.getText().toString().replace(" ","");
String msgone=msg.replace("\n", "");
if (msgone.length() > 0)
{
if (chat.isConnected())
{
ctx.moveMessagetoXMPP(inputMessage.getText().toString(), 0);
inputMessage.setText("");
stopTimer();
}
}
}
String thread="";
protected void moveMessagetoXMPP(String msg, final int type)
{
data = session.getUserDetails();
if (checkChatRoomAvailablity(chatWithName))
{
thread = db.getThreadFromChatroom(chatWithName);
}
if (thread.equals(""))
thread = ChatRoomName;
chat.sendMesage(indexOfChatRoom, msg, FromChatJID, chatWithJID, thread, type);
try
{
chat.setCurrentState(ChatState.paused, chatWithJID, FromChatJID);
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
public class MyThread implements Runnable
{
String message;
File file;
public MyThread(String message, File file)
{
this.message = message;
this.file = file;
}
#Override
public void run()
{
String fileName;
if(message.contains("::images::"))
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::images::"))), file);
else
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::doodle::"))), file);
}
}
public void appendMessageInListView(long _id)
{
if (messages.size() > 0)
{
System.out.println(messages.get(messages.size() - 1).getId());
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, ""+ messages.get(messages.size() - 1).getId());
messages.add(messages.size(), cm);
}
else
{
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, "" + _id);
messages.add(messages.size(), cm);
}
refreshChatList();
}
public void refreshChatList()
{
int state = REFRESH_CHAT_LIST;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public void refreshChatStatus() {
int state = REFRESH_CHAT_STATUS;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public int getChatIndex2(String participant) {
return db.getChatRoomIndex(participant);
}
ImageView img;
View oldview;
public class ChatMessageAdapter extends BaseAdapter
{
public ArrayList<ChatMessage> messages;
private Context ctx;
public ChatMessageAdapter(Context ctx, ArrayList<ChatMessage> messages)
{
this.ctx = ctx;
this.messages = messages;
}
#Override
public int getCount()
{
return messages.size();
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
#Override
public View getView(int position, View oldView, ViewGroup parent)
{
if (ctx == null)
return oldView;
final ChatMessage msg = getItem(position);
if (oldView == null || (((Integer) oldView.getTag()) != msg.getIsOutgoing()))
{
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
{
oldView = inflater.inflate(R.layout.fragment_message_outgoing_item, null);
oldView.setTag(MyMessage.OUTGOING_ITEM);
}
else
{
oldView = inflater.inflate(R.layout.fragment_message_ingoing_item, null);
oldView.setTag(MyMessage.INGOING_ITEM);
}
}
TextView message = (TextView) oldView.findViewById(R.id.msg);
message.setTypeface(typeFaceCurseCasual);
LinearLayout lay_txt = (LinearLayout) oldView.findViewById(R.id.lay_txt);
LinearLayout lay_img = (LinearLayout) oldView.findViewById(R.id.lay_img);
img = (ImageView) oldView.findViewById(R.id.imagev);
FrameLayout fmlay=(FrameLayout) oldView.findViewById(R.id.fmlay);
ImageView textView1 = (ImageView) oldView.findViewById(R.id.textView1);
ImageView imgSticker = (ImageView) oldView.findViewById(R.id.img_sticker);
ImageView tickSent = (ImageView) oldView.findViewById(R.id.tickSent);
ImageView tickDeliver = (ImageView) oldView.findViewById(R.id.tickDeliver);
TextView timestamp = (TextView) oldView.findViewById(R.id.timestamp);
oldview=oldView;
timestamp.setTypeface(typeFaceCurseCasual);
message.setText(msg.getMessage());
System.out.println("message in adapter");
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
tickSent.setVisibility(View.VISIBLE);
else
tickSent.setVisibility(View.INVISIBLE);
if (msg.getIsDeliver() == true)
tickDeliver.setVisibility(View.VISIBLE);
else
tickDeliver.setVisibility(View.INVISIBLE);
if(msg.getTimeStamp()!= null) timestamp.setText(getTimeAgo(Long.parseLong(msg.getTimeStamp()),ctx));
if(msg.getMessage()!= null)
{
if(msg.getMessage().contains("::sticker::"))
{
lay_img.setVisibility(View.GONE);
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.VISIBLE);
String Dir = msg.getMessage().substring(2, msg.getMessage().indexOf("-"));
String file = msg.getMessage().substring(2, msg.getMessage().indexOf("}}"));
if(isFileExist(Dir, file))
{
String path = ctx.getFilesDir() + "/booksFolder/"+Dir+"/"+file;
System.out.println("path- "+ path);
Uri imgUri = Uri.parse("file://"+path);
imgSticker.setImageURI(imgUri);
}
else
{
String url = "http://s3.amazonaws.com/rk-s-0ae8740/a/"+file;
System.out.println(url);
new ImageLoaderWithImageview(mcon).DisplayImage(url, imgSticker);
}
}
else if(!msg.getMessage().contains("::images::") && !msg.getMessage().contains("::doodle::"))
{
System.out.println("in text condition");
lay_img.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_txt.setVisibility(View.VISIBLE);
System.out.println("msg coming :"+msg.getMessage());
message.setText(msg.getMessage());
}
else
{
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_img.setVisibility(View.VISIBLE);
if (msg.getIsOutgoing() == MyMessage.INGOING_ITEM)
{
fmlay.setVisibility(View.VISIBLE);
}
Log.v("","msg getting:..."+msg.getMessage());
String pathOne = null ;
if(msg.getMessage().contains("imagePrefixEnd")){
Log.v("In images/doddle if", "askfk");
pathOne="default";
textView1.setVisibility(View.VISIBLE);
String imgpath=setdefaultImage(msg.getMessage());
textView1.setTag(imgpath);
}
else {
Log.v("In images else", "askfk");
try{
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::images::"));
}
catch(Exception ex){
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::doodle::"));
}
textView1.setVisibility(View.GONE);
Bitmap bitmap=setImage(pathOne);
img.setImageBitmap(bitmap);
textView1.setTag("");
}
}
}
return oldview;
}
#Override
public ChatMessage getItem(int position)
{
return messages.get(position);
}
}
public String setdefaultImage(String msg){
Bitmap bImage = BitmapFactory.decodeResource(ChatScreen.this.getResources(), R.drawable.dummyimage);
img.setImageBitmap(bImage);
String urlpath="";
try{
urlpath = msg.substring(0, msg.indexOf("::images::"));
}
catch(Exception ex){
urlpath = msg.substring(0, msg.indexOf("::doodle::"));
}
//Log.v("","msg getting:..."+urlpath);
String pt[]=urlpath.split("PrefixEnd");
//System.out.println("path :"+pt[1]);
return pt[1];
}
public Bitmap setImage(String pathOne){
Bitmap bitmap=null;
File imgFile = new File(pathOne);
//Log.v("","msg image path:..."+pathOne);
if(imgFile.exists())
{
//Log.v("","msg path exits:...");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap= BitmapFactory.decodeFile(pathOne, options);
}
else{
}
return bitmap;
}
}
Try to tag the data model/ data source with your list view view.setTag(dataModel) in getView method of your adapter class.
Why not try RecyclerView instead of ListView and use Fresco Image Library?

Android: "unable to add window token is not valid is your activity running?" in my SplashScreenActivity

I am new to android and now I am creating a app with splash screen as a launcher activity.
When I am trying to open the app it shows unable to add window token is not valid is your activity running.But if I open the app second time then it is working fine
My code is here:
public class SplashScreenActivity extends Activity {
private String mSavedEmail;
private String mSavedPassword;
public static SplashScreenActivity sInstance = null;
private User mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_splash_screen);
SplashScreenActivity.sInstance = SplashScreenActivity.this;
/* Initiate Crittercism */
Crittercism.initialize(SplashScreenActivity.this, Const.CRITTERCISM_APP_ID);
new Thread(new Runnable() {
#Override
public void run() {
new CouchDB();
}
}).start();
// new UsersManagement();
String language = SampleApp.getPreferences().getGuiLanguage();
if (!language.equals("")) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
if (SampleApp.hasNetworkConnection()) {
if (checkIfUserSignIn()) {
boolean isLinked = false;
mSavedEmail = SampleApp.getPreferences().getUserEmail();
mSavedPassword = SampleApp.getPreferences().getUserPassword();
if (mSavedPassword.equals("")) {
isLinked = true;
mSavedPassword = SampleApp.getPreferences().getUserLinkedPassword();
}
mUser = new User();
CouchDB.authAsync(mSavedEmail, mSavedPassword, isLinked, new AuthListener(), SplashScreenActivity.this, false);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreenActivity.this,
SignInActivity.class));
//finish();
}
}, 2000);
}
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this,
SignInActivity.class);
intent.putExtra(Const.SIGN_IN, true);
SplashScreenActivity.this.startActivity(intent);
Log.v("sample", "SplashScreenActivity starts SignInActivity");
Toast.makeText(SplashScreenActivity.this,
getString(R.string.no_internet_connection),
Toast.LENGTH_LONG).show();
}
}, 2000);
}
}
catch (Exception e){
}
}
#Override
protected void onResume() {
super.onResume();
overridePendingTransition(0, 0);
}
private boolean checkIfUserSignIn() {
boolean isSessionSaved = false;
Preferences prefs = LasteekApp.getPreferences();
if (prefs.getUserEmail() == null
|| (prefs.getUserPassword() == null && prefs.getUserLinkedPassword() == null)) {
isSessionSaved = false;
} else if (prefs.getUserEmail().equals("")
&& (prefs.getUserPassword() != null && prefs.getUserPassword().equals(""))) {
isSessionSaved = false;
}
else if (prefs.getUserEmail().equals("")
&& (prefs.getUserLinkedPassword() != null && prefs.getUserLinkedPassword().equals(""))) {
isSessionSaved = false;
}
else {
isSessionSaved = true;
}
return isSessionSaved;
}
private void signIn(User u) {
UsersManagement.setLoginUser(u);
UsersManagement.setToUser(u);
UsersManagement.setToGroup(null);
Log.d("User", "GetEmail "+u.getEmail());
boolean openPushNotification = getIntent().getBooleanExtra(
Const.PUSH_INTENT, false);
Intent intent = new Intent(SplashScreenActivity.this,
MyProfileActivity.class);
if (openPushNotification) {
intent = getIntent();
intent.setClass(SplashScreenActivity.this,
MyProfileActivity.class);
}
//parse URI hookup://user/[ime korisnika] and hookup://group/[ime grupe]
Uri userUri = getIntent().getData();
//If opened from link
if (userUri != null) {
String scheme = userUri.getScheme(); // "hookup"
String host = userUri.getHost(); // "user" or "group"
if (host.equals("user")) {
List<String> params = userUri.getPathSegments();
String userName = params.get(0); // "ime korisnika"
intent.putExtra(Const.USER_URI_INTENT, true);
intent.putExtra(Const.USER_URI_NAME, userName);
} else if (host.equals("group")) {
List<String> params = userUri.getPathSegments();
String groupName = params.get(0); // "ime grupe"
intent.putExtra(Const.GROUP_URI_INTENT, true);
intent.putExtra(Const.GROUP_URI_NAME, groupName);
}
}
intent.putExtra(Const.SIGN_IN, true);
try{
if(u.getName().toString().equals("")||u.getName().toString()==null){
Log.v("lasteek", "SplashScreenActivity starts EditProfileActivity 1");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getTitlePosition().toString().equals("")||u.getTitlePosition().toString()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 2");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getFunction()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 3");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getIndustry()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 4");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else {
Log.v("sample", "SplashScreenActivity starts MyProfileActivity");
SplashScreenActivity.this.startActivity(intent);
}
} catch (Exception e){
Log.e("Exception",e.toString());
}
//finish();
}
private void checkPassProtect (User user) {
if (sample.getPreferences().getPasscodeProtect())
{
Intent passcode = new Intent(SplashScreenActivity.this,
PasscodeActivity.class);
passcode.putExtra("protect", true);
SplashScreenActivity.this.startActivityForResult(passcode, 0);
}
else
{
signIn(user);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
signIn(mUser);
}
else {
startActivity(new Intent(SplashScreenActivity.this,
SignInActivity.class));
//finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
private boolean authentificationOk(User user) {
boolean authentificationOk = false;
if (user.getEmail() != null && !user.getEmail().equals("")) {
if (user.getEmail().equals(mSavedEmail)) {
authentificationOk = true;
}
}
return authentificationOk;
}
private class AuthListener implements ResultListener<String>
{
#Override
public void onResultsSucceded(String result) {
boolean tokenOk = result.equals(Const.LOGIN_SUCCESS);
mUser = UsersManagement.getLoginUser();
if (tokenOk && mUser!=null) {
if (authentificationOk(mUser)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
checkPassProtect(mUser);
}
}, 2000);
}
} else {
SideBarActivity.appLogout(false, false, true, false);
}
}
#Override
public void onResultsFail() {
SideBarActivity.appLogout(false, false, false, true);
}
}
public void onStart() {
super.onStart();
try {
if (SharedData.runningActivities == 0) {
// app enters foreground
}
SharedData.runningActivities++;
Log.v("sample.activitymonitor", "SplashScreenActivity enters foreground");
Log.v("sample.activitymonitor", "runningActivities=" + SharedData.runningActivities);
}
catch (Exception e){
}
}
public void onStop() {
super.onStop();
SharedData.runningActivities--;
if (SharedData.runningActivities == 0) {
// app goes to background
}
Log.v("sample.activitymonitor", "SplashScreenActivity enters background");
Log.v("sample.activitymonitor", "runningActivities=" + SharedData.runningActivities);
}
}

Getting incoming calls for an hour only using Twilio

I have implemented Twilio in my android app for outgoing and incoming calls. But I'm facing an issue while getting incoming call with the background service. The issue is that I get calls in first 30-40 mins only. After sometime phone stops getting incoming calls. I tried so much. Please respond me soon. I'm sharing code with you too.
I get token from a background service which generates token after a time period.
IncomingCallService.java
public class IncomingCallService extends Service implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static Handler handler, handler_login;
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
Ringtone r;
Uri notification;
public static final String LOGIN_DETAILS = "XXXXXXXX";
AudioManager am;
Intent intent;
public static String DEFAULT_CLIENT_NAME = "developer";
static String Twilio_id = "",
INCOMING_AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT
+ MenuItems.Twilio_id;
Runnable newrun;
Activity context;
Context ctx;
static String op_id = "";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
handler_login = new Handler();
handler_login.postDelayed(new Runnable() {
#Override
public void run() {
Login();
handler_login.postDelayed(this, 20000);
}
}, 1000);
}
public void Login() {
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, true, true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.intent = intent;
// I know getIntent always return NULL in service
if (intent != null) {
op_id = intent.getStringExtra("operator_id");
onCallHandler();
}
return START_STICKY;
}
public void onCallHandler() {
handler = new Handler();
newrun = new Runnable() {
#Override
public void run() {
handler.removeCallbacks(newrun);
new IncomingTokenTask().execute();
if (phone.handleIncomingIntent(intent)) {
}
handler.postDelayed(this, 2000000);
}
};
handler.postDelayed(newrun, 8000000);
}
class IncomingTokenTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
}
}
The BasicPhone class of twilio
public class IncomingPhone implements DeviceListener, ConnectionListener {
private static final String TAG = "IncomingPhone";
static String decodedString = "";
static String capabilityToken = "";
// TODO: change this to point to the script on your public server
private static final String AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT+MenuItems.Twilio_id;
public interface LoginListener {
public void onLoginStarted();
public void onLoginFinished();
public void onLoginError(Exception error);
}
public interface BasicConnectionListener {
public void onIncomingConnectionDisconnected();
public void onConnectionConnecting();
public void onConnectionConnected();
public void onConnectionFailedConnecting(Exception error);
public void onConnectionDisconnecting();
public void onConnectionDisconnected();
public void onConnectionFailed(Exception error);
}
public interface BasicDeviceListener {
public void onDeviceStartedListening();
public void onDeviceStoppedListening(Exception error);
}
private static IncomingPhone instance;
public static final IncomingPhone getInstance(Context context) {
if (instance == null)
instance = new IncomingPhone(context);
return instance;
}
private final Context context;
private LoginListener loginListener;
private BasicConnectionListener basicConnectionListener;
private BasicDeviceListener basicDeviceListener;
private static boolean twilioSdkInited;
private static boolean twilioSdkInitInProgress;
private boolean queuedConnect;
private Device device;
private Connection pendingIncomingConnection;
private Connection connection;
private boolean speakerEnabled;
private String lastClientName;
private boolean lastAllowOutgoing;
private boolean lastAllowIncoming;
private IncomingPhone(Context context) {
this.context = context;
}
public void setListeners(LoginListener loginListener,
BasicConnectionListener basicConnectionListener,
BasicDeviceListener basicDeviceListener) {
this.loginListener = loginListener;
this.basicConnectionListener = basicConnectionListener;
this.basicDeviceListener = basicDeviceListener;
}
private void obtainCapabilityToken(String clientName,
boolean allowOutgoing, boolean allowIncoming) {
StringBuilder url = new StringBuilder();
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient httpclient = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory
.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(
httpclient.getParams(), registry);
#SuppressWarnings("unused")
DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
httpclient.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
url.append(AUTH_PHP_SCRIPT);
// This runs asynchronously!
new GetAuthTokenAsyncTask().execute(url.toString());
}
private boolean isCapabilityTokenValid() {
if (device == null || device.getCapabilities() == null)
return false;
long expTime = (Long) device.getCapabilities().get(
Capability.EXPIRATION);
return expTime - System.currentTimeMillis() / 1000 > 0;
}
//
private void updateAudioRoute() {
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(speakerEnabled);
}
public void login(final String clientName, final boolean allowOutgoing,
final boolean allowIncoming) {
if (loginListener != null)
loginListener.onLoginStarted();
this.lastClientName = clientName;
this.lastAllowOutgoing = allowOutgoing;
this.lastAllowIncoming = allowIncoming;
if (!twilioSdkInited) {
if (twilioSdkInitInProgress)
return;
twilioSdkInitInProgress = true;
Twilio.setLogLevel(Log.DEBUG);
Twilio.initialize(context, new Twilio.InitListener() {
#Override
public void onInitialized() {
twilioSdkInited = true;
twilioSdkInitInProgress = false;
obtainCapabilityToken(clientName, allowOutgoing,
allowIncoming);
}
#Override
public void onError(Exception error) {
twilioSdkInitInProgress = false;
if (loginListener != null)
loginListener.onLoginError(error);
}
});
} else {
obtainCapabilityToken(clientName, allowOutgoing, allowIncoming);
}
}
private void reallyLogin(final String capabilityToken) {
try {
if (device == null) {
device = Twilio.createDevice(capabilityToken, this);
Intent intent = new Intent(context, IncomingPhoneActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
device.setIncomingIntent(pendingIntent);
} else
device.updateCapabilityToken(capabilityToken);
if (loginListener != null)
loginListener.onLoginFinished();
if (queuedConnect) {
// If someone called connect() before we finished initializing
// the SDK, let's take care of that here.
connect(null);
queuedConnect = false;
}
} catch (Exception e) {
if (device != null)
device.release();
device = null;
if (loginListener != null)
loginListener.onLoginError(e);
}
}
public void setSpeakerEnabled(boolean speakerEnabled) {
if (speakerEnabled != this.speakerEnabled) {
this.speakerEnabled = speakerEnabled;
updateAudioRoute();
}
}
public void connect(Map<String, String> inParams) {
if (twilioSdkInitInProgress) {
// If someone calls connect() before the SDK is initialized, we'll
// remember
// that fact and try to connect later.
queuedConnect = true;
return;
}
if (!isCapabilityTokenValid())
login(lastClientName, lastAllowOutgoing, lastAllowIncoming);
if (device == null)
return;
if (canMakeOutgoing()) {
disconnect();
connection = device.connect(inParams, this);
if (connection == null && basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
"Couldn't create new connection"));
}
}
public void disconnect() {
IncomingPhoneActivity.incomingAlert = null;
if (connection != null) {
connection.disconnect(); // will null out in onDisconnected()
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnecting();
}
}
public void acceptConnection() {
if (pendingIncomingConnection != null) {
if (connection != null)
disconnect();
pendingIncomingConnection.accept();
connection = pendingIncomingConnection;
pendingIncomingConnection = null;
}
}
public void connecta(String phoneNumber) {
Toast.makeText(context, "Calling...", Toast.LENGTH_SHORT).show();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("group_id", "11");
// String capabilityToken;
try {
device = Twilio
.createDevice(decodedString, this /* DeviceListener */);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
device.disconnectAll();
} catch (Exception e) {
e.printStackTrace();
}
connection = device.connect(parameters, this);
if (connection == null) {
Log.w(TAG, "Failed to create new connection");
}
}
public void ignoreIncomingConnection() {
if (pendingIncomingConnection != null) {
pendingIncomingConnection.ignore();
}
}
public boolean isConnected() {
return connection != null
&& connection.getState() == Connection.State.CONNECTED;
}
public Connection.State getConnectionState() {
return connection != null ? connection.getState()
: Connection.State.DISCONNECTED;
}
public boolean hasPendingConnection() {
return pendingIncomingConnection != null;
}
public boolean handleIncomingIntent(Intent intent) {
Device inDevice = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection inConnection = intent
.getParcelableExtra(Device.EXTRA_CONNECTION);
if (inDevice == null && inConnection == null)
return false;
intent.removeExtra(Device.EXTRA_DEVICE);
intent.removeExtra(Device.EXTRA_CONNECTION);
if (pendingIncomingConnection != null) {
Log.i(TAG, "A pending connection already exists");
inConnection.ignore();
return false;
}
pendingIncomingConnection = inConnection;
pendingIncomingConnection.setConnectionListener(this);
return true;
}
public boolean canMakeOutgoing() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.OUTGOING)
&& (Boolean) caps.get(Capability.OUTGOING);
}
public boolean canAcceptIncoming() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.INCOMING)
&& (Boolean) caps.get(Capability.INCOMING);
}
public void setCallMuted(boolean isMuted) {
if (connection != null) {
connection.setMuted(isMuted);
}
}
#Override
/* DeviceListener */
public void onStartListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStartedListening();
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(null);
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice, int inErrorCode,
String inErrorMessage) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(new Exception(
inErrorMessage));
}
#Override
/* DeviceListener */
public boolean receivePresenceEvents(Device inDevice) {
return false;
}
#Override
/* DeviceListener */
public void onPresenceChanged(Device inDevice, PresenceEvent inPresenceEvent) {
}
#Override
/* ConnectionListener */
public void onConnecting(Connection inConnection) {
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnecting();
}
#Override
/* ConnectionListener */
public void onConnected(Connection inConnection) {
updateAudioRoute();
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnected();
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnected();
} else if (inConnection == pendingIncomingConnection) {
pendingIncomingConnection = null;
if (basicConnectionListener != null)
basicConnectionListener.onIncomingConnectionDisconnected();
}
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection, int inErrorCode,
String inErrorMessage) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
inErrorMessage));
}
}
private class GetAuthTokenAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
IncomingPhone.this.reallyLogin(result);
}
#Override
protected String doInBackground(String... params) {
try {
capabilityToken = HttpHelper.httpGet(params[0]);
decodedString = capabilityToken.replace("\"", "");
} catch (Exception e) {
e.printStackTrace();
}
return decodedString;
}
}
}
And the activity which opens after getting incoming call via Service class.
public class IncomingPhoneActivity extends Activity implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static final Handler handler = new Handler();
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
private LinearLayout disconnect_btn;
private LinearLayout mainButton;
private ToggleButton speakerButton;
private ToggleButton muteButton;
private EditText logTextBox;
static AlertDialog incomingAlert;
private EditText outgoingTextBox;
private EditText clientNameTextBox;
private Button capabilitesButton;
private CheckBox incomingCheckBox, outgoingCheckBox;
Button call_btn, dis_call_btn, updateButton;
public static String AUTH_PHP_SCRIPT, rating1, rating2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_screen);
Intent intent = getIntent();
Operator_id = intent.getStringExtra("operator_id");
gps = new GPSTracker(IncomingPhoneActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
} else {
// gps.showSettingsAlert();
latitude = 0.00;
longitude = 0.00;
}
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
AUTH_PHP_SCRIPT = "http://xxxxxxxxxxxxxx/getGenToken?group_id="
+ Operator_id + "&twilio_id=" + Twilio_id + "&latitude="
+ latitude + "&longitude=" + longitude;
disconnect_btn = (LinearLayout) findViewById(R.id.d_call);
mainButton = (LinearLayout) findViewById(R.id.call);
call_btn = (Button) findViewById(R.id.call_btn);
dis_call_btn = (Button) findViewById(R.id.d_call_btn);
mainButton.setOnClickListener(this);
call_btn.setOnClickListener(this);
dis_call_btn.setOnClickListener(this);
disconnect_btn.setOnClickListener(this);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
speakerButton = (ToggleButton) findViewById(R.id.speaker_btn);
speakerButton.setOnCheckedChangeListener(this);
muteButton = (ToggleButton) findViewById(R.id.mute_btn);
muteButton.setOnCheckedChangeListener(this);
logTextBox = (EditText) findViewById(R.id.log_text_box);
outgoingTextBox = (EditText) findViewById(R.id.outgoing_client);
clientNameTextBox = (EditText) findViewById(R.id.client_name);
clientNameTextBox.setText(DEFAULT_CLIENT_NAME);
capabilitesButton = (Button) findViewById(R.id.capabilites_button);
capabilitesButton.setOnClickListener(this);
outgoingCheckBox = (CheckBox) findViewById(R.id.outgoing);
incomingCheckBox = (CheckBox) findViewById(R.id.incoming);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (MenuItems.Speaker == true) {
speakerButton.setVisibility(View.VISIBLE);
} else {
speakerButton.setVisibility(View.INVISIBLE);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, outgoingCheckBox.isChecked(),
incomingCheckBox.isChecked());
}
private void syncMainButton() {
handler.post(new Runnable() {
public void run() {
if (IncomingPhone.decodedString.length() != 0) {
if (phone.isConnected()) {
switch (phone.getConnectionState()) {
default:
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case DISCONNECTED:
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case CONNECTED:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
case CONNECTING:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
}
} else if (phone.hasPendingConnection()) {
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
} else {
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
}
/*
* else { Toast.makeText(getApplicationContext(),
* "TRY AGAIN!", Toast.LENGTH_SHORT).show(); }
*/
}
}
});
}
public void onBackPressed() {
phone.disconnect();
incomingAlert = null;
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
in.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(in);
finish();
}
class TokenTask extends AsyncTask<Void, Void, Void> {
String message;
JSONObject jsonResponse;
int crash_app;
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(AUTH_PHP_SCRIPT);
try {
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
IncomingPhone.decodedString = IncomingPhone.capabilityToken
.replace("\"", "");
}
}
} catch (Exception e) {
crash_app = 5;
message = "Something went wrong. Please try again later.";
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (status.equals("success")) {
final Handler handler12 = new Handler();
handler12.postDelayed(new Runnable() {
public void run() {
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton
.setBackgroundResource(R.drawable.light_green_connect);
}
}, 3000);
}
if (status.equals("failure")) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
// mainButton.setBackgroundColor(Color.parseColor("#4ca64c"));
mainButton.setBackgroundResource(R.drawable.dark_green_connect);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
}
}
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
if (phone.handleIncomingIntent(getIntent())) {
showIncomingAlert();
addStatusMessage(R.string.got_incoming);
if (Utils.isNetworkAvailable(IncomingPhoneActivity.this)) {
syncMainButton();
} else {
Toast.makeText(IncomingPhoneActivity.this,
"No internet connection!!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (phone != null) {
phone.setListeners(null, null, null);
phone = null;
}
}
#Override
public void onClick(View view) {
if ((view.getId() == R.id.d_call) || (view.getId() == R.id.d_call_btn)) {
phone.disconnect();
incomingAlert = null;
phone.setSpeakerEnabled(false);
phone.setCallMuted(false);
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
startActivity(in);
finish();
}
if ((view.getId() == R.id.call) || (view.getId() == R.id.call_btn)) {
} else if (view.getId() == R.id.capabilites_button) {
phone.login(clientNameTextBox.getText().toString(),
outgoingCheckBox.isChecked(), incomingCheckBox.isChecked());
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (group.getId() == R.id.input_select) {
if (checkedId == R.id.input_number) {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_PHONE);
outgoingTextBox.setHint(R.string.outgoing_number);
} else {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_TEXT);
outgoingTextBox.setHint(R.string.outgoing_client);
}
outgoingTextBox.setText("");
}
}
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (button.getId() == R.id.speaker_btn) {
phone.setSpeakerEnabled(isChecked);
} else if (button.getId() == R.id.mute_btn) {
phone.setCallMuted(isChecked);
}
}
private void addStatusMessage(final String message) {
handler.post(new Runnable() {
#Override
public void run() {
logTextBox.append('-' + message + '\n');
}
});
}
private void addStatusMessage(int stringId) {
addStatusMessage(getString(stringId));
}
private void showIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert == null) {
notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.play();
break;
case AudioManager.RINGER_MODE_VIBRATE:
long pattern[] = { 0, 500, 200, 300, 500 };
vibrator.vibrate(pattern, 0);
break;
case AudioManager.RINGER_MODE_NORMAL:
r.play();
break;
}
incomingAlert = new AlertDialog.Builder(
IncomingPhoneActivity.this)
.setTitle(R.string.incoming_call)
.setCancelable(false)
.setMessage(R.string.incoming_call_message)
.setPositiveButton(R.string.answer,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.acceptConnection();
disconnect_btn
.setVisibility(View.VISIBLE);
mainButton.setVisibility(View.GONE);
incomingAlert = null;
}
})
.setNegativeButton(R.string.ignore,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.ignoreIncomingConnection();
incomingAlert = null;
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(
DialogInterface dialog) {
phone.ignoreIncomingConnection();
}
}).create();
incomingAlert.show();
}
}
});
}
private void hideIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert != null) {
incomingAlert.dismiss();
incomingAlert = null;
}
}
});
}
#Override
public void onLoginStarted() {
addStatusMessage(R.string.logging_in);
}
#Override
public void onLoginFinished() {
addStatusMessage(phone.canMakeOutgoing() ? R.string.outgoing_ok
: R.string.no_outgoing_capability);
addStatusMessage(phone.canAcceptIncoming() ? R.string.incoming_ok
: R.string.no_incoming_capability);
syncMainButton();
}
#Override
public void onLoginError(Exception error) {
if (error != null)
addStatusMessage(String.format(getString(R.string.login_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.login_error_unknown);
syncMainButton();
}
#Override
public void onIncomingConnectionDisconnected() {
hideIncomingAlert();
addStatusMessage(R.string.incoming_disconnected);
syncMainButton();
}
#Override
public void onConnectionConnecting() {
addStatusMessage(R.string.attempting_to_connect);
syncMainButton();
}
#Override
public void onConnectionConnected() {
addStatusMessage(R.string.connected);
syncMainButton();
}
#Override
public void onConnectionFailedConnecting(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.couldnt_establish_outgoing_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.couldnt_establish_outgoing);
}
#Override
public void onConnectionDisconnecting() {
addStatusMessage(R.string.disconnect_attempt);
syncMainButton();
}
#Override
public void onConnectionDisconnected() {
addStatusMessage(R.string.disconnected);
syncMainButton();
}
#Override
public void onConnectionFailed(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.connection_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.connection_error);
syncMainButton();
}
#Override
public void onDeviceStartedListening() {
addStatusMessage(R.string.device_listening);
}
#Override
public void onDeviceStoppedListening(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.device_listening_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.device_not_listening);
}
}

Android contact picker returning nulll (resultCode == 0)

I'm new to Android and I'm trying to attach a contact picker to a form. This "contact picker code" works well when I test it with other forms but with this form, the resultCode = RESULT_CANCELED. I have checked other examples, but it doesn't work with this from but still works with other forms.
public class EmergencyButtonActivity extends Activity {
static private MoreEditText mPhonesMoreEditText = null;
private static final String DEBUG_TAG = "EmergencyButtonActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, new StackMailer());
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first phone
if (cursor.moveToFirst()) {
phone = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtPhoneNo.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Phone : "+ phone, Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
private void popup(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyButtonActivity.this);
builder.setMessage(text)
.setTitle(title)
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void initUI() {
setContentView(R.layout.main);
this.restoreTextEdits();
ImageButton btnEmergency = (ImageButton) findViewById(R.id.btnEmergency);
btnEmergency.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// try sending the message:
EmergencyButtonActivity.this.redButtonPressed();
}
});
ImageButton btnHelp = (ImageButton) findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupHelp();
}
});
}
public void popupHelp() {
final String messages [] = {
"Welcome To App xxxxxx",
"XXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXX."
};
// inverted order - They all popup and you hit "ok" to see the next one.
popup("3/3", messages[2]);
popup("2/3", messages[1]);
popup("1/3", messages[0]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
initUI();
}
private class StackMailer implements ExceptionHandler.StackTraceHandler {
public void onStackTrace(String stackTrace) {
EmailSender.send("a#zzz.com", "Error", "ButtonError\n" + stackTrace);
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
initUI();
//IntroActivity.openOnceAfterInstallation(this);
helpOnceAfterInstallation();
}
#Override
protected void onPause() {
super.onPause();
this.saveTextEdits();
}
#Override
protected void onStop() {
super.onStop();
}
public void helpOnceAfterInstallation() {
// runs only on the first time opening
final String wasOpenedName = "wasOpened";
final String introDbName = "introActivityState";
SharedPreferences settings = this.getSharedPreferences(introDbName, Context.MODE_PRIVATE);
boolean wasOpened = settings.getBoolean(wasOpenedName, false);
if (wasOpened) {
return;
}
// mark that it was opened once
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(wasOpenedName, true);
editor.commit();
popupHelp();
}
private class EditTextRow {
LinearLayout mLinlay;
EditText mEditText;
ImageButton mRemoveBtn;
public EditTextRow(String text, EditText example) {
mEditText = new EditText(EmergencyButtonActivity.this);
mEditText.setLayoutParams(example.getLayoutParams());
mEditText.setText(text);
mEditText.setInputType(example.getInputType());
mRemoveBtn = new ImageButton(EmergencyButtonActivity.this);
mRemoveBtn.setBackgroundResource(R.drawable.grey_x);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mRemoveBtn.setLayoutParams(params);
mLinlay = new LinearLayout(EmergencyButtonActivity.this);
mLinlay.setOrientation(LinearLayout.HORIZONTAL);
mLinlay.addView(mEditText);
mLinlay.addView(mRemoveBtn);
}
}
private class MoreEditText {
private LinearLayout mContainer;
private ArrayList<EditText> mEditTextList = null;
public MoreEditText(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from scratch, this should only happen onCreate
mContainer = container;
mEditTextList = new ArrayList<EditText>();
EditText edit;
edit = textWidget;
if(! stringsList.isEmpty()) {
edit.setText(stringsList.get(0));
}
mEditTextList.add(edit);
for (int i = 1; i < stringsList.size(); i++) {
addRow(stringsList.get(i));
}
}
public void restore(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from older existing rows, this can happen on
// changes of orientation, onResume, etc
mContainer = container;
for(int i = 0; i < mEditTextList.size(); i++) {
EditText edit;
if (i == 0) {
edit = textWidget;
mEditTextList.set(0, edit);
if (stringsList.size() > 0) {
edit.setText(stringsList.get(0));
}
} else {
edit = mEditTextList.get(i);
View viewRow = (LinearLayout) edit.getParent();
((LinearLayout)viewRow.getParent()).removeView(viewRow);
mContainer.addView(viewRow);
}
}
}
#SuppressWarnings("unused")
public EditText getDefaultTextEdit(LinearLayout container) {
// TODO: turn this into something like "getEditTextChild" rather than counting on the index "0"
return (EditText) ((LinearLayout)container.getChildAt(0)).getChildAt(0);
}
public void removeRow(EditText editText) {
mContainer.removeView((View) editText.getParent());
mEditTextList.remove(editText);
}
public void addRow(String text) {
final EditTextRow editRow = new EditTextRow(text, mEditTextList.get(0));
editRow.mRemoveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MoreEditText.this.removeRow(editRow.mEditText);
}
});
mContainer.addView(editRow.mLinlay);
mEditTextList.add(editRow.mEditText);
}
public List<String> GetTexts() {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < mEditTextList.size(); i ++) {
texts.add(mEditTextList.get(i).getText().toString());
}
return texts;
}
}
private void addPhonesEmailsUI(List<String> phones, List<String> emails) {
LinearLayout phoneNoLin = (LinearLayout)findViewById(R.id.linPhoneNo);
EditText txtPhoneNo = (EditText)findViewById(R.id.txtPhoneNo);
// NOTE: we don't always create from scratch so that empty textboxes
// aren't erased on changes of orientation.
if (mPhonesMoreEditText == null) {
mPhonesMoreEditText = new MoreEditText(phoneNoLin, txtPhoneNo, phones);
} else {
mPhonesMoreEditText.restore(phoneNoLin, txtPhoneNo, phones);
}
}
public void restoreTextEdits() {
EmergencyData emergencyData = new EmergencyData(this);
addPhonesEmailsUI(emergencyData.getPhones(), emergencyData.getEmails());
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(emergencyData.getMessage());
}
#SuppressWarnings("unused")
public void saveTextEdits() {
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
EmergencyData emergencyData = new EmergencyData(this);
emergencyData.setPhones(mPhonesMoreEditText.GetTexts());
emergencyData.setMessage(txtMessage.getText().toString());
}
public void redButtonPressed() {
this.saveTextEdits();
EmergencyData emergency = new EmergencyData(this);
if ((emergency.getPhones().size() == 0) && (emergency.getEmails().size() == 0)) {
Toast.makeText(this, "Enter a phone number or email.",
Toast.LENGTH_SHORT).show();
return;
}
EmergencyActivity.armEmergencyActivity(this);
Intent myIntent = new Intent(EmergencyButtonActivity.this, EmergencyActivity.class);
EmergencyButtonActivity.this.startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ebutton_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(Intent.ACTION_VIEW);
switch (item.getItemId()) {
case R.id.project_page:
i.setData(Uri.parse("http://#/"));
startActivity(i);
break;
case R.id.credits:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.credits_dialog);
dialog.setTitle("Credits");
TextView text = (TextView) dialog.findViewById(R.id.textView);
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.credits);
byte[] b = new byte[in_s.available()];
in_s.read(b);
text.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
text.setText("Error: can't show credits.");
}
dialog.show();
break;
}
return true;
}
}
Finally found a solution, the problem was with the android:launchMode in the manifest.

Categories

Resources