FATAL EXCEPTION:main java.lang.NullPointerException:尝试调用虚拟m

时间:2015-10-31 06:25:15

标签: android sms

大家好,我正在开发一个Rechargeapp refrence第一个活动参考,如this

但只提供一个按手机号码注册的字段

但我得到错误

我的错误是打击

http://localhost:4000/

SMSActivity

FATAL EXCEPTION: main
 Process: com.example.com.sms_sending, PID: 2036
 java.lang.NullPointerException: Attempt to invoke virtual method 'void   com.example.com.sms_sending.app.MyApplication.addToRequestQueue(com.android.volley.Request)' on a null object reference
 at com.example.com.sms_sending.activity.SmsActivity.requestForSMS(SmsActivity.java:217)
 at com.example.com.sms_sending.activity.SmsActivity.validateForm(SmsActivity.java:139)
 at com.example.com.sms_sending.activity.SmsActivity.onClick(SmsActivity.java:107)
 at android.view.View.performClick(View.java:4780)
 at android.view.View$PerformClick.run(View.java:19866)
 at android.os.Handler.handleCallback(Handler.java:739)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:135)
 at android.app.ActivityThread.main(ActivityThread.java:5254)
 at java.lang.reflect.Method.invoke(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:372)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

请求队列

public class SmsActivity extends AppCompatActivity implements View.OnClickListener{
private static String TAG = SmsActivity.class.getSimpleName();
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private Button btnRequestSms, btnVerifyOtp;
private EditText inputName, inputEmail, inputMobile, inputOtp;
private ProgressBar progressBar;
private MyApplication newapp;
private PrefManager pref;
private ImageButton btnEditMobile;
private TextView txtEditMobile;
private LinearLayout layoutEditMobile;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sms);
    viewPager = (ViewPager) findViewById(R.id.viewPagerVertical);
    inputMobile = (EditText) findViewById(R.id.inputMobile);
    inputOtp = (EditText) findViewById(R.id.inputOtp);
    btnRequestSms = (Button) findViewById(R.id.btn_request_sms);
    btnVerifyOtp = (Button) findViewById(R.id.btn_verify_otp);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    btnEditMobile = (ImageButton) findViewById(R.id.btn_edit_mobile);
    txtEditMobile = (TextView) findViewById(R.id.txt_edit_mobile);
    layoutEditMobile = (LinearLayout) findViewById(R.id.layout_edit_mobile);
            // view click listeners
    btnEditMobile.setOnClickListener(this);
    btnRequestSms.setOnClickListener(this);
    btnVerifyOtp.setOnClickListener(this);
             // hiding the edit mobile number
    layoutEditMobile.setVisibility(View.GONE);
    pref = new PrefManager(this);
    if (pref.isLoggedIn()) {
        Intent intent = new Intent(SmsActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
    adapter = new ViewPagerAdapter();
    viewPager.setAdapter(adapter);
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
        @Override
        public void onPageSelected(int position) {
        }
        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
    /**
     * Checking if the device is waiting for sms
     * showing the user OTP screen
     */
    if (pref.isWaitingForSms()) {
        viewPager.setCurrentItem(1);
        layoutEditMobile.setVisibility(View.VISIBLE);
    }
}
@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btn_request_sms:
            validateForm();////333333 error
            break;
        case R.id.btn_verify_otp:
            verifyOtp();
            break;
        case R.id.btn_edit_mobile:
            viewPager.setCurrentItem(0);
            layoutEditMobile.setVisibility(View.GONE);
            pref.setIsWaitingForSms(false);
            break;
    }
}
/**
 * Validating user details form
 */
private void validateForm() {
    String mobile = inputMobile.getText().toString().trim();
    if (isValidPhoneNumber(mobile)) {
        // request for sms
        progressBar.setVisibility(View.VISIBLE);
        // saving the mobile number in shared preferences
        pref.setMobileNumber(mobile);
        // requesting for sms
        requestForSMS(mobile); /////22222222222 error
    } else {
        Toast.makeText(getApplicationContext(), "Please enter valid mobile number", Toast.LENGTH_SHORT).show();
    }
}
/**
 * Method initiates the SMS request on the server
 *
 * @param mobile user valid mobile number
 */
private void requestForSMS(final String mobile) {
    StringRequest strReq = new StringRequest(Request.Method.POST,
            config.Config.URL_REQUEST_SMS, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response.toString());
            try {
                JSONObject responseObj = new JSONObject(response);
                boolean error = responseObj.getBoolean("error");
                String message = responseObj.getString("message");
                if (!error) {
                    pref.setIsWaitingForSms(true);
                    viewPager.setCurrentItem(1);
                    txtEditMobile.setText(pref.getMobileNumber());
                    layoutEditMobile.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Error: " + message,
                            Toast.LENGTH_LONG).show();
                }
                // hiding the progress bar
                progressBar.setVisibility(View.GONE);
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(),
                        "Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
                progressBar.setVisibility(View.GONE);
            }
            Toast.makeText(getApplicationContext(),"Hello Here is Problem"+response,Toast.LENGTH_LONG).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
    }) {
        /**
         * Passing user parameters to our server
         * @return
         */
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("key","xxxxxxxxxxxxx");
            params.put("mobile", mobile);
            Log.e(TAG, "Posting params: " + params.toString());
            return params;
        }
    };
    int socketTimeout = 60000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    strReq.setRetryPolicy(policy);

    // Adding request to request queue
  newapp.getInstance().addToRequestQueue(strReq); /////// 11111111111
}

/**
 * sending the OTP to server and activating the user
 */
private void verifyOtp() {
    String otp = inputOtp.getText().toString().trim();

    if (!otp.isEmpty()) {
        Intent grapprIntent = new Intent(getApplicationContext(), HttpService.class);
        grapprIntent.putExtra("otp", otp);
        startService(grapprIntent);
    } else {
        Toast.makeText(getApplicationContext(), "Please enter the OTP", Toast.LENGTH_SHORT).show();
    }
}

/**
 * Regex to validate the mobile number
 * mobile number should be of 10 digits length
 *
 * @param mobile
 * @return
 */
private static boolean isValidPhoneNumber(String mobile) {
    String regEx = "^[0-9]{10}$";
    return mobile.matches(regEx);
}


class ViewPagerAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((View) object);
    }

    public Object instantiateItem(View collection, int position) {

        int resId = 0;
        switch (position) {
            case 0:
                resId = R.id.layout_sms;
                break;
            case 1:
                resId = R.id.layout_otp;
                break;
        }
        return findViewById(resId);
    }
  }
 }

清单

public class MyApplication extends Application {

    public static final String TAG = MyApplication.class
            .getSimpleName();

    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
  }

请帮助我,我试了4天

2 个答案:

答案 0 :(得分:1)

打开位于app文件夹下的 build.gradle ,然后添加

com.mcxiaoke,添加 排球 库相关性。凌空:库AAR:1.0.0

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "com.android.support:appcompat-v7:22.1.1"
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

答案 1 :(得分:0)

与日志一样:

  

NullPointerException:尝试调用虚方法'void
  com.example.com.sms_sending.app.MyApplication.addToRequestQueue(com.android.volley.Request)”   在空对象引用上

表示由sourceArray.Length * sizeof(type)类引起的getInstance()方法返回null未被系统用作MyApplication类。

Application中未添加AndroidManifest.xml名称属性。这样做:

MyApplication