0

I have created a login page which consists of username password login button and change language option(drop down consisting of required languages).

Login Page

enter image description here

enter image description here

My problem is how to apply internationalization to all the pages.Suppose if click on french it should be applied to to login page as well as the next page after login.Please Help..

MainActivity.java

package com.example.login11;


import java.util.HashMap;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity 
{

    // User Session Manager Class
    UserSessionManager session;

 // Button Logout
    Button btnLogout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Session class instance
        session = new UserSessionManager(getApplicationContext());

        TextView lblName = (TextView) findViewById(R.id.lblName);
        TextView lblEmail = (TextView) findViewById(R.id.lblEmail);

        // Button logout
        btnLogout = (Button) findViewById(R.id.btnLogout);

        Toast.makeText(getApplicationContext(), 
                       "User Login Status: " + session.isUserLoggedIn(), 
                       Toast.LENGTH_LONG).show();



        // Check user login (this is the important point)
        // If User is not logged in , This will redirect user to LoginActivity 
        // and finish current activity from activity stack.
        if(session.checkLogin())
            finish();

        // get user data from session
        HashMap<String, String> user = session.getUserDetails();

        // get name
        String name = user.get(UserSessionManager.KEY_NAME);

        // get email
        String email = user.get(UserSessionManager.KEY_EMAIL);

        // Show user data on activity
        lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
        lblEmail.setText(Html.fromHtml("Email: <b>" + email + "</b>"));


        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // Clear the User session data
                // and redirect user to LoginActivity
                session.logoutUser();
            }
        });
    }

}

LoginActivity.java

package com.example.login11;



import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class LoginActivity extends ActionBarActivity
{
     Button btnLogin;

    EditText txtUsername, txtPassword;
    private Spinner language;
    // User Session Manager Class
    UserSessionManager session;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // User Session Manager
        session = new UserSessionManager(getApplicationContext());                

        // get Email, Password input text
        txtUsername = (EditText) findViewById(R.id.txtUsername);
        txtPassword = (EditText) findViewById(R.id.txtPassword); 
        language = (Spinner) findViewById(R.id.spinner1);
        Toast.makeText(getApplicationContext(), 
                "User Login Status: " + session.isUserLoggedIn(), 
                Toast.LENGTH_LONG).show();


        // User Login button
        btnLogin = (Button) findViewById(R.id.btnLogin);

     // Spinner method to read the on selected value
            ArrayAdapter<State> spinnerArrayAdapter = new ArrayAdapter<State>(this,
                    android.R.layout.simple_spinner_item, new State[] {
                            new State("english"), new State("french") });
            language.setAdapter(spinnerArrayAdapter);
            //language.setOnItemSelectedListener(this);
        // Login button click event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // Get username, password from EditText
                String username = txtUsername.getText().toString();
                String password = txtPassword.getText().toString();

                // Validate if username, password is filled             
                if(username.trim().length() > 0 && password.trim().length() > 0){

                    // For testing puspose username, password is checked with static data
                    // username = admin
                    // password = admin

                    if(username.equals("admin") && password.equals("admin")){


                        session.createUserLoginSession("Android Example", 
                           "androidexample84@gmail.com");

                        // Starting MainActivity
                        Intent i = new Intent(getApplicationContext(), MainActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        // Add new Flag to start new Activity
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);

                        finish();

                    }else{

                        // username / password doesn't match&
                        Toast.makeText(getApplicationContext(), 
                          "Username/Password is incorrect",
                                Toast.LENGTH_LONG).show();

                    }               
                }else{

                    // user didn't entered username or password
                    Toast.makeText(getApplicationContext(), 
                         "Please enter username and password",
                              Toast.LENGTH_LONG).show();

                }

            }
        });
    }

}

userSession.java

package com.example.login11;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class UserSessionManager 
{
     // Shared Preferences reference
    SharedPreferences pref;

    // Editor reference for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREFER_NAME = "AndroidExamplePref";

    // All Shared Preferences Keys
    private static final String IS_USER_LOGIN = "IsUserLoggedIn";

    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "name";

    // Email address (make variable public to access from outside)
    public static final String KEY_EMAIL = "email";

    // Constructor
    public UserSessionManager(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    //Create login session
    public void createUserLoginSession(String name, String email){
        // Storing login value as TRUE
        editor.putBoolean(IS_USER_LOGIN, true);

        // Storing name in pref
        editor.putString(KEY_NAME, name);

        // Storing email in pref
        editor.putString(KEY_EMAIL, email);

        // commit changes
        editor.commit();
    }   

    /**
     * Check login method will check user login status
     * If false it will redirect user to login page
     * Else do anything
     * */
    public boolean checkLogin(){
        // Check login status
        if(!this.isUserLoggedIn()){

            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.class);

            // Closing all the Activities from stack
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);

            return true;
        }
        return false;
    }



    /**
     * Get stored session data
     * */
    public HashMap<String, String> getUserDetails(){

        //Use hashmap to store user credentials
        HashMap<String, String> user = new HashMap<String, String>();

        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));

        // user email id
        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

        // return user
        return user;
    }

    /**
     * Clear session details
     * */
    public void logoutUser(){

        // Clearing all user data from Shared Preferences
        editor.clear();
        editor.commit();

        // After logout redirect user to Login Activity
        Intent i = new Intent(_context, LoginActivity.class);

        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }


    // Check for login
    public boolean isUserLoggedIn(){
        return pref.getBoolean(IS_USER_LOGIN, false);
    }
}
user3736518
  • 75
  • 1
  • 2
  • 12

1 Answers1

0

You can do something like this:

public class LanguagePesistence {

    SharedPreferences pref;
    Editor editor;
    Context _context;
    int PRIVATE_MODE = 0;

    private static final String PREF_NAME = "LanguagePesistence";

    public static final String LANGUAGE_DEFAULT = Locale.getDefault().getLanguage();
    public static final String LANGUAGE = "language";

    public LanguagePesistence(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public String getLanguageSelected(){
        return pref.getString(LANGUAGE, LANGUAGE_DEFAULT);
    }

    public void setLanguage(String language){
        editor.putString(LANGUAGE, language);         
        editor.commit();
        alterIdioma(language);
    }

    public void alterIdioma(String languageToLoad){

        Locale locale = new Locale(languageToLoad);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        Resources res = this._context.getResources(); 
        res.updateConfiguration(config, res.getDisplayMetrics());
    }   
}

To set a language

LanguagePesistence lf = new LanguagePesistence(getBaseContext());
lf.setLanguage("eng");

edited: see more here : http://mobgeek.com.br/blog/apps-android-multi-idiomas

values-en

 <string name="toast_network">Network not avaliable</string>
 <string name="toast_router_fail">Route not created!</string>
 <string name="toast_router_create">Wait!</string>

values-pt

<string name="toast_network">Sem conexão com internet</string>
<string name="toast_router_fail">Não foi possivel criar uma rota!</string>
<string name="toast_router_create">Aguarde!</string>

Edited part 2 :

the code below is to change at runtime the language setting if you have an option to choose a language, so that code propagates to its application selected language

Locale locale = new Locale(languageToLoad);
            Locale.setDefault(locale);
            Configuration config = new Configuration();
            config.locale = locale;
            Resources res = this._context.getResources(); 
            res.updateConfiguration(config, res.getDisplayMetrics());

taking the language selected in the spinner and changing the system configuration to use this

language.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id){
            //get language selected example: eng or esp or fr
            LanguagePesistence lf = new LanguagePesistence(getBaseContext());
            lf.setLanguage("eng");

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });
Anderson K
  • 5,445
  • 5
  • 35
  • 50
  • do i need to create any xml file for these languages – user3736518 Jul 22 '14 at 04:06
  • and where to use this code LanguagePesistence lf = new LanguagePesistence(getBaseContext()); lf.setLanguage("eng"); – user3736518 Jul 22 '14 at 04:13
  • @user3736518, spinner in your language changer, I will add some more information! – Anderson K Jul 22 '14 at 04:19
  • where to add this particular line..LanguagePesistence lf = new LanguagePesistence(getBaseContext()); lf.setLanguage("eng"); – user3736518 Jul 22 '14 at 04:54
  • @user3736518, I add this info in my answer!! – Anderson K Jul 22 '14 at 05:04
  • still i am facing problem.can we chat?? – user3736518 Jul 22 '14 at 05:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57727/discussion-between-user3736518-and-andre-c-s). – user3736518 Jul 22 '14 at 05:13
  • can u plz tell wat mistake i did? – user3736518 Jul 23 '14 at 04:16
  • @user3736518,try to understand this tutorial, but if you still do not understand, we will try other![Android Building Multi-Language Supported App](http://www.androidhive.info/2014/07/android-building-multi-language-supported-app/) – Anderson K Jul 23 '14 at 12:09
  • @ André.C.S by changing the settings i am able to change to language ..but suppose if there is another page after login,will that action be applied to next page also? i.e. suppose I have selected Japanese as my language,but want to apply the language to be applied to the whole application?how to do that? – user3736518 Jul 24 '14 at 04:04
  • Language Locale German - de Chinese - zh Czech - cs Dutch - nl French - fr Italian - it pass the desired location in this method, your application and all wore strings of the corresponding folder `LanguagePesistence lf = new LanguagePesistence(getBaseContext()); //examples lf.setLanguage("de");` lf.setLanguage("zh");` lf.setLanguage("cs");` lf.setLanguage("fr");` – Anderson K Jul 24 '14 at 04:18
  • i am still facing problem.can we chat? – user3736518 Jul 24 '14 at 04:30