-2

I have a spinner populated from DB in toolbars onCreateOptionsMenu of an ViewPager and I want to pass it's value in to fragment.

What I want to achieve is to change fragments content based on spinner value. I tried to pass this value via Bundle but it throws me null object reference...

I bet its because fragment and it's stuff is loaded faster than my spinner is geting its value in to Bundle. Even so I have no clue how to pass this value there in correct way...

Thanks in advance for any help!

EDIT:

I find a way to solve problem but i hit another one. I can't sent valute to the activity other than null.

ChartsActivity.java

public class ChartsAcivity extends AppCompatActivity {

Context context = this;
int selected_car_id = 0;
DBHelper dbHelper;
String spinnerValue = null;

private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if (getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    Chart1Activity chart1 = (Chart1Activity) mSectionsPagerAdapter.getItem(0);
    if (spinnerValue != null) chart1.respond("test");
    else chart1.respond("OMG EMPTY AGAIN?!?!");

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_charts_acivity, menu);
    MenuItem carSpinner = menu.findItem(R.id.charts_activ_car_spinner);
    Spinner CarRefuelListSpinner = (Spinner) MenuItemCompat.getActionView(carSpinner);
    SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
    Cursor spinner_cursor = db.rawQuery("SELECT " + TableCar.NewCar.CAR_ID + " AS _id, " + TableCar.NewCar.CAR_NAME + " FROM " + TableCar.NewCar.TABLE_NAME, null);

    if(spinner_cursor.moveToFirst()) {

        String[] from = new String[]{TableCar.NewCar.CAR_NAME};
        int[] to = new int[]{android.R.id.text1};

        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, spinner_cursor, from, to);
        simpleCursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        CarRefuelListSpinner.setAdapter(simpleCursorAdapter);

        CarRefuelListSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);

                selected_car_id = Integer.valueOf(String.valueOf(id));

                String s = String.valueOf(selected_car_id);
                getSpinnerVal(s);
                //chart1.respond("test");


                //Chart1Activity chart1 = (Chart1Activity) mSectionsPagerAdapter.getItem(0);
                //chart1.respond(s);

            }

            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    else {
        ...
    }


    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    switch (item.getItemId()) {
        case android.R.id.home:

            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void getSpinnerVal (String value){

    spinnerValue = value;

}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {


        switch (position){
            case 0:
                Chart1Activity chart1 = new Chart1Activity();
                return chart1;

            case 1:
                Chart2Activity chart2 = new Chart2Activity();
                return chart2;

            case 2:
                Chart3Activity chart3 = new Chart3Activity();
                return chart3;

            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "TEST 1";
            case 1:
                return "TEST 2";
            case 2:
                return "TEST 3";
        }
        return null;
    }
}
}

Chart1Activity.java

public class Chart1Activity extends Fragment implements FragmentCommunicator{

Context context;// = getActivity();
DBHelper dbHelper;
LineChart chart;
String car_id = null;
String test = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.chart1_fragment, container, false);

    if (car_id != null) {
        chart = (LineChart) getActivity().findViewById(R.id.chart1_line_fuel_usage);
        Toast.makeText(getActivity(), "ID = " + car_id, Toast.LENGTH_LONG).show();
        setData(car_id);
    }
    else Toast.makeText(getActivity(), "ID = null", Toast.LENGTH_LONG).show();

    return rootView;
}

@Override
public void respond(String data) {
    car_id = data;
}

public void setData(String car_id){

    dbHelper = new DBHelper(context);

    Cursor curChartFuelUsage = dbHelper.getChartFuelUsage(car_id);
    curChartFuelUsage.moveToFirst();

    int count = curChartFuelUsage.getCount();
    final String[] x_refuel_data = new String[count];
    final String[] x2_refuel_data = new String[count];
    Float[] y_fuel_usage = new Float[count];


    if (curChartFuelUsage.moveToFirst()){

        for (int i = 0 ; i < count ; i++){

            x_refuel_data[i] = curChartFuelUsage.getString(0);
            x2_refuel_data[i] = x_refuel_data[i].replace("-", "/");

            y_fuel_usage[i] = curChartFuelUsage.getFloat(1);
            curChartFuelUsage.moveToNext();
        }

        ArrayList<Entry> values = new ArrayList<Entry>();

        for (int i = 0 ; i < count ; i++){
            values.add(new Entry(i, y_fuel_usage[i]));
        }

        LineDataSet set1 = new LineDataSet(values,"test");
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        set1.setColors(new int[]{R.color.chartRed}, context);

        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        dataSets.add(set1);

        LineData lineData = new LineData(dataSets);
        chart.setData(lineData);

        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return x2_refuel_data[(int)value];
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        };

        chart.getXAxis().setValueFormatter(formatter);
        chart.invalidate();


    }
    else Toast.makeText(context, "xxx.", Toast.LENGTH_LONG).show();

}
}

FragmentCommunicator.java

public interface FragmentCommunicator {

    public void respond (String data);
}

error

relliz
  • 19
  • 7
  • Possible duplicate of [Avoiding != null statements](http://stackoverflow.com/questions/271526/avoiding-null-statements) – Chisko Jan 23 '17 at 23:14

1 Answers1

0

This is the same as communication between fragments ... I suggest you watch this video about Fragment Communication. I'm sure it will help you a lot and make your code more organized

MohammedAlSafwan
  • 872
  • 1
  • 8
  • 25
  • Edited my post. I found that i needed to use interface to send value from Activity to fragment but I can't find out why Im sending null value all the time... – relliz Feb 11 '17 at 00:17
  • you are doing it the other way around ... your Activity should implement the `FragmentCommunicator` and your fragment should have a field of interface `FragmentCommunicator` that you declare inside of OnAttach(Context context) that you override <<<< this is how you send data from a fragment to an activity – MohammedAlSafwan Feb 11 '17 at 01:25
  • sending data from an activity to a fragment is different. you have to get your fragmentManager in your activity and look through it. if you find the fragment then just call the method from it after you cast it to your fragment – MohammedAlSafwan Feb 11 '17 at 01:28
  • if you don't find the fragment or got a nullPointerException from the fragmentManager when you pass it the tag, then you simply created the fragment and then you pass your data to it – MohammedAlSafwan Feb 11 '17 at 01:31
  • I understad what you said (hopefully) so because I want to pass value from Activity to fragment I realized that I dont even need this interfaceso I just created a method in my fragment and named it setCarID(int id). Then in Activity I have this line Chart1Activity chart1 = (Chart1Activity) mSectionsPagerAdapter.getItem(0); in onCrate which gives me reference to the fragment. Then from my Activity Im doing chart1.setCarID(spinnerValue) if it is not null - And its, not passing the value at all.. – relliz Feb 11 '17 at 18:24
  • Basically what I want to achieve is by changing my toolbar spinner which I create in onCreateOptionsMenu, I want it to pass the id of an car to the method in the fragments to draw the chart with setData method. Im stuck with this for a while now and think Im doing sth wrong with passing the data from toolbar spinner to the ViewPager fragments... I bet is sth different than passing it to the normal fragment but I cannot find out what. – relliz Feb 11 '17 at 18:24
  • since you are using ViewPager, you in your Activity ask your fragmentManager for your ViewPager and if null, then build ViewPager. if not null, then ask the pager for to get the fragment by calling the method getItem. Now you cast what you get from the method to your wanted fragment, then call the method you want. – MohammedAlSafwan Feb 11 '17 at 18:26
  • do you wanna go on hangout for more help ? – MohammedAlSafwan Feb 11 '17 at 18:28
  • I sent you an invite ... you can remove your comment :) – MohammedAlSafwan Feb 11 '17 at 19:14