Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/216.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java android中带有json的NullPointerException错误_Java_Android - Fatal编程技术网

Java android中带有json的NullPointerException错误

Java android中带有json的NullPointerException错误,java,android,Java,Android,我知道StackOverFlow中有很多关于这个错误的解释。但我花了无数个小时试图解决代码中的这个错误,但我做不到。我是android编程新手。希望你们能帮忙 我试图在这个android应用程序中使用PHP将数据存储在MySQL中 这是我的主要活动 public class MainActivity extends ActionBarActivity implements View.OnClickListener { private EditText userName, userCon

我知道StackOverFlow中有很多关于这个错误的解释。但我花了无数个小时试图解决代码中的这个错误,但我做不到。我是android编程新手。希望你们能帮忙

我试图在这个android应用程序中使用PHP将数据存储在MySQL中

这是我的主要活动

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private EditText userName, userContact, userAddress, userRequest;
    private Spinner userStore;
    private Button mRegister;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    //php login script

    //localhost :
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";

    //testing on Emulator:
    private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";

    //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";

    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
        String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
        dropdown.setAdapter(adapter);

        userName = (EditText)findViewById(R.id.EditName);
        userContact = (EditText)findViewById(R.id.EditContact);
        userAddress = (EditText)findViewById(R.id.EditAddress);
        userStore = (Spinner)findViewById(R.id.StoreSpinner);
        userRequest = (EditText)findViewById(R.id.EditRequest);

        mRegister = (Button)findViewById(R.id.SubmitButton);
        mRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        new CreateUser().execute();

    }

    class CreateUser extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Creating Request...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            String username = userName.getText().toString();
            String usercontact = userContact.getText().toString();
            String useraddress = userAddress.getText().toString();
            String userstore = userStore.getSelectedItem().toString();
            String userrequest = userRequest.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("userName", username));
                params.add(new BasicNameValuePair("userContact", usercontact));
                params.add(new BasicNameValuePair("userAddress", useraddress));
                params.add(new BasicNameValuePair("userStore", userstore));
                params.add(new BasicNameValuePair("userRequest", userrequest));

                Log.d("request!", "starting");

                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(
                        LOGIN_URL, "POST", params);

                // full json response
                Log.d("Login attempt", json.toString());


                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created!", json.toString());
                    finish();
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

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

            return null;

        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}
公共类MainActivity扩展了ActionBarActivity实现了View.OnClickListener{
私有EditText用户名、userContact、userAddress、userRequest;
私有微调器用户存储;
私人按钮注册器;
//进度对话框
私人对话;
//JSON解析器类
JSONParser JSONParser=新的JSONParser();
//php登录脚本
//本地主机:
//在您的设备上进行测试
//将本地ip改为在windows上运行CMD>ipconfig
//或者在mac的终端类型ifconfig中,查找en0或en1下的ip
//私有静态最终字符串登录\u URL=”http://xxx.xxx.x.x:1234/webservice/register.php";
//在模拟器上测试:
私有静态最终字符串登录\u URL=”http://10.0.2.2/callarocket/register.php";
//从真实服务器进行测试:
//私有静态最终字符串登录\u URL=”http://www.yourdomain.com/webservice/register.php";
//身份证
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_MESSAGE=“MESSAGE”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
微调器下拉列表=(微调器)findViewById(R.id.StoreSpinner);
字符串[]项=新字符串[]{“NZ Mamak”、“Indo Shop”、“NZ超市”};
ArrayAdapter=新的ArrayAdapter(这个,android.R.layout.simple\u微调器\u项,项);
下拉列表.setAdapter(适配器);
用户名=(EditText)findViewById(R.id.EditName);
userContact=(EditText)findViewById(R.id.EditContact);
userAddress=(EditText)findViewById(R.id.EditAddress);
userStore=(微调器)findviewbyd(R.id.StoreSpinner);
userRequest=(EditText)findViewById(R.id.EditRequest);
mRegister=(按钮)findviewbyd(R.id.SubmitButton);
mRegister.setOnClickListener(此);
}
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
新建CreateUser().execute();
}
类CreateUser扩展异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
布尔失败=假;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(MainActivity.this);
setMessage(“创建请求…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…args){
//TODO自动生成的方法存根
//检查成功标签
成功;
字符串username=username.getText().toString();
字符串usercontact=usercontact.getText().toString();
字符串useraddress=useraddress.getText().toString();
字符串userstore=userstore.getSelectedItem().toString();
字符串userrequest=userrequest.getText().toString();
试一试{
//建筑参数
List params=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
添加(新的BasicNameValuePair(“userContact”,userContact));
添加(新的BasicNameValuePair(“userAddress”,userAddress));
添加(新的BasicNameValuePair(“userStore”,userStore));
添加(新的BasicNameValuePair(“userRequest”,userRequest));
Log.d(“请求!”,“启动”);
//将用户数据发布到脚本
JSONObject json=jsonParser.makeHttpRequest(
登录URL,“POST”,参数);
//完整json响应
Log.d(“登录尝试”,json.toString());
//json成功元素
success=json.getInt(TAG_success);
如果(成功==1){
Log.d(“用户创建的!”,json.toString());
完成();
返回json.getString(TAG_消息);
}否则{
Log.d(“登录失败!”,json.getString(TAG_MESSAGE));
返回json.getString(TAG_消息);
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//删除产品后关闭对话框
pDialog.disclose();
如果(文件url!=null){
Toast.makeText(MainActivity.this,file_url,Toast.LENGTH_LONG.show();
}
}
}
}
这是我的JSONParser.java

public class JSONParser {
    static InputStream is = null ;
    static JSONObject jObj = null ;
    static String json = " " ;

    // constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
            //Log.i("DATA","json data is :: "+json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
            //jarr = new JSONArray(json);
            //jObj = jarr.getJSONObject(0);
            //JSONParser parser = new JSONParser();
            //Object obj = parser.parse(json);
            //JSONObject jsonObj = (JSONObject) obj;
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // Return the JSON Object.
        return jObj;

    }


    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
公共JSONObject getJSONFromUrl(最终字符串url){
//发出HTTP请求
试一试{
//构造客户端和HTTP请求。
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
//执行POST请求并在本地存储响应。
HttpResponse HttpResponse=httpClient.execute(httpPost);
//从响应中提取数据。
HttpEntity HttpEntity=httpResponse.ge
02-25 14:13:43.070    2708-2725/com.example.user.callarocket D/request!﹕ starting
02-25 14:13:43.132    2708-2723/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 14:13:43.132    2708-2723/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c46c20, error=EGL_SUCCESS
02-25 14:13:43.318    2708-2725/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 14:13:43.318    2708-2725/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.user.callarocket, PID: 2708
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
            at com.example.user.callarocket.MainActivity$CreateUser.doInBackground(MainActivity.java:129)
            at com.example.user.callarocket.MainActivity$CreateUser.doInBackground(MainActivity.java:86)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
02-25 14:13:45.643    2708-2708/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{279ba229 V.E..... R......D 0,0-1026,348} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:298)
            at com.example.user.callarocket.MainActivity$CreateUser.onPreExecute(MainActivity.java:100)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.example.user.callarocket.MainActivity.onClick(MainActivity.java:82)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            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:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)