Finding out http response code in android - java

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.

Related

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.

How to call a php file and store the json output

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");
}

send data from android app to cakephp whith url

I wrote one android login app that get username and password from user. I whant to send username & password to server that is cakephp application.This is my android code:
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/ar/users/login?name="+name+"&password="+pass);
//Execute HTTP Post Request
response=httpclient.execute(httppost);
final ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
JSONArray jArray;
jArray = new JSONArray(result);
JSONObject j =new JSONObject();
j = jArray.getJSONObject(0);
JSONObject json = j.getJSONObject("User");
text = json.getString("last_name");
I write only this line in layout:
<?php echo $content_for_layout ?>
view code:
<?php echo json_encode($user); ?>
controller:
function login() {
if(isset($this->params['url']['name']))
$data = $this -> User -> findByuser_name($this->params['url']['name']);
if ($data && $data['User']['password'] == ($this->params['url']['password'])) {
$this -> set('user', $data);
} else {
$this -> set('error', true);
}
}
this code work goodly by enter below url in browser but don't work in android app!
"localhost/ar/users/login?name=m_sepehri&password=111"
anybody can help me?
You are using httppost but appending your data name and pass into the url itself. Use AsyncTask with List as follows:
private class MyAsyncTask extends AsyncTask<String, Integer, Double> {
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(name1, email1, password1, mobile1);
return null;
}
protected void onPostExecute(Double result) {
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),
"Account Activated Login To MyGenie",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
}
protected void onProgressUpdate(Integer... progress) {
pb.setProgress(progress[0]);
}
public void postData(String name, String email, String password,
String mobile) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://yoursite.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs
.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("mobile", mobile));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Except you're running a webserver and CakePHP on your phone you might want to use the ip or hostname of the machine running the website instead of using localhost from your phone.
localhost/ar/users/login?name=m_sepehri&password=111
And read this page about json views in CakePHP.
Also sending the password in plain text and as a bonus not using https is negligent.
You can use the Auth Comp. of CakePhp Then create a RESTFULL link ; in your controller USerController create a method like the one caled login then receive data via POST
public function api_loginx(){
//$this->autoRender = false;
if ($this->request->is('post')) {
//print_r($this->request->data);
$this->request->data['User']['password'] =$_POST['password'];
$this->request->data['User']['username'] = $_POST['username'];
print_r($this->request->data);
print_r($this->request->data['User']);
debug($this->Auth->login());
if ($this->Auth->login()) {
echo "true";
//$this->Session->setFlash(__('Welcome, '. $this->Auth->user('username')));
//$this->redirect($this->Auth->redirectUrl());
} else {
echo "false";
//$this->Session->setFlash(__('Invalid username or password'));
}
}
}

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()

Android login authentication to remote MySQL database

Here's my java code:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > ();
postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters);
String res = response.toString();
// res = res.trim();
res = res.replaceAll("\\s+", "");
//error.setText(res);
if (res.equals("1")) {
txtError.setText("Correct Username or Password");
//Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class);
//startActivity(i);
} else {
txtError.setText("Sorry!! Incorrect Username or Password");
}
} catch (Exception e) {
txtUsername.setText(e.toString());
}
}
});
I thinks there's an error in my res.equals because it keeps saying "Invalid Username or password" even though I've entered the correct username or password. But when I change the res.equals to res.contains it keeps saying "correct username or password" even though i've entered the correct username and password. I really need your help. to all mastered in android development. Hope you could help me on this. And also, when i change the txtError.setText(res) just to check if it returns 1 and 0 it does not.
This needs to be done in the php file not in the Android code:
<?php
define('DB_USER', "root"); //username used to connect to the database.
define('DB_PASSWORD', ""); //password used to connect to the database.
define('DB_DATABASE', "dbname"); //database name
define('DB_SERVER', "127.0.0.1"); //database server address
?>
Using a JSON parser, you would then need to parse the data on the server. You need to use something similar to the following:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
//Method to connect to the database
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
//The following works just as in normal GET and POST methods
try {
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
In a second class, you would then need to define the connection parameters as follows:
public class UserFunctions {
private JSONParser jsonParser;
private static String loginURL = "http://www.sampleweb.com/login.php";
private static String registerURL = "http://www.sampleweb.com/register.php";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
In addition to this, you would finally need to use your application classes to parse data and show it to the users. There are several online tutorials on how this can be done.
Hope this helps :)
It is really difficult to figure out what is going on with out the response from server. To debug the issue, for both valid and invalid user name/password combinations check the response of http://www.sampleweb.com/imba.php using a POST library like curl or Postman

Categories

Resources