Reputation: 61
I'm trying to get a json response from api call.But some errors has occurred. Please tell me what is wrong with my code...My code is like this.
private JSONObject responseJson;
private void apiRequest() {
mQueue = Volley.newRequestQueue(MainActivity.this);
String mRequestUrl = "http://hogehoge";
JsonObjectRequest jsonOR = new JsonObjectRequest(Request.Method.GET, mRequestUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if (response.getJSONObject("response").has("error")) {
throw new NoSuchElementException(msg);
}else{
responseJson = response;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
}
});
jsonOR.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mQueue.add(jsonOR);
}
and error messages are this.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.mymaterialapp/com.example.user.mymaterialapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
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.mymaterialapp.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
Upvotes: 0
Views: 460
Reputation: 704
To call a web service
public static String handleJsonPOSTRequest(String serverURL, String data)
{
int responseCode;
InputStream inputStream = null;
String serverResponseMsg = null;
OutputStream outputStream = null;
HttpURLConnection httpURLConnection = null;
URL url = null;
URLConnection conn = null;
try
{
url = new URL(serverURL);
Log.e("URL: ", serverURL);
Log.e("REQUEST: ", data);
conn = url.openConnection();
httpURLConnection = (HttpURLConnection) conn;
httpURLConnection.setRequestMethod(POST_METHOD);
httpURLConnection.setReadTimeout(AppConstant.TIME_CONNECTION_TIMEOUT);
httpURLConnection.setConnectTimeout(AppConstant.TIME_CONNECTION_TIMEOUT);
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter ouStreamWriter = new OutputStreamWriter(outputStream);
ouStreamWriter.write(data);
ouStreamWriter.flush();
ouStreamWriter.close();
responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200)
{
inputStream = httpURLConnection.getInputStream();
serverResponseMsg = readInputStream(inputStream);
}
if (serverResponseMsg != null)
{
Log.e("RESPONSE: " + serverURL, serverResponseMsg);
}
else
{
Log.e("RESPONSE: " + serverURL, "Null");
}
}
catch (IOException exception)
{
}
catch (Exception exception)
{
}
return serverResponseMsg;
}
To get JSON from inputstream
private static String readInputStream(InputStream inputStream)
{
StringBuilder stringBuilder = new StringBuilder();
String subMessage = null;
try
{
InputStreamReader inStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferReader = new BufferedReader(inStreamReader);
while ((subMessage = bufferReader.readLine()) != null)
{
stringBuilder.append(subMessage);
}
}
catch (IOException exception)
{
}
catch (Exception exception)
{
}
return stringBuilder.toString();
}
Upvotes: 0
Reputation: 704
Try this code
public String callWebService(String serviceURL) {
StringBuffer buff = new StringBuffer("");
HttpClient client;
BufferedReader in = null;
try {
HttpGet getRequest = new HttpGet(serviceURL);
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
client = new DefaultHttpClient(httpParams);
HttpResponse response = client.execute(getRequest);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
String line = "";
while ((line = in.readLine()) != null) {
buff.append(line);
}
in.close();
} catch (Exception e) {
}
return buff.toString();
}
It will return JSON
Upvotes: 1