How to call a php file and store the json output - java

I am developing an android app, I have run into a situation where the app will use an API to send some data to the php webservice and the webservice will greate some json encoded message which will be echoed back.
My question is
How Do I store this json message that was sent by php echo into a variable in the android app?
How Do I then go about parsing the json and use the data to construct a switch case?
I had raised a similar question sometime back and was told to use AsyncTask but what I don't understand is why would I need to use it.
The sample json response that will be sent by the phpwebservice is
{"error":false,"message":"New user created"}
I want to be able to get the error variable and decide if there is any error and also get the message in a variable and display it to the user in the app.
I currently have the android signup.java code like this
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
//Code to check if user was successfully created
final int statusCode = httpResponse.getStatusLine().getStatusCode();
switch (statusCode)
{
case 201:
Toast.makeText(getBaseContext(), "Successfully Registered", Toast.LENGTH_SHORT).show();
break;
case 400:
Toast.makeText(getBaseContext(), "Username already taken", Toast.LENGTH_SHORT).show();
username.setText("");
break;
default:
Toast.makeText(getBaseContext(), "Unknown error occurred", Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
While this checks the http header code and might work( I havent tested it out) I want to use the jsnon response and do the handling using it.

Use java-json:
HttpURLConnection urlConnection = (HttpURLConnection) (uri.toURL().openConnection());
urlConnection.setConnectTimeout(1500);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("pass", password));
params.add(new BasicNameValuePair("email", email));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
if(urlConnection.getResponseCode() == 200){
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject json = new JSONObject(responseStrBuilder.toString());
String message = json.getString("message");
}

Related

Cannot save the data to the url using json

My json code { "Status": "NO UPDATES" }
Iam getting the output as couldn't save the data.
JSONResult iam getting as "FAILED"-- when i check the log.v(jsonresult,"jsonResult")
iam unable to solve the issue
please help me out.
btn_Save.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{try
{StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String postReceiverUrl = "http://";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
#SuppressWarnings("resource")
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
Log.v(TAG, jsonobject.toString());
nameValuePairs.add(new BasicNameValuePair("EmployeeId", wepemployeeDeptId.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("visitorname", wepName.getText().toString()));
Log.v(TAG, "Visitor Name: " + wepName.getText().toString());
nameValuePairs.add(new BasicNameValuePair("PhoneNo", wepMobile.getText().toString()));
// nameValuePairs.add(new BasicNameValuePair("WhomToMeet", wepWhomToMeet.getSelectedItem().toString()));
nameValuePairs.add(new BasicNameValuePair("Address", wepAddress.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("EmailID", wepEmail.getText().toString()));
// nameValuePairs.add(new BasicNameValuePair("visitType", wepVisitType.getSelectedItem().toString()));
nameValuePairs.add(new BasicNameValuePair("PurposeOfMeet", wepPurpose.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("DateofVisit", wepVisitDate.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("Intime", wepInTime.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("Outtime", wepOutTime.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("BadgeNo", wepBadgeNumber.getText().toString()));
// nameValuePairs.add(new BasicNameValuePair("CreatedBy", wepcreatedby.getText().toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("jsonResult",jsonResult);
JSONObject object = new JSONObject(jsonResult);
String status = object.getString("Status").trim();
Toast.makeText(getBaseContext(), "Please wait...",100).show();
if(status.toString().equals("SUCCESS"))
{
Intent i = new Intent(Entry.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Toast.makeText(getBaseContext(), "Details Inserted",1000000).show();
}
if(status.toString().equals("FAILED"))
{
Toast.makeText(getBaseContext(), "Couldn't save the data...",1000000).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
String data = null;
try {
data = URLEncoder.encode("EmployeeId", "UTF-8")
+ "=" + URLEncoder.encode(wepemployeeDeptId.getText().toString(), "UTF-8");
data += "&" + URLEncoder.encode("visitorname", "UTF-8") + "="
+ URLEncoder.encode(wepName.getText().toString()), "UTF-8");
//add key according to your requirement
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL("Your URL");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();EmployeeId

Uploading Image using Base64 results in error 413

So I'm moving hosting packages from bluehost to namecheap. I'm currently developing an Android application for a university problem. The image upload worked fine on the bluehost webhost. However when I try do the same technique I run into an error.
I've done some debugging and have come to the conclusion that it's server-side related as it's the same code but with parameters changed and nothing on android throws up any errors whatsoever. The entries get added to the database but the image doesn't get uploaded (registration system).
Error:
413 Request Entity Too Large
Request Entity Too Large
The requested resource does not allow request data with GET requests, or the amount of data provided in the request exceeds the capacity limit.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
PHP Code:
$user = $_POST['userName'];
$base = $_REQUEST['image'];
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
mkdir('../usr/'.$user);
$file = fopen('../usr/'.$user.'/display_picture.png', 'wb');
fwrite($file, $binary);
fclose($file);
Java Code: (Just incase)
public void uploadDisplayPicture(final ProgressDialog uploadingImage) {
final String UPLOAD_DISPLAY_PICTURE = "Upload Display Picture";
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
Log.d(UPLOAD_DISPLAY_PICTURE,"Do In Background Running");
InputStream is;
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userName", registrationDetails[0]));
nameValuePairs.add(new BasicNameValuePair("image", encodedString));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.IP + Config.DISPLAY_PHOTO_PATH);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) sb.append(line + "\n");
String resString = sb.toString();
is.close();
Log.d("Http Post Response:", response.toString());
Log.d("Http Response:", resString);
} catch (Exception e) {
System.out.println("Error: " + e);
}
return "";
}
#Override
protected void onPostExecute(String msg) {
Log.d(UPLOAD_DISPLAY_PICTURE, "On Post Execute Running");
super.onPostExecute(msg);
uploadingImage.setMessage("Registering User Details...");
new registerUserDetails().execute(registrationDetails);
}
}.execute(null, null, null);
}

Android - Keep user logged between activities

In my app I've a first activity that allow you to login to a web service. If the server allow user to connect it should call a TabHost activity. In TabHost activity I've 3 different activity:
HomeActivity: it display just a webview
HistoryActivity: it should display a ListView in which I insert the notification history
SettingsActivity: it display some settings of the app
In HistoryActivity I've to call to a web service to download a list of the notification history. To call this service I've to keep user logged, how I can do that?
I'm using the following code to connect to history service:
public void postData(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
StringEntity jsonSend = new StringEntity("{\"history\": true}");
httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
httpPost.setEntity(jsonSend);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
Log.d("HISTORY", json);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I used it for login and it works great. To connect to login service I use the following code:
public void postData(final String username, final String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("pollingId", "XXXXXXXXX"));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
JSONObject jsonObject = new JSONObject(json);
Boolean success = jsonObject.getBoolean("success");
if (success == true) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "ACCESSO EFFETTUATO!", Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this, TabBarActivity.class);
startActivity(i);
}
});
}
} catch (ClientProtocolException e) {
Log.d("CLIENT EXCEPTION", "ERRORE: " + e);
}catch (IOException e) {
Log.d("I/O EXCEPTION", "ERRORE: " + e);
} catch (JSONException e) {
e.printStackTrace();
}
}
If I use it to get notification history the JSON said me that user is not logged. How I can fix it? Thank you
UPDATE
I tried to follow your suggestions, but I've the same result. The modified code is the follow:
MainActivity.java
public void postData(final String username, final String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://extranet.gruppotesta.it/srv/at-brain/login.jsp");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("pollingId", "XXXXXXX"));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
JSONObject jsonObject = new JSONObject(json);
Boolean success = jsonObject.getBoolean("success");
if (success == true) {
Header[] cookie = response.getHeaders("cookie");
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", cookie.toString());
editor.commit();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "ACCESSO EFFETTUATO!", Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this, TabBarActivity.class);
startActivity(i);
}
});
}
} catch (ClientProtocolException e) {
Log.d("CLIENT EXCEPTION", "ERRORE: " + e);
}catch (IOException e) {
Log.d("I/O EXCEPTION", "ERRORE: " + e);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
HistoryActivity.java
public void postData(String url) {
HttpClient httpClient = new DefaultHttpClient();
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String stringCookie = sharedPreferences.getString("cookie", null);
BasicCookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("login", stringCookie);
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httpPost = new HttpPost(url);
try {
StringEntity jsonRequest = new StringEntity("{\"history\": true}");
httpPost.setEntity(jsonRequest);
httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
httpPost.setHeader("Cookie", cookie.toString());
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
Log.d("HISTORY", json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I try to run the app the server answer me with error "User not logged". What's wrong in my code?
When you first login, the web service must provide you with some sort of access token - a valid user id perhaps. You need to store and retrieve this user id in a SharedPreference. This user id must be passed as a parameter to all subsequent web services to indicate that the user is indeed logged in.
The official tutorial for how to get and set a SharedPreference is here.
You can try to use CookieStore to store a cookie with the login credentials. Take a look at this link: Http cookie store in Android.
Does your service give back a session cookie after successful login? If so you should store the cookie that the service issues after a login (in the Set-Cookie header in the response from the server) and set this cookie for any future HTTP requests.
httpPost.setHeader("Cookie", COOKIE_FROM_SERVER_AFTER_LOGIN);
You could use a CookieStore as well to help you store the cookies from HTTP requests - this will make cookie and session management easier.
UPDATE
Server headers won't include a Cookie header but a Set-Cookie header (because the server is instructing your useragent/browser/client to set a cookie and it's this cookie that will be included in your Cookie headers) so change this line:
response.getHeaders("cookie");
to
response.getHeaders("set-cookie");
UPDATE:
Your revision is now pulling out the correct Set-Cookie header but you are incorrectly storing the value (you are storing the entire header as the cookie when all you need is the value).
if (success == true) {
Header[] cookies = response.getHeaders("set-cookie");
//at this point cookies looks like this:
//Set-Cookie: JSESSIONID=84DB43CE8CABC52EBDF777BC0EA96D0F; Path=/; Secure
//if you just do cookies.toString() like you were doing before it will also include
//the cookie header which will create an incorrect cookie value.
//you just need the value of the Set-Cookie header and store that as your cookie
if (cookies.length > 0){
//it is very possible for a server to return more than one Set-Cookie header so the proper
//way would be to iterate through all of the values and string them together
//in the correct synatax of
//so you might want to store all of the values as a list in sharedPreferences
//and let your cookie store put them all in the request for you
String finalCookie = "";
for (Header header: cookies){
//access the value from the Header object and nothing else
//JSESSIONID=90D84EF5D5BD1C4008F332F9EDA8F9AA; Path=/; Secure;
if (header.getValue().contains(";")){
finalCookie += String.format("%s; ", header.getValue().split(";")[0]);
} else {
finalCookie += String.format("%s; ", header.getValue());
}
}
//finalCookie = JSESSIONID=1B70CAB822430E14991E14ACAE153F5D;
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", finalCookie);
editor.commit();
}
Now in your StoredPreferences you will have correctly formatted cookies (in your case you are only returning one from your server but it's likely that more than one Set-Cookie header can be included in a server response. So this implementation parses out each cookie and builds a cookie string in the correct format.
Since we are now correctly building the cookie string ourselves you can remove the CookieStore and just pull the "cookie" value out of SharedPreferences and use the string that is returned in your setHeader call:
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String stringCookie = sharedPreferences.getString("cookie", "");
...
httpPost.setHeader("Cookie", cookie);
Keep in mind that although this implementation will work for you it won't take into consideration if cookies change throughout your session. Since you are the author of the web application you should be aware of whether or not cookies change - maybe when you log in it's the only time you will be given cookies to set in the browser and this solution will work for you. But a more robust solution will be to save out all of the cookies individually (instead of using editor.putString you can use editor.putStringSet to save out all of the cookie headers) then when you want to build a cookie for the respond you can .add() each individual cookie to the cookie store and then use the cookie store the same way you were before. This way each cookie by name is stored individually so that if you ever get another Set-Cookie header again for a cookie that you already have loaded in your client it will correctly overwrite that value with the updated cookie value.

Finding out http response code in android

I need to be able to get the http header code in android which is going to be generated by a php code.
I am very new to android and not able to grasp the correct way to do it.
Currently the code I have on my signup.java file is able to post some data to the php based webservice and depending on the data sent the webservice echo a json encoded response.
The php code for response when an error occurs is
$response["error"] = true;
$response["message"] = "Username Already taken";
echoRespnse(400,$response);
and the code on success is
$response["error"] = false;
$response["message"] = "Successfuly Registered";
echoRespnse(201,$response);
This will generate a json ecoded response message.
My signup.java file has the following code
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost); //http header response??
//Code to check if user was successfully created
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
I want to know if httpResponse will hold the http header response code being generated by the webservice or will I need to parse the json response message to understand what is being returned by the webserivce.
The response code can be retrieved this way:
final int statusCode = httpResponse.getStatusLine().getStatusCode();
switch (statusCode)
{
case 201:
// Successfuly Registered
break;
case 400:
// Username Already taken
break;
default:
break;
}
To list the header values, you can use:
for (final Header h : httpResponse.getAllHeaders())
{
Log.d("Responser Header", h.getName() + ": " + h.getValue()); // or h.getElements()
}
or pick the desired header directly:
final String[] contentLength = httpResponse.getHeaders("Content-Length");
and parse it.

Accessing a single PHP file from two different activites in android

I have two activites: Mainpage.java and Secondary.java. And I am trying to access the same php file from both the class. When the second class is called the following error is revoked.
java.lang.nullpointerexception.
How can i remove this error?
This is causing the apllication to force close.
Thanks.
This the code for the first class:
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/ABC/login.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("action","LOGIN"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response=httpclient.execute(httppost);
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
tv.setText("Response from PHP : " + response);
if(response.equalsIgnoreCase("User Found"))
{
Toast.makeText(Axdroid.this,"Login Success",Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Secondary.class));
} else
{
showAlert();
}
dialog.dismiss();
}catch(Exception e){
System.out.println("Exception : " + e.getMessage());
}
}
And this for the secondary class
void jsr(){
try{
httpclient = new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/AndroidLeave/login.php");
nameValuePairs.add(new BasicNameValuePair("action","SUMMARY"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
System.out.println(" ++++++++ +++++++++++++"+response);
entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
System.out.println(" ++++++++ After getting data from PHP file +++++++++++++");
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());}
}}
LOGCAT:
10-26 18:10:01.313: W/SingleClientConnManager(2296): Make sure to release the connection before allocating another one.
10-26 18:10:01.964: E/log_tag(2296): Error in http connectionjava.lang.NullPointerException
10-26 18:10:01.974: E/log_tag(2296): Error converting result java.lang.NullPointerException
The error happens because you try to initiate the second connection, but you didn't close the first one.
Since you didn't use and InputStream in the first class, you didn't call, like in the second one, is.close().
I don't quite understand why, in the first class, you make two calls to execute().
You could do this:
delete these two lines
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
and after this line
response=httpclient.execute(httppost);
add:
final String responseString = EntityUtils.toString(response.getEntity());
then use responseString where ever you use response as a String.
If it still happening, add after that
EntityUtils.consume(response.getEntity());
the toString shoud do the consume as well, but just in case it doesn't.
If it still doestn' work, let me know.
Just quickly looking at your code, the exception is probably occurring on this line in the second class:
nameValuePairs.add(new BasicNameValuePair("action","SUMMARY"));
because nameValuePairs is null. You might try adding something like:
nameValuePairs = new ArrayList<NameValuePair>(2);
before you try calling nameValuePairs.add()

Categories

Resources