2

I am new to android development , I am trying to connect to my api in android . I have developed my api using laravel Framework . Here Login.java

package com.example.yasha.myapplication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;

public class Login extends AppCompatActivity {

    EditText emailText;
    EditText passwordText ;
    TextView signup;
    Button loginButton ;

    @Override
    public void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

         emailText = (EditText) findViewById(R.id.email);
         passwordText = (EditText) findViewById(R.id.password);
         signup = (TextView) findViewById(R.id.signup);
         loginButton = (Button) findViewById(R.id.login);

        signup.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Start the Signup activity
                Intent signupIntent = new Intent(getApplicationContext(), SignUp.class);
                startActivity(signupIntent);
            }
        });


    }

    public class MakeAccessToken extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(urls[0]);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();

                while (data != -1) {

                    char current = (char) data;

                    result += current;

                    data = reader.read();

                }

                //int responseCode = urlConnection.getResponseCode();
                //if(responseCode == HttpsURLConnection.HTTP_OK){
                    return result;
                //}else{
                //    return "Wrong Creditinal";
                // }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i("Access Token", result);
        }
    }

    public void login(View view) {

        if (!validate()) {
            onLoginFailed();
            return;
        }
        final String email = emailText.getText().toString();
        final String password = passwordText.getText().toString();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        final int client_id = prefs.getInt("client_id", 1);
        final String client_secret = prefs.getString("client_secret", " ");


        loginButton.setEnabled(false);

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Verifying...");
        progressDialog.show();

        // TODO: Implement your own authentication logic here.
        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        MakeAccessToken task = new MakeAccessToken();
                        task.execute("http://10.0.2.3:8000/oauth/token?grant_type=password&client_id="+client_id+"&client_secret="+client_secret+"&username="+email+"&password="+password);
                    }
                }, 3000);

    }



    public void onLoginSuccess() {
        loginButton.setEnabled(true);
        Intent profileIntent = new Intent(getApplicationContext(), Profile.class);
        startActivity(profileIntent);
    }

    public void onLoginFailed() {
        Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

        loginButton.setEnabled(true);
    }

    public boolean validate() {
        boolean valid = true;

        String email = emailText.getText().toString();
        String password = passwordText.getText().toString();

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            emailText.setError("enter a valid email address");
            valid = false;
        } else {
            emailText.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            passwordText.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            passwordText.setError(null);
        }

        return valid;
    }
}

My api is running in localhost . I am using xampp in windows . Laravel project run on the 8000 port. My code is right as i am able to connect to other api on web . I am able to connect to localhost but not able to access the 8000 port . I have tried many methods like using 10.10.2.2 , 10.10.2.3 . But getting error

java.net.ConnectException: failed to connect to /10.0.2.2 (port 8000): connect failed: ETIMEDOUT

Any help appreciated . Please help me , I am trying to do this for 3 days .

Yash Agarwal
  • 66
  • 16

3 Answers3

2

You'll need to use ip address of the system where your Laravel project is running. Localhost can only be used to connect to a server within same system.

dpaksoni
  • 327
  • 3
  • 17
0

You can have an alternative as SOAP with this having your code in PHP connect to your localhost and your code in android just calls the method to your PHP code.

in PHP code:

<?php   
class service{      
    public function getUser(){
        $user = "root";`enter code here`
        $pass = "";
        $database = "";
        $server = "localhost";
        $mysqli = new mysqli($server,$user,$pass,$database);
        $vquery = "Your query here";                
        //<Your code in iterating the data you can put it as JSON >
        $mysqli->close();
        return $<return JSON user data>;
    }   
}   
$server = new SoapServer(null, array(
'uri' => "urn://<url>",
'soap_version' => SOAP_1_2)
);              
$server->setClass("service");     
$server->handle(); 
?>

IN ANDROID: refer your code here AsyncTask Android example

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • I am not able to understand what you mean – Yash Agarwal Jan 03 '17 at 09:26
  • There is an alternative solution for this and it is the SOAP from android you call your method to PHP Code embedded on your laravel folder the php method then query to your localhost. –  Jan 03 '17 at 09:31
  • Yeah you put this on your folder and then setup your localhost server to listen –  Jan 04 '17 at 01:02
0

Instead of localhost you should use ip along with port number if any. Say your ip is 10.10.2.2 and your port is 8000. Then your URL should be something like this:

http://10.10.2.2:8000/Android%20studio/myapplication/loginScript.php

Suresh Kumar
  • 2,014
  • 3
  • 19
  • 32