-1

when I pass parameter between two fragment, the value of string user it is not print in log...why?

This is my code:

ARRAY ADAPTER CLASS:

 public abstract class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener

{
    private List<Planet> planetList;
    private Context context ;
    ArrayList<Birra> objects;
    public boolean Checked;
    private Integer[] imageId;
    String ciao;
    static PlanetAdapter plAdapter;
    String selState ;
    private FragmentManager fragmentManager;

   /* public PlanetAdapter(Context context) {
        super(context, R.layout.single_listview_item);
    }
*/

    /*public PlanetAdapter(FragmentManager fm,List<Planet> planetList, Context context,Integer[] imageId) {


        super(context, R.layout.single_listview_item,planetList);


        this.fm=fm;
        this.planetList = planetList;
        this.context = context;
        this.imageId = imageId;
    }
*/
    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId) {
        super(context, R.layout.single_listview_item,planetList);
        this.planetList = planetList;
        this.context = context;
        this.imageId = imageId;
    }

    public FragmentManager getFragmentManager() {
        return fragmentManager;
    }


    public class PlanetHolder {
        public TextView planetName;
        public TextView distView;
        public TextView valuta;
        public CheckBox chkBox;
        public EditText edit;
        public TextView caratteristica;
        public boolean checked;
        public TextView id;
        public ImageView imageView;
        public Spinner spinner;
    }

    @Override
    public int getCount() {
        return planetList.size();
    }

    @Override
    public Planet getItem(int position) {
        return planetList.get(position);
    }




    @Override
    public View getView(final int position, final View convertView, ViewGroup parent) {

        View row = convertView;
        PlanetHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.single_listview_item, parent, false);
            holder = new PlanetHolder();
            holder.planetName = (TextView) row.findViewById(R.id.name);
            holder.distView = (TextView) row.findViewById(R.id.dist);
            holder.valuta = (TextView) row.findViewById(R.id.valuta);
            holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
            holder.edit = (EditText) row.findViewById(R.id.editText);
            holder.spinner = (Spinner) row.findViewById(R.id.simpleSpinner);

            holder.caratteristica=(TextView) row.findViewById(R.id.caratteristica);
            holder.imageView = (ImageView) row.findViewById(R.id.ivImage);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);
            holder.spinner.setVisibility(View.GONE);

            // holder.id = (TextView) row.findViewById(R.id.id);


            row.setTag(holder);

        } else {
            holder = (PlanetHolder) row.getTag();
        }

        final Planet p = planetList.get(position);
        holder.imageView.setImageResource(imageId[position]);
        holder.planetName.setText(p.getName());
        holder.distView.setText("" + p.getDistance());
        holder.valuta.setText("" + p.getValuta());
        holder.chkBox.setChecked(p.isSelected());
        holder.chkBox.setTag(p);
        holder.caratteristica.setText(p.getCaratteristica());
       holder.edit.setEnabled(false);
        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        boolean isChecked = states.getBoolean("holder.chkBox" + holder.planetName.getText().toString(), false);
        System.out.println(isChecked);
        if (isChecked) {
            holder.chkBox.setChecked(true);
            holder.edit.setVisibility(View.VISIBLE);
            holder.edit.setEnabled(true);
            holder.spinner.setVisibility(View.VISIBLE);

            SharedPreferences statess = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
            String string = statess.getString("finalHolder.edit" + holder.planetName.getText().toString(), holder.edit.getText().toString().trim());
            holder.edit.setText(string);


        } else {
            holder.chkBox.setChecked(false);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);
            holder.spinner.setVisibility(View.GONE);


         }

        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);
       // final BirraHolder finalHolder = birraHolder;
        final PlanetHolder finalHolder = holder;

        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    finalHolder.spinner.setVisibility(View.VISIBLE);
                    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                            getContext(),
                            R.array.country_arrays,
                            android.R.layout.simple_spinner_item);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    //finalHolder.spinner.setAdapter(adapter);

                    finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            finalHolder.spinner.setSelection(position);
                            selState = finalHolder.spinner.getSelectedItem().toString();
                            System.out.println(selState);
                            Toast.makeText(
                                    getContext(),
                                    "Clicked on Planet: " + selState + "", Toast.LENGTH_SHORT).show();

/*
                            Fragment fragment = new Fragment();
                             Bundle bundle = new Bundle();
                            bundle.putString("key", selState);
                            Log.i("BUNDLE", bundle.toString());
                            fragment.setArguments(bundle);*/
                            MyListFragment fragment = MyListFragment.newInstance("my_string");

FRAGMENT:

public  class MyListFragment extends Fragment implements
        CompoundButton.OnCheckedChangeListener{

    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user="";

    private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;

    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,
            /*R.drawable.image6,
            R.drawable.image7*/

    };
    public static MyListFragment newInstance(String tagName) {
        MyListFragment fragment = new MyListFragment ();
        Bundle args = new Bundle();
        args.putString("key", tagName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            user = getArguments().getString("key");
        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();

        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();

        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        /*Bundle bundle = this.getArguments();
        String strtext = bundle.getString("key", " ");
        System.out.println(strtext);*/
        System.out.println("prima ancora");

        Bundle arguments = this.getArguments();
        System.out.println("prima");
        if (arguments != null) {
            System.out.println("dopo");

            //String userId = arguments.getString("key");
                //System.out.println("finalmente:"+userId);
             user = getArguments().getString("Key");


        } /*else {
            Log.i("BUNDLE == null", "NULL");
        }*/
        System.out.println("finalmente:"+user);
        Log.d("finalmente:", "" + user);



        lv = (ListView) rootView.findViewById(R.id.listview);
        ListAdapter listAdapter = new MyListAdapter(getContext());
        lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
        txtName = (TextView) rootView.findViewById(R.id.name);
        txtEmail = (TextView) rootView.findViewById(R.id.numero_telefonico);
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);

        // SqLite database handler
        db = new SQLiteHandler(context.getApplicationContext());


        // session manager
        session = new SessionManager(context.getApplicationContext());
/*

        if (!session.isLoggedIn()) {
            logoutUser();
        }
*/

        // Fetching user details from SQLite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        //String email = user.get("email");
//      String email = user.get("email");
        String email = user.get("numero_telefonico");


        // Displaying the user details on the screen
        System.out.println(name + email);

        txtName.setText(name);
        txtEmail.setText(email);
    /*  Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showResult(v);


            }
        });*/
        //return inflater.inflate(R.custom_spinner_items.fragment_list2, container, false);
        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });



        return rootView;
    }




    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
//      Intent intent = new Intent(MyListFragment.this, LoginActivity.class);
        Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);

        startActivity(intent);
        mInstance.finish();
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();


    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", "6", "€","(pomodoro e mozzarella),"));
        planetList.add(new Planet("Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet("Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet("Marinara", "5", "€","(pomodoro)"));
        planetList.add(new Planet("Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
    }




    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        /*int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);


            *//*Toast.makeText(
                getActivity(),
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*//*
        }*/

    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    /*public String showResult(View v) throws IOException {
    *//*    //String  result = "Selected Product are :";
        String  result = "";

    //  int totalAmount=0;
        //String  result2 = "";
        //int totalAmount2=0;

        //String a="";
        //String z="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                result += "\n" + p.getName()+" "+p.getDistance()+"€"+"q.tà :"+p.getQuantità();
            }
        }


        //Toast.makeText(context, result + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();

        return result;*//*
        String  result = "";

        Gson json = new Gson();
        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                *//*json.put("name",p.getName());
                json.put("distance",p.getDistance());
                json.put("quantity",p.getQuantità());*//*
                result=result+json.toJson(p);


            }
        }
         //result=json.toString();

        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/droidText/";

        //FileWriter file=null;

    *//*    try {
            file = new FileWriter(path+"filename5.json");
            file.write(result);


        }catch(IOException ie){}
        finally{


            file.flush();
            file.close();

        }*//*
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());

        try(FileWriter file = new FileWriter(path  + currentDate + " - " + ".json"))  {
        //  file=new FileWriter(path+"filename100.json");
        *//*FileWriter file = new FileWriter(path+"filename31.json");
            file.write(result);
        file.close();
        *//*

            json.toJson(result, file);
        *//*catch(IOException r){

        }*//*
        }catch (IOException e){

        }
        System.out.println(result);
        return result;

    }*/
    public static String showResultTotale2(View v,String user) {

        int totalAmount=0;
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName()+ " " + p.getDistance() + "€" + "q.tà :" + p.getQuantità()+ " " + user;

            }
        }
        return pizzeOrdinate;
    }


    public static int showResultTotale(View v) {

        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt;
            }
        }
        return totalAmount;
    }





}
markella
  • 21
  • 2
  • 7

4 Answers4

0

Try like this (When creating fragment in android studio, it is done this way):

public  class MyListFragment extends Fragment implements
        CompoundButton.OnCheckedChangeListener{

    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user="";

    private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;

    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,
            /*R.drawable.image6,
            R.drawable.image7*/

    };

public MyListFragment () { //Always put the empty constructor
        }

    public static MyListFragment newInstance(String tagName) {
        MyListFragment fragment = new MyListFragment ();
        Bundle args = new Bundle();
        args.putString("key", tagName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            user = getArguments().getString("key");
        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();

        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();

        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        /*Bundle bundle = this.getArguments();
        String strtext = bundle.getString("key", " ");
        System.out.println(strtext);*/
        System.out.println("prima ancora");

        Bundle arguments = this.getArguments();
        System.out.println("prima");

        System.out.println("finalmente:"+user);
        Log.d("finalmente:", "" + user);



        lv = (ListView) rootView.findViewById(R.id.listview);
        ListAdapter listAdapter = new MyListAdapter(getContext());
        lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
        txtName = (TextView) rootView.findViewById(R.id.name);
        txtEmail = (TextView) rootView.findViewById(R.id.numero_telefonico);
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);

        // SqLite database handler
        db = new SQLiteHandler(context.getApplicationContext());


        // session manager
        session = new SessionManager(context.getApplicationContext());
/*

        if (!session.isLoggedIn()) {
            logoutUser();
        }
*/

        // Fetching user details from SQLite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        //String email = user.get("email");
//      String email = user.get("email");
        String email = user.get("numero_telefonico");


        // Displaying the user details on the screen
        System.out.println(name + email);

        txtName.setText(name);
        txtEmail.setText(email);
    /*  Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showResult(v);


            }
        });*/
        //return inflater.inflate(R.custom_spinner_items.fragment_list2, container, false);
        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });



        return rootView;
    }




    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
//      Intent intent = new Intent(MyListFragment.this, LoginActivity.class);
        Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);

        startActivity(intent);
        mInstance.finish();
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();


    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", "6", "€","(pomodoro e mozzarella),"));
        planetList.add(new Planet("Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet("Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet("Marinara", "5", "€","(pomodoro)"));
        planetList.add(new Planet("Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
    }




    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        /*int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);


            *//*Toast.makeText(
                getActivity(),
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*//*
        }*/

    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    /*public String showResult(View v) throws IOException {
    *//*    //String  result = "Selected Product are :";
        String  result = "";

    //  int totalAmount=0;
        //String  result2 = "";
        //int totalAmount2=0;

        //String a="";
        //String z="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                result += "\n" + p.getName()+" "+p.getDistance()+"€"+"q.tà :"+p.getQuantità();
            }
        }


        //Toast.makeText(context, result + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();

        return result;*//*
        String  result = "";

        Gson json = new Gson();
        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                *//*json.put("name",p.getName());
                json.put("distance",p.getDistance());
                json.put("quantity",p.getQuantità());*//*
                result=result+json.toJson(p);


            }
        }
         //result=json.toString();

        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/droidText/";

        //FileWriter file=null;

    *//*    try {
            file = new FileWriter(path+"filename5.json");
            file.write(result);


        }catch(IOException ie){}
        finally{


            file.flush();
            file.close();

        }*//*
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());

        try(FileWriter file = new FileWriter(path  + currentDate + " - " + ".json"))  {
        //  file=new FileWriter(path+"filename100.json");
        *//*FileWriter file = new FileWriter(path+"filename31.json");
            file.write(result);
        file.close();
        *//*

            json.toJson(result, file);
        *//*catch(IOException r){

        }*//*
        }catch (IOException e){

        }
        System.out.println(result);
        return result;

    }*/
    public static String showResultTotale2(View v,String user) {

        int totalAmount=0;
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName()+ " " + p.getDistance() + "€" + "q.tà :" + p.getQuantità()+ " " + user;

            }
        }
        return pizzeOrdinate;
    }


    public static int showResultTotale(View v) {

        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt;
            }
        }
        return totalAmount;
    }





}

Just simpler :

public class MyListFragment extends Fragment {


    public MyListFragment () { //Always put the empty constructor
    }


    public static MyListFragment newInstance(String tagName) {
        MyListFragment fragment = new MyListFragment ();
        Bundle args = new Bundle();
        args.putString("key", tagName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
             user = arguments.getString("key");
            }

        }
}

And where your are creating the fragment instead of this :

MyListFragment fragment = new MyListFragment();
                            final Bundle bundle = new Bundle();
                            bundle.putString("key", selState);
                            Log.i("BUNDLE", bundle.toString());
                            fragment.setArguments(bundle);

Use this:

MyListFragment fragment = MyListFragment.newInstance("my_string");

Question was really NOT clear... In adpater:

private MyListFragment fragment;
    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId, MyListFragment myFragment) {
            super(context, R.layout.single_listview_item,planetList);
            this.planetList = planetList;
            this.context = context;
            this.imageId = imageId;
this.fragment = myFragment;
    }

When you need it:

fragment.passValue("my string");

Now in your fragment create the method:

public void passValue(String myString){
//Do whatever with myString
}
Chol
  • 2,097
  • 2
  • 16
  • 26
  • Which adapter?, you just need to pass your string in the newInstance when creating fragment – Chol Jul 26 '16 at 12:37
  • MyListFragment fragment = new MyListFragment(); final Bundle bundle = new Bundle(); bundle.putString("key", selState); Log.i("BUNDLE", bundle.toString()); fragment.setArguments(bundle); THIS STAY IN ADAPTER – markella Jul 26 '16 at 12:38
  • Just replace every thing by the last line I have put : MyListFragment fragment = MyListFragment.newInstance("my_string"); – Chol Jul 26 '16 at 12:38
  • where i must put this MyListFragment fragment = MyListFragment.newInstance("my_string"); ? – markella Jul 26 '16 at 12:41
  • where you need to create your fragment, actually where you put MyListFragment fragment = new MyListFragment(); at first – Chol Jul 26 '16 at 12:44
  • do you have another solution? – markella Jul 26 '16 at 12:45
  • sorry, but i don t understand your answer......can you write it in complete mode? – markella Jul 26 '16 at 12:48
  • Ok add the empty constructor in the fragment, now I need the code where you are creating the fragment – Chol Jul 26 '16 at 12:54
  • after that i create empty constructor what i do? – markella Jul 26 '16 at 12:55
  • and in OnCreateView no need to get the argument again, it is save in string user already – Chol Jul 26 '16 at 12:55
  • Just copy my last line where you are creating the fragment, acutally where you put your MyListFragment fragment = new MyListFragment(); final Bundle bundle = new Bundle(); bundle.putString("key", selState); Log.i("BUNDLE", bundle.toString()); fragment.setArguments(bundle); – Chol Jul 26 '16 at 12:56
  • please, write me complete code and i say you if it works! – markella Jul 26 '16 at 12:57
  • MyListFragment fragment = MyListFragment.newInstance("my_string"); fragment is written in grey because never used – markella Jul 26 '16 at 13:06
  • where do you use fragment after? – Chol Jul 26 '16 at 13:08
  • Are you able to launch the fragment and to see it? – Chol Jul 26 '16 at 13:09
  • If fragment is not launched it is normal you will see nothing printed from the fragment – Chol Jul 26 '16 at 13:09
  • i must pass gray fragment as argument of instanceof? – markella Jul 26 '16 at 13:11
  • Give the complete code where you use MyListFragment fragment = new MyListFragment(); final Bundle bundle = new Bundle(); bundle.putString("key", selState); Log.i("BUNDLE", bundle.toString()); fragment.setArguments(bundle); – Chol Jul 26 '16 at 13:11
  • instead this MyListFragment fragment = new MyListFragment(); final Bundle bundle = new Bundle(); bundle.putString("key", selState); Log.i("BUNDLE", bundle.toString()); fragment.setArguments(bundle); i used only MyListFragment fragment = MyListFragment.newInstance("my_string"); – markella Jul 26 '16 at 13:12
  • First are you able to see the fragment? – Chol Jul 26 '16 at 13:13
  • And after the new instance no more code? but where are you using this fragment? – Chol Jul 26 '16 at 13:15
  • have you another solution to pass parameter? – markella Jul 26 '16 at 13:24
  • But before passing parameter you need to display the fragment... I think your problem is you are not showing the fragment – Chol Jul 26 '16 at 13:26
  • when i click on item of spinner toast show on display the selection and automatically i want pass the selection from adapter to fragment – markella Jul 26 '16 at 13:29
  • In your planet adapter, in constructor pass the "this" as MyListFragment and you will be able to call a fragment method to do what you want – Chol Jul 26 '16 at 13:34
0

This is because you are calling getArguments() in the wrong place.

Override onCreate() and put the code to fetch the value inside it.

 @Override
    public void onCreate(Bundle savedInstanceState) {
            Bundle arguments = getArguments();
            if (arguments != null) {
                    //String userId = arguments.getString("key");
                    //System.out.println("finalmente:"+userId);
                 user = arguments.getString("key");


            } /*else {
                Log.i("BUNDLE == null", "NULL");
            }*/
            //System.out.println("finalmente:"+user);
            Log.e("MESSAGE","finalmente:"+user);

    }
Arpit Ratan
  • 2,976
  • 1
  • 12
  • 20
0

System.out.println("finalmente:"+user); doesn't work in android.

you must use Log.d("MESSAGE","MY MESSAGE");

Bundle arguments = getArguments();
            if (arguments != null) {
                    //String userId = arguments.getString("key");
                    //System.out.println("finalmente:"+userId);
                 user = arguments.getString("key");


            } /*else {
                Log.i("BUNDLE == null", "NULL");
            }*/
           Log.d("finalmente:",""+user);

    }

see answer here Why doesn't “System.out.println” work in Android?

Community
  • 1
  • 1
Md. Nasir Uddin Bhuiyan
  • 1,598
  • 1
  • 14
  • 24
0

You are trying to getArguments() when initiating the Fragment. Better try to handle your Arguments when onViewCreated trigger

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    handleArguments(getArguments());
}

public void handleArguments(Bundle bnd) {
    if (bnd != null) {
         if (bnd.containsKey("key")) {
         user = arguments.getString("key");
         }
    }
System.out.println("finalmente:"+user);
}
Pwnstar
  • 2,333
  • 2
  • 29
  • 52