-2

I'm fairly new to android programming and trying to save data of one (or more) activities to later use them in different activities. My plan was to use sharedPreferences to do that. I created all the variables, etc. but when I want to call the saved Data from the activity C_Produktspezifikation in the activity D_Maschine I get a NullPointerException. Is there a problem with the fragments or anything? I searched the net and tried a lot different things but nothing has worked so far. I hope somebody can help me and explain what my mistake was. Thannks in advance

Here is the first activity with the data:

package com.robomillup.wirtschaftlichkeit;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;


import com.robomillup.wirtschaftlichkeit.DB_Werkstueck.WST_bearbeiten;
import com.robomillup.wirtschaftlichkeit.DB_Werkstueck.WstDBHandler;

import java.util.ArrayList;

public class C_Produktspezifikation extends AppCompatActivity {

    public static final String SHARED_PREFS = "sp_Produktspezifikation";  //Name der shared Prefs für diese Seite
    public static final String WST_NAME = "Wst_Name"; //shared Prefs für Werkstückname
    public static final String SCHNITTWEG = "Schnittweg"; //shared Prefs für Schnittweg
    public static final String LOSGROESSE = "Losgroeße"; //shared Prefs für Losgröße
    public static final String STUECKZAHL = "Stueckzahl"; //shared Prefs für Stückzahl
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_produktspezifikation);


        //region BUTTON DEKLARATION
        Button neuesWST = (Button) findViewById(R.id.btn_Neu_WST);
        neuesWST.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                startActivity(new Intent(C_Produktspezifikation.this,WST_bearbeiten.class));
            }
        });

        Button Weiter = (Button) findViewById(R.id.btn_Produktspezifikation_weiter);
        Weiter.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                saveData_Produktspezifikation();
                startActivity(new Intent(C_Produktspezifikation.this,D_Maschine.class));

            }
        });

        Button Abbrechen = (Button) findViewById(R.id.btn_Produktspezifikation_zurück);
        Abbrechen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                startActivity(new Intent(C_Produktspezifikation.this,B_Auswahl.class));
            }
        });

        //endregion

        SpinnerDatenEinfuegen();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SpinnerDatenEinfuegen();
    }

    //Spinner mit den Daten aus der Werkstückdatenbank füllen
    private void SpinnerDatenEinfuegen() {

       // Elemente zum Spinner hinzufügen

        WstDBHandler dbHandler = new WstDBHandler(this, null, null, 1);
        SQLiteDatabase sqLiteDatabase = dbHandler.getReadableDatabase();
        Cursor cursor = dbHandler.getAllRows(sqLiteDatabase);
        if (cursor.moveToFirst()) {

            Spinner spinner;
            String wstname, schnittweg;
            final ArrayList<String> wstliste = new ArrayList<String>();
            final ArrayList<String> schnittwegliste = new ArrayList<String>();

            do {

                //Werkstücke aus Datenbank lesen
                wstname = cursor.getString(1);
                schnittweg = cursor.getString(2);
                wstliste.add(wstname);
                schnittwegliste.add(schnittweg);

            } while (cursor.moveToNext());

            // dataAdapter zu Spinner hinzufügen
            spinner = (Spinner) findViewById(R.id.spn_wst);
            ArrayAdapter<String> spinner_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, wstliste);
            spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(spinner_adapter);

            //Auswahl von Spinner Daten füllen entsprechende Felder aus
            Spinner spinner1 = (Spinner) findViewById(R.id.spn_wst);
            spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                    wstliste.get(position);

                    TextView gew_werkstueck, gew_schnittweg;

                    gew_werkstueck = (TextView) findViewById(R.id.tv_WST);
                    gew_schnittweg = (TextView) findViewById(R.id.tv_Schnittweg_Eintrag);
                    gew_werkstueck.setText(wstliste.get(position).toString());
                    gew_schnittweg.setText(schnittwegliste.get(position).toString());

                    }

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

                }


            });

        }

    }

    //Daten an die Shared Prefs übergeben
    public void saveData_Produktspezifikation(){


        //Deklaration der Variablen, die an Shared Prefs übergeben werden sollen
        TextView WstName = (TextView) findViewById(R.id.tv_WST);
        TextView Schnittweg = (TextView) findViewById(R.id.tv_Schnittweg_Eintrag);
        EditText Stueckzahl = (EditText) findViewById(R.id.et_Stuekzahl_Eintrag);
        EditText Losgroeße = (EditText) findViewById(R.id.et_losgroeße);

        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); //Mode Private, damit keine andere App unsere Shared Preferences ändern kann
        SharedPreferences.Editor editor = sharedPreferences.edit();

        //Hier werden im Editor der Shared Prefs nun die eigentlichen Daten übergeben
        editor.putString(WST_NAME, WstName.getText().toString());
        editor.putString(SCHNITTWEG, Schnittweg.getText().toString());
        editor.putString(STUECKZAHL, Stueckzahl.getText().toString());
        editor.putString(LOSGROESSE, Losgroeße.getText().toString());

        editor.apply();

    }



}

And this is the second activity which is supposed to load the data and insert it into some textviews:

package com.robomillup.wirtschaftlichkeit;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.robomillup.wirtschaftlichkeit.DB_Bearbeitungsmaschine.MaschineDBHandler;
import com.robomillup.wirtschaftlichkeit.DB_Bearbeitungsmaschine.Bearbeitungsmaschine_bearbeiten;

import static com.robomillup.wirtschaftlichkeit.C_Produktspezifikation.LOSGROESSE;
import static com.robomillup.wirtschaftlichkeit.C_Produktspezifikation.SCHNITTWEG;
import static com.robomillup.wirtschaftlichkeit.C_Produktspezifikation.SHARED_PREFS;

public class D_Maschine extends AppCompatActivity {

    private static String sp_Schnittweg;
    private static String sp_Losgroesse;

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_maschine);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container_maschine);
        mViewPager.setAdapter(mSectionsPagerAdapter);

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

        //region BUTTON DEKLARATION REGION

        //Weiter Button

        Button Weiter = (Button) findViewById(R.id.btn_maschine_weiter);
        Weiter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    Intent i = new Intent(D_Maschine.this, E_Werkzeug.class);
                    startActivity(i);
            }
        });

       //Zurück Button
        Button Abbrechen = (Button) findViewById(R.id.btn_maschine_zurück);
        Abbrechen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(D_Maschine.this, C_Produktspezifikation.class);
                startActivity(i);

            }
        });

        //endregion

        loadData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_varianten, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }
    // Definitionen, was in den einzelnen Tabs zu sehen ist und passiert

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Definition von Inhalt und so von Fragment 1

            if (getArguments().getInt(ARG_SECTION_NUMBER) == 1){
                final View rootView = inflater.inflate(R.layout.fragment_maschine_variante_1, container, false);


                   // Button für neues Werkstück
               Button neuesWst = (Button) rootView.findViewById(R.id.btn_v1_Neu_Maschine);
               neuesWst.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       Intent i = new Intent(getActivity(), Bearbeitungsmaschine_bearbeiten.class);
                       startActivity(i);
                   }
               });

                //region SPINNER BEFUELLEN REGION

                 MaschineDBHandler dbHandler = new MaschineDBHandler(getActivity(), null, null, 2);
                 SQLiteDatabase sqLiteDatabase = dbHandler.getReadableDatabase();
                 Cursor cursor = dbHandler.getAllRows(sqLiteDatabase);
                if (cursor.moveToFirst()) {

                    Spinner spinner;
                    String maschinenname, anschaffungswert, raumbedarf, el_anschlusswert;
                    final ArrayList<String> maschineliste = new ArrayList<String>();
                    final ArrayList<String> anschaffungswertliste = new ArrayList<String>();
                    final ArrayList<String> raumbedarfliste = new ArrayList<String>();
                    final ArrayList<String> el_anschlusswertliste = new ArrayList<String>();

                    do {

                     //Bearbeitungsmaschine aus Datenbank lesen
                     maschinenname = cursor.getString(1);
                     anschaffungswert = cursor.getString(2);
                     raumbedarf = cursor.getString(3);
                        el_anschlusswert = cursor.getString(4);
                     maschineliste.add(maschinenname);
                        anschaffungswertliste.add(anschaffungswert);
                        raumbedarfliste.add(raumbedarf);
                        el_anschlusswertliste.add(el_anschlusswert);

                    } while (cursor.moveToNext());

                 // dataAdapter zu Spinner hinzufügen
                 spinner = (Spinner) rootView.findViewById(R.id.sp_v1_Maschine);
                 ArrayAdapter<String> spinner_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, maschineliste);
                 spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                 spinner.setAdapter(spinner_adapter);

                    //Auswahl von Spinner Daten füllen entsprechende Felder aus
                    Spinner spinner1 = (Spinner) rootView.findViewById(R.id.sp_v1_Maschine);
                 spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                       @Override
                     public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                         maschineliste.get(position);

                         TextView gew_maschine, gew_anschaffungswert, gew_raumbedarf, gew_el_anschlusswert;

                         gew_maschine = (TextView) rootView.findViewById(R.id.tv_v1_Maschine);
                         gew_anschaffungswert = (TextView) rootView.findViewById(R.id.et_v1_Werkzeug_Standweg_Eintrag);
                         gew_raumbedarf = (TextView) rootView.findViewById(R.id.tv_v1_Werkzeug_Schnittweg_Eintrag);
                         gew_el_anschlusswert = (TextView) rootView.findViewById(R.id.tv_m_v1_el_Anschlusswert_Eintrag);

                         gew_maschine.setText(maschineliste.get(position).toString());
                         gew_anschaffungswert.setText(anschaffungswertliste.get(position).toString());
                         gew_raumbedarf.setText(raumbedarfliste.get(position).toString());
                         gew_el_anschlusswert.setText(el_anschlusswertliste.get(position).toString());

                                    }

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

                     }


                    });

                }



                     //endregion


                return rootView;

            }

            //Definition von Inhalt und so von Fragment 2
            else {
                final View rootView = inflater.inflate(R.layout.fragment_maschine_variante_2, container, false);

                 // Button für neues Werkstück
                Button neuesWst = (Button) rootView.findViewById(R.id.btn_v2_Neu_Maschine);
                neuesWst.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(getActivity(), Bearbeitungsmaschine_bearbeiten.class);
                        startActivity(i);
                    }
                });

                //region SPINNER BEFUELLEN REGION

                MaschineDBHandler dbHandler = new MaschineDBHandler(getActivity(), null, null, 2);
                SQLiteDatabase sqLiteDatabase = dbHandler.getReadableDatabase();
                Cursor cursor = dbHandler.getAllRows(sqLiteDatabase);
                if (cursor.moveToFirst()) {

                    Spinner spinner;
                    String maschinenname, anschaffungswert, raumbedarf, el_anschlusswert;
                    final ArrayList<String> maschineliste = new ArrayList<String>();
                    final ArrayList<String> anschaffungswertliste = new ArrayList<String>();
                    final ArrayList<String> raumbedarfliste = new ArrayList<String>();
                    final ArrayList<String> el_anschlusswertliste = new ArrayList<String>();

                    do {

                        //Bearbeitungsmaschine aus Datenbank lesen
                        maschinenname = cursor.getString(1);
                        anschaffungswert = cursor.getString(2);
                        raumbedarf = cursor.getString(3);
                        el_anschlusswert = cursor.getString(4);
                        maschineliste.add(maschinenname);
                        anschaffungswertliste.add(anschaffungswert);
                        raumbedarfliste.add(raumbedarf);
                        el_anschlusswertliste.add(el_anschlusswert);

                    } while (cursor.moveToNext());

                    // dataAdapter zu Spinner hinzufügen
                    spinner = (Spinner) rootView.findViewById(R.id.sp_m_v2_Maschine);
                    ArrayAdapter<String> spinner_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, maschineliste);
                    spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner.setAdapter(spinner_adapter);

                    //Auswahl von Spinner Daten füllen entsprechende Felder aus
                    Spinner spinner1 = (Spinner) rootView.findViewById(R.id.sp_m_v2_Maschine);
                    spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                            maschineliste.get(position);

                            TextView gew_maschine, gew_anschaffungswert, gew_raumbedarf, gew_el_anschlusswert;

                            gew_maschine = (TextView) rootView.findViewById(R.id.tv_m_v2_Maschine);
                            gew_anschaffungswert = (TextView) rootView.findViewById(R.id.tv_m_v2_Anschaffungswert_Eintrag);
                            gew_raumbedarf = (TextView) rootView.findViewById(R.id.tv_m_v2_Raumbedarf_Eintrag);
                            gew_el_anschlusswert = (TextView) rootView.findViewById(R.id.tv_m_v2_el_Anschlusswert_Eintrag);

                            gew_maschine.setText(maschineliste.get(position).toString());
                            gew_anschaffungswert.setText(anschaffungswertliste.get(position).toString());
                            gew_raumbedarf.setText(raumbedarfliste.get(position).toString());
                            gew_el_anschlusswert.setText(el_anschlusswertliste.get(position).toString());

                        }

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

                        }


                    });

                }



                //endregion

                return rootView;
            }

        }

    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        // Anzahl der Tabs
        @Override
        public int getCount() {
            return 2;
        }

        //Benennung der einzelnen Tabs
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Variante 1";
                case 1:
                    return "Variante 2";
            }
            return null;
        }
    }

    public void loadData(){
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
        sp_Schnittweg = sharedPreferences.getString(SCHNITTWEG, "");
        sp_Losgroesse = sharedPreferences.getString(LOSGROESSE, "");

        TextView textView = (TextView) findViewById(R.id.tv_m_v1_Anschaffungswert_Eintrag);
        TextView tv2 =(TextView) findViewById(R.id.tv_m_v1_Raumbedarf_Eintrag);

        textView.setText(sp_Schnittweg);
        tv2.setText(sp_Losgroesse);
    }
}

EDIT: The implemented methods for saving the data (in C_Produktspezifikation) and loading the data (and displaying it in TextViews) in D_Maschine. The Helper class is exactly like the one in the first answer only write_to_key is changed to saveData and read_from_key is changed to load Data

 public void saveData_Produktspezifikation(){

        TextView Schnittweg = (TextView) findViewById(R.id.tv_Schnittweg_Eintrag);
        EditText Losgroeße = (EditText) findViewById(R.id.et_losgroeße);

        XX_Datenspeicher sharePref = new XX_Datenspeicher(this);
        String sp_Schnittweg = sharePref.saveData("sp_Produktspezifikation", "SCHNITTWEG", Schnittweg.getText().toString());
        String sp_Losgroesse = sharePref.saveData("sp_Produktspezifikation", "LOSGROESSE", Losgroeße.getText().toString());


    }

public void loadData(){

        XX_Datenspeicher sharePref = new XX_Datenspeicher(this);
        String sp_Schnittweg = sharePref.loadData("sp_Produktspezifikation", "SCHNITTWEG");
        String sp_Losgroesse = sharePref.loadData("sp_Produktspezifikation", "LOSGROESSE");

        TextView textview = (TextView) findViewById(R.id.tv_m_v1_Anschaffungswert_Eintrag);
        TextView tv2 = (TextView) findViewById(R.id.tv_m_v1_Raumbedarf_Eintrag);
        textview.setText(SCHNITTWEG);
        tv2.setText(LOSGROESSE);
    }
Steck84
  • 17
  • 1
  • 5

1 Answers1

0

Try creating a helper class and pass in the context.

import android.content.Context;
import android.content.SharedPreferences;
import static android.content.Context.MODE_PRIVATE;

public class SharedPref {

private Context mContext;

public SharedPref(Context context){
    mContext = context;
  }

public void write_to_key(String shared_pref, String pref_key, String value_of_key) {
    //This block of code will automatically store the key and value in the shared preferences
    //All you need to do is provide the sharedpreference, the key you wish to save the value as, and the value
    SharedPreferences sharedpreferences = mContext.getSharedPreferences(shared_pref, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(pref_key, value_of_key);
    editor.commit();
  }

public String read_from_key(String shared_pref, String pref_key) {
    //This block of code will automatically read the value in the shared preferences with the provided key
    //All you need to do is provide the key you want to read and the value will be returned as a string
    SharedPreferences shared = mContext.getSharedPreferences(shared_pref, MODE_PRIVATE);
    return (shared.getString(pref_key, ""));
  }

}

Pass context in constructor

SharedPref sharePref = new SharedPref(this);
String sp_Schnittweg = sharePref.read_from_key("sp_Produktspezifikation", "SCHNITTWEG");
String sp_Losgroesse = sharePref.read_from_key("sp_Produktspezifikation", "LOSGROESSE");
Jantzilla
  • 638
  • 1
  • 7
  • 19
  • Thanks for the answer Jantzilla, but I'm a little confused now. I created the helper class (which was a very good idea). In my first activity (C_Produktspezifikation) I have to put the write_to_key in the on create part and the read _from_key in my second activity (D_Maschine), right? I'm struggling with the value_of_key input. In my case it should be the String in a Textview. But when I put .getText().toString() I encounter problems. Where does my mind mess things up? – Steck84 Jun 18 '18 at 08:02
  • It sounds like you are implementing it correctly. I'm not sure what you mean by problems. Try checking that your `TextView` isn't null and it to a class variable first. – Jantzilla Jun 18 '18 at 10:28
  • Hey Jantzilla. Sorry for not answering sooner. I edited my question and showed the method to load and save the data. The two methods are both called last in the on create portion of the activities. When I run the app I get a nullpointer exception from the textviews where they are supposed to be displayed and I can't find the reason why. – Steck84 Jun 20 '18 at 07:59