JSON Android 错误 - 尝试在空对象引用上调用虚拟方法 'java.lang.String org.


JSON Android Error- Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference

我的应用程序崩溃,日志显示此错误:

尝试在我这样做的行上的空对象引用上调用虚拟方法'java.lang.String org.json.JSONObject.getString(java.lang.String)':

ab = jobj.getString("title");

我是Android开发的菜鸟。请帮忙!

public class MainActivity extends ActionBarActivity {
JSONObject jobj = null;
ClientServerInterface clientServerInterface = new ClientServerInterface();
TextView textView;
String ab = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.textView);
    new RetrieveData().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings)
    {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
class RetrieveData extends AsyncTask<String,String,String>
{
    protected String doInBackground(String... arg0) {
        jobj = clientServerInterface.makeHttpRequest("http://**.***.***.**/printresult.php");
        try {
            ab = jobj.getString("title");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return ab;
    }
    protected void onPostExecute(String ab){
        textView.setText(ab);
    }
}
}

这是另一个文件:

public class ClientServerInterface {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";

public ClientServerInterface(){
}
public JSONObject makeHttpRequest(String url){
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try{
        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity httpentity = httpresponse.getEntity();
        is = httpentity.getContent();
    }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;
        try{
            while((line = reader.readLine())!= null){
                sb.append(line+"'n");
            }
            is.close();
            json = sb.toString();
            try{
                jobj = new JSONObject(json);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }catch (UnsupportedEncodingException e){
        e.printStackTrace();
    }
    return jobj;
}
}

也许它在我的 php 文件中?

<?php
require_once('connection.php');
$qry = "SELECT * FROM eventdetails";
$result = mysql_query($qry);
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
mysql_close();
?>

我真的被难住了。请帮忙!

我相信导致困难的原因是您的 URL 指向格式错误的 JSON 字符串。 我在提供的 URL 中得到的是:

[{"title":"School Start","pictureURL": ...   }]

前面和结尾的方括号不应出现在您在此处传递给 JSONObject 构造函数的字符串中。

 json = sb.toString();
        try{
            jobj = new JSONObject(json);
        }catch (JSONException e){
            e.printStackTrace();
        }

您需要修剪 json 的第一个和最后一个字符,因为我相信构造函数正在抛出一个您捕获并忽略的异常。

尝试这样做

class RetrieveData extends AsyncTask<String,String,JSONObject>{
    protected JSONObject doInBackground(String... arg0) {
        JSONObject jobj = clientServerInterface.makeHttpRequest("http://54.164.136.46/printresult.php");
        return jobj;
    }
    protected void onPostExecute(JSONObject jobj){
        try {
            String ab = jobj.getString("title");
            textView.setText(ab);
        } catch (JSONException e) {
        e.printStackTrace();
        }
    }
}
通常

将更高版本的 JDK 版本设置为目标。 当我们使用 JDK 1.7 作为目标平台进行构建时,我就会发生这种情况。 当更改为JDK 1.5时,它解决了该问题。不确定,但它奏效了。还要提到的是,这不是特定于Android应用程序,而是一个 部署包 。不确定它是否相关,但包是相同的java.lang.string。

正如 user1023110 指出的那样,发生错误是因为构造函数抛出异常。在这种情况下,我给构造函数一个 JSONArray,它给出了无法转换为 JSONObject 的错误。首先,我将其添加到我的 ClientServerInterface 类的顶部:

static JSONArray jarr = null;

然后,我添加了这两行:

jarr = new JSONArray(json);
jobj = jarr.getJSONObject(0);

我以前有这个的地方:

jobj = new JSONObject(json);

该方法现在返回 JSONArray 的第一个 JSONObject。

感谢您的帮助!