How to pass value from fragment button to another activity - android

So I have a map fragment for my application for Google maps. I want to pass the value from the marker (lat/lng) to the String holding the location and then I want to pass that value to the TextField in another application. That textfield will then be stored to the SQLite database that I have built.
My current map activity is as follows
public class MapActivity extends FragmentActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
Serializable {
GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final int EDITOR_REQUEST_CODE = 1001;
public static final String LOCAT_KEY = "location";
private GoogleApiClient mLocationClient;
private Marker marker;
Bundle bundle;
String value;
private static final double
CITY_LAT = 53.3478,
CITY_LNG = -6.2597;
Circle shape;
public String lat;
public String lng;
public String location;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if enabled and if not send user to the GSP settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Getting reference to Button
Button btnDraw = (Button) findViewById(R.id.btn_draw);
if (servicesOK()) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (initMap()) {
gotoLocation(CITY_LAT, CITY_LNG, 12);
mMap.setMyLocationEnabled(true);
mLocationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationClient.connect();
} else {
Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
}
} else {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
bundle = new Bundle();
btnDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String location = lat + "," + lng;
// Checks, whether location is captured
((TextView) findViewById(R.id.editLocation)).setText(location);
}
});
}
Note I have only added code down to the actual button that is activated.
My code for the button that is clicked in my XML file is as follows:
<Button
android:id="#+id/btn_draw"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/save_location_btn"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="mapLocationClick"/>
And finally my code for the editor class is as follows:
public class EditorActivity extends AppCompatActivity {
public static final String KEY_ID = "id";
public static final String KEY_TIME = "time" ;
public static final String KEY_LOCAT = "location";
private String action;
private EditText editor;
private EditText editorDate;
private EditText editorTime;
private EditText editorLocation;
private ImageButton dateButton;
private ImageButton timeButton;
private ImageButton locationButton;
private String noteFilter;
private String oldText;
private String oldDate;
private String oldTime;
private String oldLocation;
String value = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
editor = (EditText) findViewById(R.id.editText);
editorDate = (EditText) findViewById(R.id.editDate);
editorTime = (EditText) findViewById(R.id.editTime);
editorLocation = (EditText) findViewById(R.id.editLocation);
dateButton = (ImageButton) findViewById(R.id.imgButtonCal);
timeButton = (ImageButton) findViewById(R.id.imgButtonClock);
locationButton = (ImageButton) findViewById(R.id.imgButtonMap);
//enableEdit = (FloatingActionButton) findViewById(R.id.fabEdit);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
action = Intent.ACTION_INSERT;
setTitle(getString(R.string.new_note));
}
else {
long id = extras.getLong(KEY_ID);
if (id == 0){
action = Intent.ACTION_INSERT;
setTitle(getString(R.string.new_note));
long time = intent.getLongExtra(KEY_TIME, 0);
if (time != 0) {
Date d = new Date(time);
String dateString= DateFormat.format("yyyy-MM-dd", `d).toString();`
editorDate.setText(dateString);
}
}
else {
action = Intent.ACTION_EDIT;
setTitle(getString(R.string.edit_note));
Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id);
noteFilter = DBOpenHelper.NOTE_ID + "=" + uri.getLastPathSegment();
Cursor cursor;
cursor = getContentResolver().query(uri,
DBOpenHelper.ALL_COLUMNS, noteFilter, null, null);
cursor.moveToFirst();
oldText = cursor.getString(cursor.getColumnIndex(NOTE_TEXT));
oldDate = cursor.getString(cursor.getColumnIndex(NOTE_DATE));
oldTime = cursor.getString(cursor.getColumnIndex(NOTE_TIME));
oldLocation = cursor.getString(cursor.getColumnIndex(NOTE_LOCATION));
editor.setText(oldText);
editor.setEnabled(false);
editorDate.setText(oldDate);
editorDate.setEnabled(false);
dateButton.setEnabled(false);
editorTime.setText(oldTime);
editorTime.setEnabled(false);
timeButton.setEnabled(false);
editorLocation.setText(oldLocation);
editorLocation.setEnabled(false);
locationButton.setEnabled(false);
//saveButton.setEnabled(false);
editor.requestFocus();
//enableEdit.setEnabled(true);
//enableSave.setEnabled(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (action.equals(Intent.ACTION_EDIT)){
getMenuInflater().inflate(R.menu.menu_editor, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case android.R.id.home:
finishEditing();
break;
case R.id.action_delete:
deleteNote();
break;
case R.id.action_edit:
enableFields();
break;
}
return true;
}
private void enableFields(){
if(NotesProvider.CONTENT_URI != null) {
editor.setEnabled(true);
editorDate.setEnabled(true);
dateButton.setEnabled(true);
editorTime.setEnabled(true);
timeButton.setEnabled(true);
editorLocation.setEnabled(true);
locationButton.setEnabled(true);
}
}
private void deleteNote() {
getContentResolver().delete(NotesProvider.CONTENT_URI,
noteFilter,null);
Toast.makeText(this, R.string.note_deleted,
Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
private void finishEditing(){
String newText = editor.getText().toString().trim();
String newDate = editorDate.getText().toString().trim();
String newTime = editorTime.getText().toString().trim();
String newLocation = editorLocation.getText().toString().trim();
switch (action) {
case Intent.ACTION_INSERT:
if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0){
setResult(RESULT_CANCELED);
} else{
insertNote(newText, newDate, newTime, newLocation);
}
break;
case Intent.ACTION_EDIT:
if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0 && newLocation.length() == 0){
deleteNote();
}else if (oldText.equals(newText) && oldDate.equals(newDate) && oldTime.equals(newTime) && oldLocation.equals(newLocation)){
setResult(RESULT_CANCELED);
}else {
updateNote(newText, newDate, newTime, newLocation);
}
}
finish();
}
private void updateNote(String noteText, String noteDate, String noteTime, String noteLocation) {
ContentValues values = new ContentValues();
values.put(NOTE_TEXT, noteText);
values.put(NOTE_DATE, noteDate);
values.put(NOTE_TIME, noteTime);
values.put(NOTE_LOCATION, noteLocation);
getContentResolver().update(NotesProvider.CONTENT_URI, values, noteFilter, null);
Toast.makeText(this, R.string.note_updated, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
}
private void insertNote(String noteText, String noteDate, String noteTime, String noteLocation) {
ContentValues values = new ContentValues();
values.put(NOTE_TEXT, noteText);
values.put(NOTE_DATE, noteDate);
values.put(NOTE_TIME, noteTime);
values.put(NOTE_LOCATION, noteLocation);
getContentResolver().insert(NotesProvider.CONTENT_URI, values);
setResult(RESULT_OK);
}
#Override
public void onBackPressed() {
finishEditing();
}
public void onSaveNote(View view) { finishEditing();}
public void onButtonClicked(View v){
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void openMapFragment(View v) {
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
Anybody help me so when I click on the button it will take the value from the location and save it in the previous class that was loaded up before.

I found the answer. I created the following in my map class
btnDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Checks, whether location is captured
Intent intent = MapActivity.this.getIntent();
intent.putExtra(LATITUDE_EXTRA, lat);
intent.putExtra(LONGITUDE_EXTRA, lng);
MapActivity.this.setResult(RESULT_OK, intent);
MapActivity.this.finish();
}
});
Then I added it to the Editor class by the following.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAP_REQUEST_CODE && resultCode == RESULT_OK) {
String lat = data.getStringExtra(MapActivity.LATITUDE_EXTRA);
String lng = data.getStringExtra(MapActivity.LONGITUDE_EXTRA);
editorLocation.setText(lat + ", " + lng);
}
else {
Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show();
}
}
Seems I needed to add a new intent and use the onActivityResult.

Related

LocalBroadcastManager sends data more than once

I have a fragment where when a User inputs a link and hits the button, a service is initiated which processes the link and grabs image or videos if there are any on the url...
But my problem is that the same is downloaded more than once like 2 to 3 times..
here is the fragment -
public class FragmentTwo extends Fragment {
FloatingActionButton btn;
EditText et1;
String profilname;
ProgressDialog pd;
private ArrayList<Long> mDownloadIds = new ArrayList<>();
public FragmentTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two,container, false);
getActivity().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(myReceiver, new IntentFilter(Constants.BROADCAST_ACTION));
FloatingActionButton btn = (FloatingActionButton) rootView.findViewById(R.id.button1);
EditText et1 = (EditText) rootView.findViewById(R.id.editText1);
pd = new ProgressDialog(getActivity());
pd.setMessage("Let us Check");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText et1 = (EditText)
getView().findViewById(R.id.editText1);
profilname = et1.getText().toString();
((InputMethodManager) getActivity().getSystemService("input_method")) .hideSoftInputFromWindow(et1.getWindowToken(), 0);
profilname.replace("https://www.instagram.com/","https://instagram.com/");
if (profilname.trim().equals("")){
Toast.makeText(getActivity(), "Link is Blank!", 0)
.show();
}
else if(isNetworkAvailable()){
Toast.makeText(getActivity(), profilname, 0)
.show();
DownloaderService.startActionFoo(getActivity(), profilname);
pd.show();
}
else{
Toast.makeText(getActivity(), "Network Error", 0)
.show();
}
}
});
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ContentValues contentValues = intent.getParcelableExtra(Constants.MEDIA_INFO);
String mediaUrl = contentValues.getAsString(Constants.MEDIA_URL);
String mediaName = contentValues.getAsString(Constants.MEDIA_NAME);
pd.dismiss();
download(mediaUrl, mediaName);
EditText et1 = (EditText)
getView().findViewById(R.id.editText1);
et1.setText("");
}
};
private BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long enqueueId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (mDownloadIds.contains(enqueueId)) {
/* if (mBtnDownload.getVisibility() == View.VISIBLE) {
mBtnDownload.setVisibility(View.GONE);
}*/
getActivity().getLoaderManager().getLoader(0);
}
}
};
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(myReceiver);
getActivity().unregisterReceiver(onComplete);
super.onDestroy();
}
private void download(String url, String fileName) {
File root = Environment.getExternalStorageDirectory();
File myDir = new File(root + "/MCD/");
myDir.mkdirs();
DownloadManager mDownloadManager = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
if (!doesRequestExist(mDownloadManager, url)) {
/* boolean allowedOverMetered = mSettings.getBoolean(PREF_KEY_NETWORK, true);*/
int networkType = NETWORK_WIFI | NETWORK_MOBILE;
/* if (allowedOverMetered) {
networkType = NETWORK_WIFI | NETWORK_MOBILE;
}*/
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(root + "/MCD/", fileName);
request.setAllowedNetworkTypes(networkType);
long id = mDownloadManager.enqueue(request);
mDownloadIds.add(id);
}
}
private boolean doesRequestExist(DownloadManager downloadManager, String url) {
boolean result = false;
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL
| DownloadManager.STATUS_PENDING
| DownloadManager.STATUS_RUNNING);
Cursor cursor = downloadManager.query(query);
while (cursor.moveToNext()) {
int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
String uri = cursor.getString(uriIndex);
if (uri.equals(url)) {
result = true;
break;
}
}
cursor.close();
return result;
}
}
here's the Downloader Service -
public class DownloaderService extends IntentService {
private static final String ACTION_FOO = "com.parrotainment.media.downloader.action.FOO";
private static final String EXTRA_URL = "com.parrotainment.media.downloader.extra.URL";
public DownloaderService() {
super("DownloaderService");
}
public static void startActionFoo(Context context, String url) {
Intent intent = new Intent(context, DownloaderService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_URL, url);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String url = intent.getStringExtra(EXTRA_URL);
handleActionFoo(url);
}
}
}
private void handleActionFoo(String urlStr) {
try {
ContentValues mediaInfo = new ContentValues();
Document doc = Jsoup.connect(urlStr).timeout(5000).get();
Document content = Jsoup.parse(doc.toString());
String videoUrl = content.getElementsByAttributeValue("property","og:video")
.attr("content");
String title = content.getElementsByAttributeValue("property","og:title")
.attr("content").replaceAll("[^a-zA-Z0-9\\u4E00-\\u9FA5\\s]","");
if (!videoUrl.isEmpty()) {
String videoName = title + ".mp4";
mediaInfo.put(Constants.MEDIA_NAME, videoName);
mediaInfo.put(Constants.MEDIA_URL, videoUrl);
} else {
String imgUrl = content.getElementsByAttributeValue("property","og:image").attr("content");
String imgName = title + ".jpg";
mediaInfo.put(Constants.MEDIA_NAME, imgName);
mediaInfo.put(Constants.MEDIA_URL, imgUrl);
}
Intent intent = new Intent(Constants.BROADCAST_ACTION);
intent.putExtra(Constants.MEDIA_INFO, mediaInfo);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
}
}
}
& the Constants -
public final class Constants {
public static final String BROADCAST_ACTION = "com.parrotainment.media.downloader.BROADCAST";
public static final String MEDIA_INFO = "com.parrotainment.media.downloader.MEDIA_INFO";
public static final String MEDIA_NAME = "com.parrotainment.media.downloader.MEDIA_NAME";
public static final String MEDIA_URL = "com.parrotainment.media.downloader.MEDIA_URL";
}
just checking data in your oReceive may help. like this:
if(intent.getAction() != null && intent.getAction().equals("your_constant_item")){
//
}

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.

Google Maps makes the app stop Unfortunately

We are working with an Android Application the first page is Splash screen and the later page is google map . This google map activity makes the app stop unfortunately in some android phones like android version 4.4.2. But in some android phone it is working fine . Is the google map has some restriction with the android API.
When it is run in Android version like 4.4.2 . It is showing this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{salon.com.barber/salon.com.barber.GoogleMapsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2342)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1266)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5421)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:970)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at salon.com.barber.GoogleMapsActivity.populateMap(GoogleMapsActivity.java:287)
at salon.com.barber.GoogleMapsActivity.onCreate(GoogleMapsActivity.java:205)
at android.app.Activity.performCreate(Activity.java:5263)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1099)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
... 11 more
My Google Map Activity is
public class GoogleMapsActivity extends FragmentActivity {
ImageButton imageButton;
NavDrawerListAdapterSalonDetails adapternav;
DrawerLayout dLayout;
List<NavDrawerSalonDetailsItem> menu;
private ProgressDialog pDialog;
ListView dList1;
private GoogleMap mMap;
GPSTracker gps;
boolean isGpsON;
ArrayList<String> arry_salondetails;
String SaloonDetails = "";
String Street = null;
String Zipcode = null;
String HouseNumber = null;
String City = null;
//final ArrayList<String> SalonNames = new ArrayList<String>();
final HashMap SalonData = new HashMap();
double lati,longi;
final ArrayList<String> serviceDataList = new ArrayList<String>();
Boolean isInternetPresent;
JSONObject objectNextClass;
private GoogleMap googleMap;
JSONArray saloonDetails = null;
RelativeLayout selectedLayout;
double latitude, longitude, range;
String tableName = "barber";
Marker selectedMarker;
ImageButton button_bookmark ;
String objectId = "";
public static final String BARBER_MAP_PREFS = "MAP_PREFS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_maps);
selectedLayout = (RelativeLayout) findViewById(R.id.selectedView);
networkCheck cd = new networkCheck(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet(); // true or
// false
Log.i("sfeeee", "wwwwwww111w");
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
String r = prefs.getString("range", null);
if (r == null) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("range", "10");
editor.commit();
}
AndroidLog.appendLog("En:2");
imageButton =(ImageButton) findViewById(R.id.Search_btn);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
Log.i("sfeeee1111111", "wwwwwwww");
Intent i = new Intent(GoogleMapsActivity.this, Search.class);
startActivity(i);
}
});
AndroidLog.appendLog("Ex:2");
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList1 = (ListView) findViewById(R.id.list_slidermenu);
menu = getNavDraweItemList();
adapternav = new NavDrawerListAdapterSalonDetails(this, menu);
LayoutInflater inflater=this.getLayoutInflater();
View header=inflater.inflate(R.layout.footer, null);
dList1.addHeaderView(header);
dList1.setAdapter(adapternav);
ImageButton buttonMenu =((ImageButton) findViewById(R.id.buttonMenu));
dList1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
getListPosition(position);
// TODO Auto-generated method stub
}
});
buttonMenu.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
dLayout.openDrawer(dList1);
}
});
ImageButton button_map=(ImageButton) findViewById(R.id.button_map);
Log.i("111111111111111", "qqqqqqqqqqqqq");
button_map.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
if (isInternetPresent) {
LatLng myCurrentLoc = getCurrentLoaction();
Log.i("mycurrentLoc", myCurrentLoc.toString());
Log.i("2222222222211", "qqqqqqqqqqqqq");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
(myCurrentLoc), 11));
Log.i("3333333333333331", "qqqqqqqqqqqqq");
}
}
});
AndroidLog.appendLog("En:3");
if (isInternetPresent) {
// Calling async task to get json
//new getLocationData().execute();
populateMap();
AndroidLog.appendLog("Ex:3");
Log.i("4444444411111", "qqqqqqqqqqqqq");
} else {
// Internet connection not present
// Ask user to connect to Internet
showAlertDialog(GoogleMapsActivity.this, "No Internet Connection",
"You don't have internet connection.", false);
}
selectedLayout.setVisibility(View.GONE);
Button button = ((Button) selectedLayout
.findViewById(R.id.selec_button_id));
button.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
Intent intent = new Intent(view.getContext(),
Salon_Detail.class);
//intent.putExtra("SalonName", (CharSequence) nameView);
// intent.putExtra("json", objectNextClass.toString());
startActivity(intent);
}
});
}
public void onDestroy() {
super.onDestroy();
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
}
public void populateMap(){
Log.d("searched", "map");
pDialog = new ProgressDialog(GoogleMapsActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
LatLng myCurrentLoc = getCurrentLoaction();
if(!isGpsON)
{
Toast.makeText(getApplicationContext(),"Switch on the location service for more accuracy",
30000).show();
}
Log.i("Latti and Longii", myCurrentLoc.toString());
latitude = myCurrentLoc.latitude;
Log.i("latitude of current Loc", String.valueOf(latitude));
longitude = myCurrentLoc.longitude;
Log.i("longitudeofcurrent Loc",String.valueOf(longitude));
mMap.addCircle(new CircleOptions()
.center(new LatLng(myCurrentLoc.latitude,
myCurrentLoc.longitude)).radius(10000)
.strokeColor(Color.parseColor("#34DDDD")).strokeWidth(6.0f)
.fillColor(Color.parseColor("#93D5E4")));
Log.i("777777777777777", "qqqqqqqqqqqqq");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
(myCurrentLoc), 11));
Log.i("666666666666666666", "qqqqqqqqqqqqq");
Marker TP = mMap.addMarker(new MarkerOptions().position(
myCurrentLoc).title("").icon(BitmapDescriptorFactory.fromResource(R.mipmap.pin_blue)));
//icon(BitmapDescriptorFactory.fromResource(R.drawable.navigate))
TP.showInfoWindow();
Log.i("5555555555555555555555", "qqqqqqqqqqqqq");
TP.setSnippet("currentLocation");
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
range = Double.parseDouble(prefs.getString("range",null));
//range = 100;
new GmapUtil().onGetCustomMarkers(getApplicationContext(), longitude, latitude, range, tableName,
new GmapUtil.CustomMarker() {
#Override
public void onSuccess(String data) {
Log.i("resulttttttt od dataaa", data);
pDialog.hide();
try {
JSONObject jsonObject = new JSONObject(data);
Log.i("jsonObjectttttttttttt", jsonObject.toString());
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
Log.i("jsonObjecttttttt1", jsonObject1.toString());
JSONArray jsonArray = jsonObject1.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
final JSONObject child = jsonArray.getJSONObject(i);
//final String sName = child.getString("SalonName");
//SalonNames.add(child.getString("SalonName"));
//Log.i("salonn namesss", SalonNames.toString());
latitude = child.getDouble("Latitude");
longitude = child.getDouble("Longitude");
LatLng saloonLoc = new LatLng(latitude, longitude);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Marker marker = mMap.addMarker(new MarkerOptions()
.position(saloonLoc).title("TutorialsPoint").icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red)));
marker.setSnippet(child.getString("objectId"));
SalonData.put(child.getString("objectId"), child);
Log.i("8888888888888888", "qqqqqqqqqqqqq");
// googleMap.setOnMarkerClickListener(this);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
SaloonDetails = "";
// Take some action here
String snippet = marker.getSnippet();
objectId = snippet;
if (selectedMarker != null && !("currentLocation".equals(snippet))) {
selectedMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red));
}
selectedMarker = marker;
if (!("currentLocation".equals(snippet)))
marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_blue));
Log.i("TAG", "snippet::::" + snippet);
if ("currentLocation".equals(snippet)) {
selectedLayout.setVisibility(View.GONE);
//button_bookmark.setVisibility(View.GONE);
return false;
} else {
selectedLayout
.setVisibility(View.VISIBLE);
TextView nameView = ((TextView) selectedLayout
.findViewById(R.id.name_txt_id));
TextView addressView = ((TextView) selectedLayout
.findViewById(R.id.address_txt_id));
try {
JSONObject jSalonData = (JSONObject)SalonData.get(snippet);
nameView.setText(jSalonData.getString("SalonName"));
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject jSalonData = (JSONObject)SalonData.get(snippet);
Log.i("jSalonData",jSalonData.toString());
//addressView.append(System.getProperty("line.separator"));
City = jSalonData.optString("City");
SaloonDetails = SaloonDetails + City;
Zipcode = jSalonData.optString("Zipcode");
SaloonDetails = SaloonDetails +" "+ Zipcode;
HouseNumber = jSalonData.optString("HouseNumber");
SaloonDetails = SaloonDetails +" "+ HouseNumber;
Street = jSalonData.optString("Street");
SaloonDetails = SaloonDetails +" "+ Street;
Log.i("SaloonDetails", SaloonDetails);
//addressView.setText(jSalonData.getString("Zipcode"));
//addressView.setText(jSalonData.getString("City"));
addressView.setText(SaloonDetails);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
});
}
} catch (Exception e) {
Log.i("Exception", e.toString());
}
}
#Override
public void onError(String data) {
}
});
}
private LatLng getCurrentLoaction() {
// TODO Auto-generated method stub
Log.i("sfeeee","wwwwwwww");
gps = new GPSTracker(GoogleMapsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
isGpsON=true;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Log.i("Latiiiiiiiiii",latLng.toString());
return latLng;
// \n is for new line
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
isGpsON=false;
LatLng latLng = new LatLng(52.156111,5.387827);
return latLng;
}
}
private List<NavDrawerSalonDetailsItem> getNavDraweItemList() {
String search = "Search";
String Privacypolicy = "Privacy policy";
String termsofconditions = "Terms and Conditions";
String favorite = " Favourites";
String Setting = "Settings";
String[] list = new String[] {search, Privacypolicy,termsofconditions,favorite,Setting};
int[] icons = { R.mipmap.small_search, R.mipmap.small_about_us };
List<NavDrawerSalonDetailsItem> menu = new ArrayList<NavDrawerSalonDetailsItem>();
for (int i = 0; i < list.length; i++) {
menu.add(new NavDrawerSalonDetailsItem(list[i], i));
}
return menu;
}
/**
* Function to display simple Alert Dialog
*
* #param context
* - application context
* #param title
* - alert dialog title
* #param message
* - alert message
* #param status
* - success/failure (used to set icon)
* */
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
public void search(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, Search.class);
startActivity(intent);
}
public void privacyPolicy(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, privacypolicy.class);
startActivity(intent);
}
public void termsAndCondition(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, Terms_and_condition.class);
startActivity(intent);
}
public void favorite(){
Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
startActivity(intent);
}
public void Settings(){
Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
startActivity(intent);
}
public void getListPosition(int position) {
switch (position) {
case 1: {
search();
break;
}
case 2: {
privacyPolicy();
break;
}
case 3: {
termsAndCondition();
break;
}
case 4: {
favorite();
break;
}
case 5: {
Settings();
break;
}
default: {
break;
}
}
}
}
To ensure that you are using a non-null instance of GoogleMap you should implement OnMapReadyCallback. From the documentation https://developers.google.com/android/reference/com/google/android/gms/maps/OnMapReadyCallback
Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non-null instance of GoogleMap.:
So, your GoogleMapsActivity needs to implement OnMapReadyCallback and you have to move the call your populateMap(); method to the onMapReady method:
public class GoogleMapsActivity extends FragmentActivity implements OnMapReadyCallback {
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// Remove populateMap(); and change it for
((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
populateMap();
}
}

Rerouting in Here Map Android SDK

I am using Here Map Android SDK for navigation functionalities. Currently my app can calculate the route and draw it through NavigationManager. But the rerouting function can't work even I have added the RerouteListener to NavigationManager. My code is as following:
public class Navigation extends ActionBarActivity {
private GeoCoordinate destinationGeo;
private GeoCoordinate originGeo;
private static Map mMap = null;
private static MapFragment mMapFragment = null;
private static MapRoute mMapRoute = null;
private static RouteManager mRouteManager = null;
private static PositioningManager mPositoningManager = null;
private static NavigationManager mNavigationManager = null;
private static boolean mPositioningListenerPaused = true;
RouteCalculationTask mRouteCalculationTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
/*
//get destination geo passed from CarParkingActivity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String lat = extras.getString("lat");
String lng = extras.getString("lng");
*/
//destinationGeo = new GeoCoordinate(Double.parseDouble(lat), Double.parseDouble(lng));
destinationGeo = new GeoCoordinate(1.37374, 103.9707);
mMapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.navigation_nokia);
if (mMapFragment == null){
System.out.println("mapfragment null");
}
mMapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(Error error) {
if (error == Error.NONE){
System.out.println("map engine init no error");
mMap = mMapFragment.getMap();
mMapFragment.getView().setVisibility(View.INVISIBLE);
mMap.setZoomLevel(mMap.getMaxZoomLevel());
mMap.setCenter(destinationGeo, Map.Animation.NONE);
//set destination marker on map
Image image = new Image();
try{
image.setImageResource(R.drawable.carpark4);
}
catch (IOException e){
e.printStackTrace();
}
MapMarker mapMarker = new MapMarker(destinationGeo, image);
mMap.addMapObject(mapMarker);
//set navigation marker on map
try{
image.setImageResource(R.drawable.gnavigation);
}catch (IOException e){
e.printStackTrace();
}
mMap.getPositionIndicator().setMarker(image);
mMap.getPositionIndicator().setVisible(true);
//set traffic information
mMap.setTrafficInfoVisible(true);
//set map scheme
mMap.setMapScheme(Map.Scheme.CARNAV_DAY);
mRouteManager = RouteManager.getInstance();
mPositoningManager = PositioningManager.getInstance();
mPositoningManager.addListener(new WeakReference<PositioningManager.OnPositionChangedListener>(mPositioningListener));
// start positioning manager
if (mPositoningManager.start(PositioningManager.LocationMethod.GPS_NETWORK)){
MapEngine.getInstance().onResume();
mPositioningListenerPaused = false;
mRouteCalculationTask = new RouteCalculationTask(RouteOptions.Type.FASTEST);
mRouteCalculationTask.execute("hello");
}
mNavigationManager = NavigationManager.getInstance();
mNavigationManager.setMap(mMap);
//set map update mode when movement
mNavigationManager.setMapUpdateMode(NavigationManager.MapUpdateMode.ROADVIEW);
//set up road view in navigation
NavigationManager.RoadView roadView = mNavigationManager.getRoadView();
roadView.addListener(new WeakReference<NavigationManager.RoadView.Listener>(mNavigationManagerRoadViewListener));
roadView.setOrientation(NavigationManager.RoadView.Orientation.DYNAMIC); //heading is at the top of the screen
//set up route recalculation in navigation
mNavigationManager.addRerouteListener(new WeakReference<NavigationManager.RerouteListener>(mNavigaionRerouteListener));
}else {
System.out.println("ERROR: cannot init MapFragment");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume(){
super.onResume();
if (mPositoningManager != null){
// start positioning manager
if (mPositoningManager.start(PositioningManager.LocationMethod.GPS_NETWORK)){
mPositioningListenerPaused = false;
mRouteCalculationTask = new RouteCalculationTask(RouteOptions.Type.FASTEST);
mRouteCalculationTask.execute("hello");
}
}
}
#Override
public void onPause(){
super.onPause();
//stop positioning manager
mPositoningManager.stop();
mPositioningListenerPaused = true;
MapEngine.getInstance().onPause();
}
//RouteManager
private RouteManager.Listener mRouteMangerListener = new RouteManager.Listener() {
#Override
public void onProgress(int i) {
}
#Override
public void onCalculateRouteFinished(RouteManager.Error error, List<RouteResult> list) {
if (error == RouteManager.Error.NONE && list.get(0).getRoute() != null){
//create a map route and place it on the map
Route route = list.get(0).getRoute();
mMapRoute = new MapRoute(route);
mMap.addMapObject(mMapRoute);
//begin navigation
NavigationManager.Error navigationError = mNavigationManager.startNavigation(route);
if (navigationError != NavigationManager.Error.NONE)
{
System.out.println(navigationError);
}
else {
System.out.println("start navigation no error");
mNavigationManager.addNavigationManagerEventListener(new WeakReference< NavigationManager.NavigationManagerEventListener>(mNavigationManagerEventListener));
}
//get boundingbox containing the route and zoom in (no animation)
GeoBoundingBox gbb = route.getBoundingBox();
mMap.zoomTo(gbb, Map.Animation.NONE, Map.MOVE_PRESERVE_ORIENTATION);
}
}
};
private NavigationManager.NavigationManagerEventListener mNavigationManagerEventListener = new NavigationManager.NavigationManagerEventListener() {
#Override
public void onRunningStateChanged() {
super.onRunningStateChanged();
System.out.println("onRunningStateChanged");
}
#Override
public void onNavigationModeChanged(){
super.onNavigationModeChanged();
System.out.println("onNavigationModeChanged");
}
};
private NavigationManager.RoadView.Listener mNavigationManagerRoadViewListener = new NavigationManager.RoadView.Listener() {
#Override
public void onPositionChanged(GeoCoordinate geoCoordinate) {
Log.d("Roadview pos", geoCoordinate.toString());
}
};
private class RouteCalculationTask extends AsyncTask<String, String, String> {
private RouteOptions.Type routeType;
private ProgressDialog progressDialog = new ProgressDialog(Navigation.this);
public RouteCalculationTask(RouteOptions.Type type) {
/*
FASTEST(0),
SHORTEST(1),
ECONOMIC(2);
*/
routeType = type;
}
#Override
protected String doInBackground(String... url){
//clear previous results
if (mMap != null && mMapRoute != null){
mMap.removeMapObject(mMapRoute);
mMapRoute = null;
}
//select routing opitions
RoutePlan routePlan = new RoutePlan();
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.PEDESTRIAN);
routeOptions.setRouteType(routeType);
routePlan.setRouteOptions(routeOptions);
//set start point
for(int i = 0; i < 100; i++)
{
if(mPositoningManager.hasValidPosition())
break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
originGeo = mPositoningManager.getPosition().getCoordinate();
routePlan.addWaypoint(originGeo);
System.out.println("get originGeo");
//set end point
routePlan.addWaypoint(destinationGeo);
//retrieve routing information via RouteManagerEventListener
RouteManager.Error error = mRouteManager.calculateRoute(routePlan, mRouteMangerListener);
if (error != RouteManager.Error.NONE)
{
/*
NONE(0),
UNKNOWN(1),
OUT_OF_MEMORY(2),
INVALID_PARAMETERS(3),
INVALID_OPERATION(4),
GRAPH_DISCONNECTED(5),
GRAPH_DISCONNECTED_CHECK_OPTIONS(6),
NO_START_POINT(7),
NO_END_POINT(8),
NO_END_POINT_CHECK_OPTIONS(9),
CANNOT_DO_PEDESTRIAN(10),
ROUTING_CANCELLED(11),
VIOLATES_OPTIONS(12),
ROUTE_CORRUPTED(13),
INVALID_CREDENTIALS(14),
REQUEST_TIMEOUT(15),
PT_ROUTING_UNAVAILABLE(16),
OPERATION_NOT_ALLOWED(17),
NO_CONNECTIVITY(18);
*/
System.out.println(error);
}
String data = "";
return data;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
mMapFragment.getView().setVisibility(View.VISIBLE);
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
//define positoning listener
private PositioningManager.OnPositionChangedListener mPositioningListener = new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod, GeoPosition geoPosition, boolean b) {
if (!mPositioningListenerPaused && geoPosition.isValid()){
//originGeo = geoPosition.getCoordinate();
mMap.setCenter(geoPosition.getCoordinate(), Map.Animation.NONE);
Double speed = geoPosition.getSpeed();
Double heading = geoPosition.getHeading();
originGeo = geoPosition.getCoordinate();
System.out.println(originGeo.toString());
System.out.println(speed);
}
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
//determine if tunnel extrapolation is active
if (locationMethod == PositioningManager.LocationMethod.GPS){
boolean isExtrapolated = ((mPositoningManager.getRoadElement() != null)
&& (mPositoningManager.getRoadElement().getAttributes().contains(RoadElement.Attribute.TUNNEL)));
boolean hasGPS = (locationStatus == locationStatus.AVAILABLE);
}
}
};
//Route recalculation
private NavigationManager.RerouteListener mNavigaionRerouteListener = new NavigationManager.RerouteListener() {
#Override
public void onRerouteBegin() {
super.onRerouteBegin();
Toast.makeText(getApplicationContext(), "reroute begin", Toast.LENGTH_SHORT).show();
}
#Override
public void onRerouteEnd(Route route){
super.onRerouteEnd(route);
Toast.makeText(getApplicationContext(), "reroute end", Toast.LENGTH_SHORT).show();
}
};
}
from my understanding when your position strays off the calculated route, it should trigger a route (re)calculation. I have tried it and I received both onRerouteBegin and onReRouteEnd callbacks. From my observation staying on route does not trigger any re-routing.

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