glln
glln

Reputation: 543

Can't get my Android Application to connect to server

I've set up a login screen on my application (that's all it is for now). It has a username and password field and a login button. When the user enters their details and presses login, it checks the user exists in my MySQL database and that the details are correct and then displays a Toast message saying "Successful" if it was and "Invalid..." if not or if there was an error connection to the server then it displays "connection error".

I keep getting the connection error message and I'm not sure why. I've tested the database connection in the php file and that is working fine as is the query to the database, so I'm assuming the problem lies in my android code.

Here is the entire block of code for you (with my domain concealed)

   package uk.co.mypackage.mypackagename;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    EditText etUser, etPass;
    Button bLogin;

//Create String variables that have input assigned to them
String username, password;

//Create an HTTPClient as form container
HttpClient httpClient;

//User HTTP Post method
HttpPost httppost;

//Create an array list for the input data to be sent
ArrayList<NameValuePair> nameValuePairs;

//Create an HTTP Response and HTTP Entity
HttpResponse response;
HttpEntity entity;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initialise();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;

}

private void initialise() {
    etUser = (EditText) findViewById(R.id.etUser);
    etPass = (EditText) findViewById(R.id.etPass);
    bLogin = (Button) findViewById(R.id.bSubmit);
    //Now to set an OnClickListener
    bLogin.setOnClickListener(this);
}

@Override
public void onClick(View v) {

    //Create New default HTTPClient
    httpClient = new DefaultHttpClient();

    //Create new HTTP POST with URL to PHP file as parameter
    httppost = new HttpPost("http://www.mydomain.co.uk/android_api/index.php"); 

    //Assign input text to string
    username = etUser.getText().toString();
    password = etPass.getText().toString();

    try{
        //Create New Array List
        nameValuePairs = new ArrayList<NameValuePair>();

        //Place them in an array list
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));

        //Add array list to HTTP POST
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //assign executed form container to response
        response = httpClient.execute(httppost);

        //check status code, need to check status code 200
        if(response.getStatusLine().getStatusCode()== 200){

            //assign response entity to http entity
            entity = response.getEntity();

            //check if entity is not null
            if(entity != null){

                //Create new input stream with received data assigned
                InputStream instream = entity.getContent();

                //Create new JSON object. assign converted data as parameter
                JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                //assign JSON responses to local string
                String retUser = jsonResponse.getString("user");//MySQL table field
                String retPass = jsonResponse.getString("pass");//MySQL table field

                //Validate login
                if(username.equals(retUser)&& password.equals(retPass)){

                    //Create a new shared preference by getting the preference
                    SharedPreferences sp = getSharedPreferences("logindetails", 0);

                    //Edit the shared preferences
                    SharedPreferences.Editor spedit = sp.edit();

                    //Put the login details as string
                    spedit.putString("user", username);
                    spedit.putString("pass", password);//May not need to store password

                    //close the editor
                    spedit.commit();

                    //Display a Toast saying login was a success
                    Toast.makeText(getBaseContext(), "SUCCESS!", Toast.LENGTH_SHORT).show();


                } else {
                    //Display a Toast status saying it failed
                    Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                }

        }

    } 
    }   catch(Exception e){
        e.printStackTrace();
        //Display Toast when there is a connection error
        Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
    }


} //End OnClick()

 private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }//End ConvertStreamToString

}

Upvotes: 0

Views: 1012

Answers (1)

Omar
Omar

Reputation: 463

Upon sending a post request with username and password, a warning message is sent Undefined variable: num. Response containing non-json elements cause error in json object parsing and return null object.

Upvotes: 1

Related Questions