-2

i want my city name on UserActivity toolbar..i am searching and showing my current city name in MainActivity...i mainactivity cityname shows on toolbar but i dont know how to get that name in useractivity...please help me...

MainActivity.java

public class MainActivity extends Activity
    implements View.OnClickListener {

private LocationManager locationManager=null;
private LocationListener locationListener=null;

private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
String cityName=null;
String addressName = null;

private static final String TAG = "Debug";
private Boolean flag = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    //if you want to lock screen for always Portrait mode
    setRequestedOrientation(ActivityInfo
            .SCREEN_ORIENTATION_PORTRAIT);

    pb = (ProgressBar) findViewById(R.id.progressBar1);
    pb.setVisibility(View.INVISIBLE);

    editLocation = (EditText) findViewById(R.id.editTextLocation);


    btnGetLocation = (Button) findViewById(R.id.btnLocation);
    btnGetLocation.setOnClickListener(this);

    locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);

}

@Override
public void onClick(View v) {
    flag = displayGpsStatus();
    if (flag) {

        Log.v(TAG, "onClick");

        editLocation.setText("Please!! move your device to" +
                " see the changes in coordinates." + "\nWait..");

        pb.setVisibility(View.VISIBLE);
       locationListener = new MyLocationListener();

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);

    } else {
        alertbox("Gps Status!!", "Your GPS is: OFF");
    }

}

/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
    ContentResolver contentResolver = getBaseContext()
            .getContentResolver();
    boolean gpsStatus = Settings.Secure
            .isLocationProviderEnabled(contentResolver,
                    LocationManager.GPS_PROVIDER);
    if (gpsStatus) {
        return true;

    } else {
        return false;
    }
}

/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your Device's GPS is Disable")
            .setCancelable(false)
            .setTitle("** Gps Status **")
            .setPositiveButton("Gps On",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // finish the current activity
                            // AlertBoxAdvance.this.finish();
                            Intent intent =new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // cancel the dialog box
                            dialog.cancel();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {

        editLocation.setText("");
        pb.setVisibility(View.INVISIBLE);

/*----------to get City-Name from coordinates ------------- */

        Geocoder gcd = new Geocoder(getBaseContext(),
                Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(), loc
                    .getLongitude(), 1);
            if (addresses.size() > 0)

                System.out.println(addresses.get(0).getLocality());
            cityName = addresses.get(0).getLocality();
            addressName = addresses.get(0).getSubLocality();
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setTitle(cityName);
            setActionBar(toolbar);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //editLocation.setText(longitude+"\n"+latitude + "\n\nMy Current Address is: "+addressName+", "+cityName);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider,
                                int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

UserActivity.java

public class UserActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    *toolbar.setTitle("how i should call that cityName here");*
    setSupportActionBar(toolbar);


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.user, 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);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}

4 Answers4

0

You can pass your city name from MainActivity to UserActivity using intent.

Where you're starting your UserActivity from MainActivity, use putExtra(String, String) of Intent.

For Example: In MainActivity

Intent i = new Intent(MainActivity.this, UserActivity.class);
i.putExtra("Title", yourCityName);
startActivity(i);

And in UserActivity

String cityName = getIntent().getExtra("Title", "Default City Name");
toolbar.setTitle(cityName);

Or you can try with

getSupportActionBar().setTitle(cityName);

after doing

setSupportActionBar(toolbar);
Ravi Sisodia
  • 776
  • 1
  • 5
  • 20
0

Create one class of Constant.

public class Constant {
    public static  String CITY_NAME ="";

    public static String getCityName() {
        return CITY_NAME;
    }

    public static void setCityName(String cityName) {
        Constant.CITY_NAME = cityName;
    }
}

Now when you get the city name you save this city name here like

Constant.setCityName("ANY");

And when you want to retrieve city name from any class or any activity you can get it from here like this

Constant.getCityName();

This name is store until your app open. So no need to pass on each activity intent. This is the way you can get city name from anywhere from your application.

And your Question Solution

At MainActivity

toolbar.setTitle(cityName);
Constant.setCityName(cityName);
setActionBar(toolbar);

At UserActivity

toolbar.setTitle("how i should call that cityName here");

change this line to

toolbar.setTitle(Constant.getCityName());
Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
0

You can save your city name using shared preference like this:

SharedPreferences sharedpreferences = getSharedPreferences("your preference name", Context.MODE_PRIVATE); Editor editor = sharedpreferences.edit(); editor.putString("cityname", your city name); editor.commit();

now wherever you want to use your city name:

SharedPreferences sharedpreferences = getSharedPreferences("your preference name", Context.MODE_PRIVATE); String cityname=sharedpreferences.getString("cityname"); toolbar.setTitle(cityname);
-1

Take cityName is static in MainActivity

public static String cityName=null; //store in this what ever you whant

then get it from UserActivity

String city=MainActivity.cityName;
Rgv
  • 504
  • 5
  • 23
  • This will create problem if MainActivity is closed and throw exception. I mean Activity is not in the activity stack user has finish that activity. What you think? – Shabbir Dhangot May 07 '16 at 08:02
  • i want one thing more can you please help...i want that my GPS get on Automatically without going to setting..i am using this that takes me to setting :( Intent intent =new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); – Abhijeet Singh May 07 '16 at 08:16
  • @Shabbir Dhangot,why MainActivity closed? – Rgv May 07 '16 at 08:46
  • I mean if developer not need main activity then he finish it. at that time you answer wont work and activity will crash – Shabbir Dhangot May 07 '16 at 11:04
  • @Shabbir Dhangot,from ur answer,if developer not set any value but he using get method then what happend? – Rgv May 07 '16 at 11:17
  • it returns null. If user not setting city and still want to retrieve than obviously it returns null. Its like you create an object not initialized and still you are using it. you need to take care about the initialization. In other way if we initialize CITY_NAME with "" it wont return null anyway. I hope you got the idea – Shabbir Dhangot May 07 '16 at 11:21