0

Getting Null while reading data from shared preference in another activity for the first time and second time its showing the value i have passed the entire json object to another activity via intent but didnt resolve my problem i have tried using volley library as well please help

public class MainActivity extends AppCompatActivity {
TextInputEditText name, addresssss, address1111, city, state, country, postalcode, landmark,mobiles;
TextView namee, addresss, address11, cityy, statee, countryy, postalcodee, landmarkk,hhhh;
String nameee, nam, ad, ad1, ci, sta, cou, pos, land, nameeee;
Button Submit;
String ggg;
JSONObject object;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    namee = (TextView) findViewById(R.id.namee);
    landmarkk = (TextView) findViewById(R.id.landmarkk);
    addresss = (TextView) findViewById(R.id.addresss);
    address11 = (TextView) findViewById(R.id.address11);
    cityy = (TextView) findViewById(R.id.cityy);
    statee = (TextView) findViewById(R.id.statee);
    countryy = (TextView) findViewById(R.id.countryy);
    postalcodee = (TextView) findViewById(R.id.postalcodee);
    hhhh=(TextView)findViewById(R.id.hhhh);
    mobiles=(TextInputEditText)findViewById(R.id.mobiles);
    name = (TextInputEditText) findViewById(R.id.name);
    addresssss = (TextInputEditText) findViewById(R.id.address);
    address1111 = (TextInputEditText) findViewById(R.id.address1);
    city = (TextInputEditText) findViewById(R.id.city);
    state = (TextInputEditText) findViewById(R.id.state);
    country = (TextInputEditText) findViewById(R.id.country);
    postalcode = (TextInputEditText) findViewById(R.id.postalcode);
    landmark = (TextInputEditText) findViewById(R.id.landmark);
    Submit = (Button) findViewById(R.id.Submit);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    Submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new SendRequest().execute();
            nameee = name.getText().toString().trim();
            if (TextUtils.isEmpty(name.getText().toString())) {


                return;


            }
            ad = addresssss.getText().toString();
            if (TextUtils.isEmpty(addresssss.getText().toString())) {


                return;

            }
            ad1 = address1111.getText().toString();
            if (TextUtils.isEmpty(address1111.getText().toString())) {


                return;

            }
            ci = city.getText().toString();
            if (TextUtils.isEmpty(city.getText().toString())) {


                return;

            }
            sta = state.getText().toString();
            if (TextUtils.isEmpty(state.getText().toString())) {


                return;

            }
            cou = country.getText().toString();
            if (TextUtils.isEmpty(country.getText().toString())) {


                return;

            }
           pos = postalcode.getText().toString();
            if (TextUtils.isEmpty(postalcode.getText().toString())) {


                return;

            }
            land = landmark.getText().toString().trim();
            if (TextUtils.isEmpty(landmark.getText().toString())) {


                return;

            }
            nameeee=mobiles.getText().toString().trim();

            if (TextUtils.isEmpty(mobiles.getText().toString())) {


                return;

            }
            else {


                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(intent);
            }


        }
    });
}
public class SendRequest extends AsyncTask<String, Void, String> {

    protected void onPreExecute() {
    }

    protected String doInBackground(String... arg0) {


        try {

            URL url = new URL("http://services.sweken.com/api2/information/checkRegionByPincode");

            JSONObject postDataParams = new JSONObject();



            postDataParams.put("address", ad);
            postDataParams.put("address_1", ad1);
            postDataParams.put("pincode", pos);
            postDataParams.put("land_mark", land);
            postDataParams.put("name", nameee);
            postDataParams.put("mobile_no", nameeee);


            Log.e("params", postDataParams.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds *);
                 conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();

            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line = "";

                while ((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            } else {
                return new String("false : " + responseCode);
            }
        } catch (Exception e) {

            return new String("Exception: " + e.getMessage());

        }
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            object = new JSONObject(result);
            ggg = object.getString("customer_id");
            Log.d("customer",ggg);
            SharedPreferences.Editor editt = sharedPreferences.edit();
            editt.putString("CUSTOMER_ID", ggg);
            editt.apply();


        } catch (JSONException e) {
            e.printStackTrace();
        }



    }



}


public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while (itr.hasNext()) {

        String key = itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}

}

Here is the second Activity where i am reading the value from shared preference i am getting null for first time second time its reading the value

 public class Main2Activity extends AppCompatActivity {
String idddd;
TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        text=(TextView)findViewById(R.id.text);
        SharedPreferences sharedPreferences = 
        PreferenceManager.getDefaultSharedPreferences(this);

       `idddd = sharedPreferences.getString`("CUSTOMER_ID","");
        text.setText(idddd);
    }
}
  • Post the whole flow where are you exactly reading it ? – ADM Feb 18 '18 at 05:38
  • Thats the code i have been using i am saving json response in string variable and saving the variable response in shared preference the data is been saved successfully i have checked in device file explorer but when i read the saved data in another activity i am getting null for first time when i open the app again its showing the value dont know whats wrong in my code – Tirumalesh kallepalli Feb 18 '18 at 05:43
  • Debug `onPostExecute()` make sure the data is saved . And also in `SharedPreferences` there is never returned `null` unless the default value or the data itself is `null`. – ADM Feb 18 '18 at 05:45
  • Instead of apply(), use commit() and set it to a boolean value; once done, print out the value to confirm it saved. https://stackoverflow.com/a/5960732/2480714 – PGMacDesign Feb 18 '18 at 06:04
  • String id = sharedPreferences.getString("CUSTOMER_ID", "CUSTOMER_ID"); should be String id = sharedPreferences.getString("CUSTOMER_ID", null); – EL TEGANI MOHAMED HAMAD GABIR Feb 18 '18 at 07:19
  • All elements and explanation should be in your question post. I can't even read a question in there. – PJProudhon Feb 18 '18 at 09:02
  • i have posted the complete code please help me on this error thanks – Tirumalesh kallepalli Feb 20 '18 at 06:15

1 Answers1

0

Sounds like a race condition since the write to SharedPreference occurs at the end of an AsyncTask. It's hard to tell without seeing more code. Try placing breakpoints, or trying to read from shared preferences directly after writing to it, or creating an OnSharedPreferenceChangeListener to ensure that data is being written to it all.

Steve
  • 538
  • 4
  • 17