PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 19, 2022

[FIXED] Not able to connect to localhost from android emulator

 February 19, 2022     android-emulator, android-studio, api, java, laravel-5     No comments   

Issue

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 .


Solution

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.



Answered By - dpaksoni
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing