2016-05-07 114 views
-2

我想要在UserActivity工具欄上顯示我的城市名稱..我正在MainActivity中搜索並顯示我當前的城市名稱...我mainactivity cityname顯示在工具欄上,但我不知道如何在有用的活動中獲取該名稱...請幫助我。 ..如何在工具欄上獲取當前城市名稱?

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; 
} 

}

+1

只發布相關的代碼,你得到錯誤,需要改進等。不要發佈整個代碼。每個人都很難找出問題。 –

+0

兄弟我在MainActivity.java中搜索城市名稱,我想在我的UserAcitivity.java(工具欄上)的城市名稱 –

+0

查看答覆我提供的 –

回答

0

創建一個常量類。

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; 
    } 
} 

現在,當你得到這個城市的名字,你在這裏保存這個城市的名字一樣

Constant.setCityName("ANY"); 

而當你想從任何類或任何活動獲取城市名稱,你可以從這裏像這樣得到它

Constant.getCityName(); 

這個名字是存儲直到你的應用程序打開。所以不需要傳遞每個活動的意圖。您可以通過這種方式從您的應用程序的任何地方獲取城市名稱

而你的問題解決方案

MainActivity

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

UserActivity

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

改變這一行

toolbar.setTitle(Constant.getCityName()); 
+0

謝謝兄弟你的幫助..我想更多的一件事你可以請幫助...我希望我的GPS自動無需設置..我使用這個需要我來設置:(意向意圖=新意圖(Settings.ACTION_LOCATION_SOURCE_SETTINGS); –

+0

在這裏你去http://stackoverflow.com/questions/4721449/how-can-i-enable-or-disable-the-gps-programmatically-on-android –

+0

兄弟我試過你的代碼太...但它顯示靜態的錯誤。 –

0

可以傳遞你的城市名稱從MainActivityUserActivity使用意圖。

當你開始你的UserActivityMainActivity,使用IntentputExtra(String, String)

例如: 在MainActivity

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

而且在UserActivity

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

或者你可以做

getSupportActionBar().setTitle(cityName); 

嘗試

setSupportActionBar(toolbar); 
+0

無法解析.getExtra .... –

+0

無法解析.getExtra .... –

-1

採取的cityName在MainActivity靜態

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

然後從UserActivity

得到它
String city=MainActivity.cityName; 
+0

這將創建問題,如果MainActivity是關閉和拋出異常。我的意思是活動不在活動堆棧中,用戶已完成該活動。你怎麼看? –

+0

謝謝兄弟:)它的作品! –

+0

我想更多的一件事你可以請幫助...我希望我的GPS自動無需設置..我使用這個需要我設置:( 意圖intent =新的意圖(Settings.ACTION_LOCATION_SOURCE_SETTINGS); –

0

您可以使用共享偏好像這樣保存您的城市名稱:

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

現在,無論你想使用你的城市名稱:

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

sharedpreferences。getString(「城市名稱 - 顯示城市名稱錯誤」); –

+0

在putstring中設置專有名稱不要在城市和名稱之間放置空格,並從相同名稱獲取字符串。希望它能工作 –

+0

我得到cityname形式的GPS ...所以我把我的字符串名稱在那裏.. 像.putString(「cityname」,cityName);這裏cityName是我的字符串名稱,我存儲從gps –

相關問題