Asyncクラスでnullポインタ例外が発生する理由を説明してください。 URLからデータを取得しようとしていますが、次のコードを含む162のnullポインタ例外が発生します。AsyncクラスのURLからJSONデータを解析しようとしたときにnullポインタ例外が発生する
int lengthJsonArr = jsonMainNode.length();
私はそれがなぜであるかはわかりませんが、誰かがそれが偉大なものになるのを助けることができたら。誰かが私にURLからのjsonデータを取得するためのより良い選択肢を示してくれれば、それは大きな助けにもなります。
public class userTask extends AsyncTask<String, Void, Void>{
HttpURLConnection connection = null;
private String Content;
@Override
protected Void doInBackground(String... urls) {
BufferedReader reader = null;
try {
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
} Content = buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void s) {
super.onPostExecute(s);
String OutputData = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
int lengthJsonArr = jsonMainNode.length(); //This is causing the exception
for (int i =0; i < lengthJsonArr; i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name").toString();
Double longitude = jsonChildNode.optDouble("lon");
Double latitude = jsonChildNode.optDouble("lat");
OutputData += " Name : "+ name +" "
+ "Longitude : "+ longitude +" "
+ "Latitude : "+ latitude +" "
+"-------------------------------------------------- ";
//Show Parsed Output on screen (activity)
Toast toast = Toast.makeText(getApplicationContext(), OutputData, Toast.LENGTH_LONG);
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
'Content'はAsyncTaskのインスタンス変数です。あなたはdoInBackgroundからそれを返し、onPostExecuteでそれを操作する必要があります。 –
"URLからjsonデータを取得するためのより良い代替方法" - VolleyまたはOkHttpライブラリは素晴らしい選択肢ですが、あなたのnull値を取得しているという事実は解決しませんAndroid配列のJSONオブジェクト。 –
doInBackground()はStringコンテンツを返す必要があり、onPostExecutはその文字列をinput(parameter)として受け取る必要があります。したがって、AsyncTaskとして修正する必要があります。 –
GVillani82