在另一个活动中首次从SharedPreference打印数据时获取NullpointerException

时间:2018-02-18 14:05:59

标签: android sharedpreferences

  

这是代码我第一次没有从共享偏好中获得任何其他活动的任何值,即使json响应已保存在资源管理器中但是当我再次单击该按钮并再次进入该活动时我得到了价值,但我第一次没有得到任何价值,请帮助谢谢

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();
}

}

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);
}

}

1 个答案:

答案 0 :(得分:0)

问题是,您在单击按钮时执行网络呼叫,并且直接启动新意图而不等待网络呼叫的响应,因此第一次无法正常工作。< / p>

解决方案是在提交按钮的onClick验证内容中链接操作。

要链接操作,请像这样提取此代码块,

public void goToNextActivity(){
    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);
        }
}

然后从asynctask的protected void onPostExecute(String result)调用此方法。

@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();

       //**after all needed data is persisted to preferences.**
       goToNextActivity();
    } catch (JSONException e) {
        e.printStackTrace();
    }



}

希望得到这个帮助。