0

我是开发android应用程序的新手。我已经阅读了很多关于我所问问题的相关帖子,但帖子中的提示或解决方案并没有解决我的问题。当我运行我的应用程序时出现此错误

03-11 11:52:39.115 3209-3236/com.example.blue_sky.store E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
03-11 11:52:39.116 3209-3236/com.example.blue_sky.store E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                          Process: com.example.blue_sky.store, PID: 3209
                                                                          java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                              at android.os.AsyncTask$3.done(AsyncTask.java:304)
                                                                              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 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
                                                                              at com.example.blue_sky.store.MainActivity$Store.doInBackground(MainActivity.java:76)
                                                                              at com.example.blue_sky.store.MainActivity$Store.doInBackground(MainActivity.java:53)
                                                                              at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                              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) 

听到的是我的 MainAcivity:

package com.example.blue_sky.store;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends ListActivity {

    private ProgressDialog pd;
    //jparser
    JSONparser jsoNparser = new JSONparser();
    ArrayList<HashMap<String,String>> p;
    //s
    static JSONArray jsonArray ;
    String Url="http://127.0.0.1/store.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        p = new  ArrayList<HashMap<String, String>>();
        new Store().execute();
       /* Store s =new Store();
        s.execute();*/
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        String code = ((TextView)v.findViewById(R.id.tvPid)).getText().toString();
        Intent i = new Intent(MainActivity.this,ADD.class);
        i.putExtra("pid",code);
        startActivity(i);
    }

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(MainActivity.this);
            pd.setMessage("LogIn");
            pd.show();
            //pd.dismiss();

        }

        @Override
        protected String doInBackground(String... params) {
            List <NameValuePair> parms = new ArrayList<>(); // Building Parameters
            //json
            JSONObject jsonObject = jsoNparser.makeHttpRequest(Url,"GET",parms);


            try {
              //  int t =jsonObject.getInt("t");
                int t =1;
                if (t==1){
                    jsonArray = jsonObject.getJSONArray("Store");
                    for(int i = 0; i<jsonArray.length(); i++){
                        //c
                        JSONObject jObject = jsonArray.getJSONObject(i);
                        String  pid =  jObject.getString("pid");
                        String name = jObject.getString("name");
                        String price = jObject.getString("price");
                        String description = jObject.getString("description");

                        HashMap<String,String> hashMap = new HashMap<String, String>();
                        hashMap.put("pid",pid);
                        hashMap.put("name",name);
                        hashMap.put("price",price);
                        hashMap.put("description",description);

                        p.add(hashMap);
                    }
                }else {
                    Toast.makeText(MainActivity.this,"اطلاعاتی یافت نشد!!",Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
               // e.printStackTrace();
                System.out.println("Error " + e.getMessage());
                return null;
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            pd.cancel();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ListAdapter listAdapter = new SimpleAdapter(MainActivity.this,p,R.layout.item_list,
                            new String[]{"pid","name","price","description","store"},
                            new int[]{R.id.tvPid,R.id.tvName,R.id.tvPrice,R.id.tvDisc});
                    setListAdapter(listAdapter);
                }
            });
        }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }
}

这是我的 ADD 类:

package com.example.blue_sky.store;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Blue_Sky on 3/11/2017.
 */

public class ADD extends Activity {
    private String cod;
    private ProgressDialog pd;
    EditText InputName,InputCode,InputNumber;
    Button Send;
    JSONparser jparser = new JSONparser();
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        InputName = (EditText)findViewById(R.id.edInputName);
        InputCode = (EditText)findViewById(R.id.edInputCode);
        InputNumber = (EditText)findViewById(R.id.edInputNumber);
        Send = (Button)findViewById(R.id.btnSend);

        setContentView(R.layout.add);
        Bundle input = getIntent().getExtras();
        cod = input.getString("pid");
        Send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new load().execute();
            }
        });
    }
    class load extends AsyncTask<String,String,String>{

        public void AttemptLogin(String name, String code, String number){
            name = InputName.getText().toString();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(ADD.this);
            pd.setMessage("LogIn");
            pd.show();

        }

        String code = InputCode.getText().toString();
        String name = InputName.getText().toString();
        String number = InputNumber.getText().toString();

        @Override
        protected String doInBackground(String... params) {
            List<NameValuePair> parms = new ArrayList<NameValuePair>();
            parms.add(new BasicNameValuePair("name",name));
            parms.add(new BasicNameValuePair("code",code));
            parms.add(new BasicNameValuePair("number",number));
            parms.add((new BasicNameValuePair("cod",cod)));

            JSONObject Json = jparser.makeHttpRequest(url,"POST",parms);

            try {
                int t = Json.getInt("t");
                if(t == 1){
                    Intent in = new Intent(ADD.this,MainActivity.class);
                    startActivity(in);
                }else {
                    Toast.makeText(getApplicationContext(),"خطایی رخ داده!!",Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pd.dismiss();
        }
    }
}

和 JSONParser 类:

package com.example.blue_sky.store;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONparser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONparser() {

    }

    // 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;

    }
}
4

1 回答 1

0

我猜,你的 php 文件返回 null。你的 jsonObject 是空的。

打印响应:

        if (BuildConfig.DEBUG) {

            Log.d("TAG", "Response : "+jsonObject);   
        }

如果您要在 Play 商店中启动应用程序,请始终使用调试检查。它不会打印任何日志。

于 2017-03-11T18:21:12.560 回答