0

am new in android studio and I am trying to make my simple app weather info via yahoo weather service JSON data , i would like to make a different language display in my app , example English and Arabic am working on string.xml and i translate some words in main activity , am try translate condition Text to Arabic but not working , if there way on string ? i want translate on condition Text , i hope get answer withe code .

my code if any one can help my

package net.digitalphantom.app.weatherapp;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import net.digitalphantom.app.weatherapp.data.Channel;
import net.digitalphantom.app.weatherapp.data.Condition;
import net.digitalphantom.app.weatherapp.data.LocationResult;
import net.digitalphantom.app.weatherapp.data.Units;
import net.digitalphantom.app.weatherapp.fragments.WeatherConditionFragment;
import net.digitalphantom.app.weatherapp.listener.GeocodingServiceListener;
import net.digitalphantom.app.weatherapp.listener.WeatherServiceListener;
import net.digitalphantom.app.weatherapp.service.WeatherCacheService;
import net.digitalphantom.app.weatherapp.service.GoogleMapsGeocodingService;
import net.digitalphantom.app.weatherapp.service.YahooWeatherService;

public class WeatherActivity extends AppCompatActivity implements WeatherServiceListener, GeocodingServiceListener, LocationListener {

    public static int GET_WEATHER_FROM_CURRENT_LOCATION = 1979455;

    private ImageView weatherIconImageView;
    private TextView temperatureTextView;
    private TextView conditionTextView;
    private TextView locationTextView;

    private YahooWeatherService weatherService;
    private GoogleMapsGeocodingService geocodingService;
    private WeatherCacheService cacheService;

    private ProgressDialog loadingDialog;

    // weather service fail flag
    private boolean weatherServicesHasFailed = false;

    private SharedPreferences preferences = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        weatherIconImageView = (ImageView) findViewById(R.id.weatherIconImageView);
        temperatureTextView = (TextView) findViewById(R.id.temperatureTextView);
        conditionTextView = (TextView) findViewById(R.id.conditionTextView);
        locationTextView = (TextView) findViewById(R.id.locationTextView);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        weatherService = new YahooWeatherService(this);
        weatherService.setTemperatureUnit(preferences.getString(getString(R.string.pref_temperature_unit), null));

        geocodingService = new GoogleMapsGeocodingService(this);
        cacheService = new WeatherCacheService(this);

        if (preferences.getBoolean(getString(R.string.pref_needs_setup), true)) {
            startSettingsActivity();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        loadingDialog = new ProgressDialog(this);
        loadingDialog.setMessage(getString(R.string.loading));
        loadingDialog.setCancelable(false);
        loadingDialog.show();

        String location = null;

        if (preferences.getBoolean(getString(R.string.pref_geolocation_enabled), true)) {
            String locationCache = preferences.getString(getString(R.string.pref_cached_location), null);

            if (locationCache == null) {
                getWeatherFromCurrentLocation();
            } else {
                location = locationCache;
            }
        } else {
            location = preferences.getString(getString(R.string.pref_manual_location), null);
        }

        if (location != null) {
            weatherService.refreshWeather(location);
        }
    }

    private void getWeatherFromCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
            }, GET_WEATHER_FROM_CURRENT_LOCATION);

            return;
        }

        // system's LocationManager
        final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        Criteria locationCriteria = new Criteria();

        if (isNetworkEnabled) {
            locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
        } else if (isGPSEnabled) {
            locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
        }

        locationManager.requestSingleUpdate(locationCriteria, this, null);
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == WeatherActivity.GET_WEATHER_FROM_CURRENT_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getWeatherFromCurrentLocation();
            } else {
                loadingDialog.hide();

                AlertDialog messageDialog = new AlertDialog.Builder(this)
                        .setMessage(getString(R.string.location_permission_needed))
                        .setPositiveButton(getString(R.string.disable_geolocation), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                startSettingsActivity();
                            }
                        })
                        .create();

                messageDialog.show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    private void startSettingsActivity() {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.currentLocation:
                loadingDialog.show();
                getWeatherFromCurrentLocation();
                return true;
            case R.id.settings:
                startSettingsActivity();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void serviceSuccess(Channel channel) {
        loadingDialog.hide();

        Condition condition = channel.getItem().getCondition();
        Units units = channel.getUnits();
        Condition[] forecast = channel.getItem().getForecast();

        int weatherIconImageResource = getResources().getIdentifier("icon_" + condition.getCode(), "drawable", getPackageName());

        weatherIconImageView.setImageResource(weatherIconImageResource);
        temperatureTextView.setText(getString(R.string.temperature_output, condition.getTemperature(), units.getTemperature()));
        conditionTextView.setText(condition.getDescription());
        locationTextView.setText(channel.getLocation());

        for (int day = 0; day < forecast.length; day++) {
            if (day >= 5) {
                break;
            }

            Condition currentCondition = forecast[day];

            int viewId = getResources().getIdentifier("forecast_" + day, "id", getPackageName());
            WeatherConditionFragment fragment = (WeatherConditionFragment) getSupportFragmentManager().findFragmentById(viewId);

            if (fragment != null) {
                fragment.loadForecast(currentCondition, channel.getUnits());
            }
        }

        cacheService.save(channel);
    }

    @Override
    public void serviceFailure(Exception exception) {
        // display error if this is the second failure
        if (weatherServicesHasFailed) {
            loadingDialog.hide();
            Toast.makeText(this, exception.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            // error doing reverse geocoding, load weather data from cache
            weatherServicesHasFailed = true;
            // OPTIONAL: let the user know an error has occurred then fallback to the cached data
            Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();

            cacheService.load(this);
        }
    }

    @Override
    public void geocodeSuccess(LocationResult location) {
        // completed geocoding successfully
        weatherService.refreshWeather(location.getAddress());

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(getString(R.string.pref_cached_location), location.getAddress());
        editor.apply();
    }

    @Override
    public void geocodeFailure(Exception exception) {
        // GeoCoding failed, try loading weather data from the cache
        cacheService.load(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        geocodingService.refreshLocation(location);
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        // OPTIONAL: implement your custom logic here
    }

    @Override
    public void onProviderEnabled(String s) {
        // OPTIONAL: implement your custom logic here
    }

    @Override
    public void onProviderDisabled(String s) {
        // OPTIONAL: implement your custom logic here
    }
}

thank you

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ALI GHASSAN
  • 221
  • 1
  • 4
  • 13

2 Answers2

2
/***You need to create separate String file for both arabic and English***/

English
 Values
  String.xml
Arabic   
 Values-ar
  String.xml

/**You can change the application language using the following code:**/

 language =  "en"; or  language =  "ar";

@Override
public void recreate()
{
    if (android.os.Build.VERSION.SDK_INT >= 14)
    {
        super.recreate();
    }
    else
    {
        startActivity(getIntent());
        finish();
    }
}

private void updateLanguage(String language)
{
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

    SharedPreferences languagepref = getSharedPreferences("language",MODE_PRIVATE);
    SharedPreferences.Editor editor = languagepref.edit();
    editor.putString("languageToLoad",language);
    editor.apply();

    recreate();
}
yash786
  • 1,151
  • 8
  • 18
  • Please format your answers correctly before posting them. – takendarkk Jul 13 '17 at 18:12
  • thank you for answer , can i make string.xml just for condition Text ? , example , cloud : صحوه – ALI GHASSAN Jul 13 '17 at 18:14
  • 1
    Yes,as i earlier said create separate String file for both arabic and English Create values-en for english and set string as: cloud Create another folder values-ar for Arabic and set string as: صحوه – yash786 Jul 13 '17 at 18:16
  • okay , good the point is how i set the Resources ? exmple if i make string_ar.xml and inside string_ar.xml `صحوه` , how i set him in main activity ? like this ? `conditionTextView.setText(condition.getDescription().getResources());` ? – ALI GHASSAN Jul 13 '17 at 18:25
  • 1
    You can set in your main activity like this: conditionTextView.setText(MainAcivity.this.getResources().getText(R.string. cloud)); – yash786 Jul 13 '17 at 18:30
  • 1
    See you need to same String for different languages buddy as i said earlier string_ar.xml --> صحوه and for English string_en.xml -->cloud – yash786 Jul 13 '17 at 18:45
1

To translate an app you must go to the Translations Editor which is accessible when you open strings.xml. You will have to translate every string yourself and put the desired translation into the Translations Editor. To access different translations the user will have to have their Locale on their device set to one of the country codes that you provide support for. For example in your app you would end up having strings.xml and strings.xml (us) and the app would use Strings from strings.xml as default unless their locale was set to us in which case they would use the strings.xml (us) strings

MacLean Sochor
  • 435
  • 5
  • 14
  • thank you for answer , can i make string.xml just for condition Text ? – ALI GHASSAN Jul 13 '17 at 18:15
  • If you're asking if you can use a ternary like `setText(isArabic ? cloud : صحوه");` I suppose you could, but it would become quite tedious to do so for every place you set a string – MacLean Sochor Jul 13 '17 at 18:20
  • okay , good the point is how i set the Resources ? exmple if i make string_ar.xml and inside string_ar.xml صحوه , how i set him in main activity ? like this ? conditionTextView.setText(condition.getDescription().getReso‌​urces()); ? – ALI GHASSAN Jul 13 '17 at 18:25
  • If you set up the translations editor and properly set the `Locale` on your device by going into the settings you just have to use `getString()` regularly :) That's the beauty of Translations Editor, you don't have to deal with any translating inside your java files – MacLean Sochor Jul 13 '17 at 18:26
  • you mean `conditionTextView.setText(condition.getDescription().getReso‌​‌​urces()); ` – ALI GHASSAN Jul 13 '17 at 18:33