空指针异常而检索JSON对象 [英] Null Pointer Exception while retrieving JSON object
问题描述
我是新来的JSON。我使用的 http://pnrapi.appspot.com/ 以获得使用JSON特定列车的状态。但是,当试图解析收到的对象,我总是得到一个空指针异常。请帮助。
下面是我的code。
公共类PNRStatusActivity延伸活动{
私有静态最后弦乐TAG_CONTACTS =接触;
静态InputStream为= NULL;
JSONObject的jObj = NULL;
静态JSON字符串=;
JSONArray接触= NULL;
私有静态字符串URL =http://pnrapi.appspot.com/4051234567;
/ **当第一次创建活动调用。 * /
@覆盖
公共无效的onCreate(捆绑savedInstanceState){ super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
//创建JSON解析器实例
乔恩的JSONObject = getJSONFromUrl(URL); 尝试{
//存储在变量中的每个JSON项目
字符串ID = jon.getString(状态);
Toast.makeText(getApplicationContext(),身份证,Toast.LENGTH_LONG).show();
}赶上(JSONException E){
// TODO自动生成catch块
e.printStackTrace();
}
} //函数来获取JSON对象
公众的JSONObject getJSONFromUrl(字符串URL){ //使HTTP请求
尝试{
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL); HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent(); }赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(线+的n);
}
is.close();
JSON = sb.toString();
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj;
}
}
有一些在你的code,虽然不一定是全部将直接关系到你的 NullPointerException异常$ C问题$ C> ...
-
在你的
getJSONFromUrl
方法使用的是HttpPost
时,它似乎并不像你实际上张贴任何东西。使用HTTPGET
代替。 -
在从响应读取一个JSON字符串,可使用
HttpEntity
的getContentLength()
方法创建一个字节数组,如(例如)...字节[]缓冲区=新的字节[CONTENTLENGTH]
,简单地阅读的InputStream
为...inStream.read(缓冲)
。你需要做的错误检查沿着课程的方式。你的情况,你试图读取行并追加N每行一个串线。首先,你不需要用这种方式来读取一个JSON字符串,如果你确实打算追加一个换行符(在任何Java code任何时间),它应该是\\ n。 -
要你的字节数组转换为一个JSON字符串,可使用解析你再简单地做下...
字符串jsonString =新的String(缓冲,UTF-8)
-
从不指定
ISO-8859-1
编码任何东西,如果你能真正避免它。 -
当您创建
吐司
在活动
的onCreate(.. 。)
方法,你可以使用getApplicationContext()
。除非你真的确定何时何地,你应该使用它,请不要使用应用程序上下文。在一个主体活动的
code,你可以简单地使用这个
为上下文
创建时,吐司
。 -
正如其他人所说,一定要检查是否有
空
返回他们到处都不可能发生。如果方法发生异常和回报是空
确保无论code呼吁空
。
I am new to JSON. I am using http://pnrapi.appspot.com/ to get the status of a particular train using JSON. But while trying to parse the received object i always get a null pointer exception. Please help.
Here is my code.
public class PNRStatusActivity extends Activity {
private static final String TAG_CONTACTS = "contacts";
static InputStream is = null;
JSONObject jObj = null;
static String json = "";
JSONArray contacts = null;
private static String url = "http://pnrapi.appspot.com/4051234567";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating JSON Parser instance
JSONObject jon=getJSONFromUrl(url);
try {
// Storing each json item in variable
String id = jon.getString("status");
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//function to get JSON Object
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
}
There are a number of problems in your code although not necessarily all would be directly related to your NullPointerException
...
In your
getJSONFromUrl
method you are usingHttpPost
when it doesn't seem like you're actually posting anything. UseHttpGet
instead.When reading a JSON string from a response, use the
getContentLength()
method ofHttpEntity
to create a byte array such as (example)...byte[] buffer = new byte[contentLength]
and simply read theInputStream
as...inStream.read(buffer)
. You will need to do error checking along the way of course. In your case you're attempting to read a string line by line and appending "n" to each line. Firstly you don't need to read a JSON string in this way and if you're actually intending to append a newline character (at any time in any Java code), it should be "\n".To convert your byte array to a usable string for JSON parsing you then simply do the following...
String jsonString = new String(buffer, "UTF-8")
Never specify
iso-8859-1
encoding for anything if you can really avoid it.When you create your
Toast
in yourActivity
onCreate(...)
method, you usegetApplicationContext()
. Don't use the application context unless you're really sure of when and where you should use it. In the main body of anActivity's
code you can simply usethis
for theContext
when creating aToast
.As others have mentioned, make sure you check for a
null
return everywhere they can possibly happen. If an exception occurs in a method and the return isnull
make sure whatever code called that method checks fornull
.
这篇关于空指针异常而检索JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!