I am developing the simple application where i need to fetch the data from the local host sql database, i am able to get the JSON when i tested on the browser , but i am getting null pointer exception while checking through the android , i have cross checked the ip address and even tried with async task and even declared the internet permissions in manifest.xml , i debugged the application but still not able to figure the cause of the error .
MainActivity.java
package library.danaraddi.com.myapplication;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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;
public class MainActivity extends ActionBarActivity {
// views import
Button PostButton, GetButton;
TextView UsernameTextView, PasswordTextView;
EditText UsernameEditText, PasswordEditText;
// 192.168.1.210
// static fields
private static String URL = "http://192.168.1.210/cpsscripts/total_items.php";
private static String GET_TOTAL = "gettotal";
// objetcs
JSONParser jsonParser ;
List<NameValuePair> params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Views Import
PostButton = (Button) findViewById(R.id.post_button);
GetButton = (Button) findViewById(R.id.get_button);
UsernameEditText = (EditText) findViewById(R.id.username_edittext);
PasswordEditText = (EditText) findViewById(R.id.password_edittext);
UsernameTextView = (TextView) findViewById(R.id.username_textView);
PasswordTextView = (TextView) findViewById(R.id.password_textView);
// Objects
jsonParser = new JSONParser();
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("", ""));
PostButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
JSONObject json = jsonParser.getJSONFromURL(URL, params);
String res = json.getString("gettotal");
UsernameTextView.setText(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
JSONParser.java
package library.danaraddi.com.myapplication;
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.HttpPost;
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;
/**
* Created by VINAY on 2/4/2015.
*/
public class JSONParser {
InputStream inputStream = null;
JSONObject jsonObject = null;
String output = "";
public JSONParser() {
}
public JSONObject getJSONFromURL(String URL, List<NameValuePair> valuePairs) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(new UrlEncodedFormEntity(valuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine())!= null){
stringBuilder.append(line + "\n");
}
inputStream.close();
output = stringBuilder.toString();
Log.i("VINAY",output);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jsonObject = new JSONObject(output);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
total_items.php
<?php
$response = array();
// import db connection variables
require_once __DIR__ . '/db_config.php';
// connect DB
$db= new mysqli(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE);
//if(!empty($_POST['total'])){
// Query
$totalquery ="SELECT * FROM `questions` ORDER BY `id` DESC LIMIT 1";
// connecting to mysql
if ($db->query($totalquery) == TRUE) {
$rows = $db->query($totalquery);
// get array
$totalrows = $rows->fetch_assoc();
// repond the total amount
$response["gettotal"] = $totalrows["id"];
// show response
print(json_encode($response));
} else {
echo "Error: " . $insertQuery . "<br>" . $db->error;
}
$db->close();
//}
?>
Logcat
02-05 06:01:24.248 400-400/library.danaraddi.com.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:65)
at java.io.InputStreamReader.<init>(InputStreamReader.java:79)
at library.danaraddi.com.myapplication.JSONParser.getJSONFromURL(JSONParser.java:56)
at library.danaraddi.com.myapplication.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
try to use this on line 56 in JsonParser
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
And check internet permission in manifest again.
I am a linux newby, so not sure if this is the definitive answer, however looking at the permissions of/var/www/html showed me that only user root had Read Write Execute permissions. As I was using the browser just as a standard user and not getting access, I assumed that 'Other' needed some permissions, so I did this:
sudo chmod 755 html -R
Now I can access localhost in a browser.
I found this video on "Users, Groups and Permissions in Linux" very helpful:
If I am interpreting the stacktrace correctly, the exception is being thrown within the InputStreamReader
constructor in this line:
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStream,
"iso-8859-1"),
8);
The only plausible explanation is that inputStream
is null
.
How so? The code prior to that is supposed to get an input stream for you!
But consider what happens if the HTTP request fails and throws an exception. If that happens, you won't get to the statement that sets inputStream
to the content stream, and hence it will still be null.
Hint: the real mistake here is that you caught the exception, printed a stacktrace (somewhere) ... and then continued as if everything was OK!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.