2

I had almost completed my app, and was doing the Navigation Menu last when I realized that you must use fragments instead of activities to have the same Navigation Menu throughout all activities. So now, I am currently in the process of copying, pasting, and making activity java work in fragment java. On my settings page I have a spinner that allows you to select a language. However, part of the code has an error in it that I can't seem to figure out. All help is very much appreciated!! Thank You!

package com.ezeapplications.quikflipfinal;


import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.Locale;
import java.util.Set;


/**
 * A simple {@link Fragment} subclass.
 */
public class SettingsFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    public SettingsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        Button settupdatebtn = (Button) view.findViewById(R.id.setting_update_btn);
        settupdatebtn.setOnClickListener(this);

        Spinner langspinner = (Spinner) view.findViewById(R.id.settings_language_spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.lang_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        langspinner.setAdapter(adapter);
        return view;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

        Spinner langspinner = (Spinner) view.findViewById(R.id.settings_language_spinner);
        langspinner.setOnItemSelectedListener(this);

        if (pos == 1) {

            Toast.makeText(parent.getContext(),
                    "You Have Selected English!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("en");
            SettingsFragment fragmenten = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransactionen =
                    getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransactionen.replace(R.id.fragment_container, fragmenten);
            fragmentTransactionen.commit();
            langspinner.setSelection(1);

        } else if (pos == 2) {

            Toast.makeText(parent.getContext(),
                    "Has Seleccionado Español!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("es");
            SettingsFragment fragmentes = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransactiones =
                    getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransactiones.replace(R.id.fragment_container, fragmentes);
            fragmentTransactiones.commit();
            langspinner.setSelection(2);

        } else if (pos == 3) {

            Toast.makeText(parent.getContext(),
                    "Vous Avez Sélectionné Le Français!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("fr");
            SettingsFragment fragmentfr = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransactionfr =
                    getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransactionfr.replace(R.id.fragment_container, fragmentfr);
            fragmentTransactionfr.commit();
            langspinner.setSelection(3);
        }
    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }


        @Override
                public void onClick (View v) {
            SettingsFragment fragment = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container,fragment);
            fragmentTransaction.commit();
            Toast.makeText(getActivity(), "Settings Updated!", Toast.LENGTH_SHORT).show();
        };

public void setLocale(String lang) {

        Locale myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        }

    }
  • Can you post the error here? Without that no one can identify ur problem. – Sanjay Hirani Feb 05 '17 at 04:10
  • I accidentally posted the question instead of adding tags or code. I was planning on it, but had to edit the question because I accidentally posted it too soon. Code is on there now! – EyeNeedSumHelp Feb 05 '17 at 04:13

2 Answers2

1

You need a Context for creating the ArrayAdapter from the resources. The Fragment class does not have it's own context, rather it depends on the Activity in which it is hosted. So you need to pass in the context from the Activity in which your Fragment resides.

This should have you sorted,

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.lang_array, android.R.layout.simple_spinner_item);

Hope this helps, Happin coding!

Narayan Acharya
  • 1,459
  • 1
  • 18
  • 33
  • Thank You! I got the error to go away, but it won't change the language. I have the Spanish (ES) and French (FR) strings.xml files made, so that shouldn't be an issue. My toast doesn't even pop up when I change the spinner selection. Hope you can help! Thanks! – EyeNeedSumHelp Feb 05 '17 at 04:35
  • Well there are a few things you would need change, so I think I will add another answer here instead of continuing in the comments. Also, if this answer worked for you, please consider upvoting this and marking this as an accepted answer. Thanks! – Narayan Acharya Feb 05 '17 at 04:38
0

Posting this other answer to answer your spinner not changing the language issue.

In short you haven't told the Spinner where to go when an item is selected. You have written the code to handle it but you haven't "linked" it to your Spinner.

First change this line at the beginning of your class,

public class SettingsFragment extends Fragment implements View.OnClickListener,
OnItemSelectedListener{...

You will need this import at the beginning of the file just in case Android Studio does not auto-import,

import android.widget.AdapterView.OnItemSelectedListener;

Next you have to add an annotation to the onItemSelected method like this,

@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {...

These two things help with allowing/letting the Fragment handle what to do when an item is clicked. Last we need to tell the Spinner that clicks will be taken care of by the Fragment.

Spinner langspinner = (Spinner) view.findViewById(R.id.settings_language_spinner);
langspinner.setOnItemSelectedListener(this);

This helps the Spinner to "delegate" the handling of item selections to the Fragment.

Hope this helps. Happy coding!

Narayan Acharya
  • 1,459
  • 1
  • 18
  • 33
  • I implemented and imported the onitemselectedlistener, added override to my onitemselected, and added the other two lines of code, but it still isn't working. :( Just like before the language doesn't change, nor does the settings activity refresh itself. Should I be able to see it open settings activity when I select a spinner option? I know with activities you can see it refresh the screen. Thanks! – EyeNeedSumHelp Feb 05 '17 at 05:08
  • Can you see the toast at least? – Narayan Acharya Feb 05 '17 at 05:10
  • No Toast at all saying you have selected english, spanish, etc. – EyeNeedSumHelp Feb 05 '17 at 05:16
  • I can, however, see that I have selected english, span, french, on the spinner, it just doesn't do anything. – EyeNeedSumHelp Feb 05 '17 at 05:17
  • If you could update your code or maybe post another question with updated code and give me a link here that would be better. – Narayan Acharya Feb 05 '17 at 05:44
  • http://stackoverflow.com/questions/42056217/how-to-make-a-spinner-in-a-fragment-that-changes-the-apps-language – EyeNeedSumHelp Feb 05 '17 at 19:25
  • There is the link to my new question. If you could help, that would be awesome!! Thanks! – EyeNeedSumHelp Feb 05 '17 at 19:26