0

I'm trying to get a response from my server side to my app, and I get null in my HTTP response. When I paste the URL in my browser, I get the wanted response.

The URL: "http://localhost:8080/TBookServerSide/LoginServlet?u=admin&p=123"

The response:

{ "info" : "success" }

Like I get a JSON object back with the word success in my info parameter but, when I try through my android app, I get null instead.

I need to fill the login form (user and password), and then press the login button for it to work.

Here's my code:

LoginFragment.java:

public class LoginFragment extends Fragment {
    public LoginFragment() {
        // Required empty public constructor
    }

    EditText firstNameText;
    EditText lastNameText;
    EditText userNameText;
    EditText passwordText;
    EditText emailText;

    Button loginButton;
    Button signUpPageButton;

    // Creating JSON Parser object
    com.example.liran.tbookandroid.LoginPage.JSONParser jParser = new com.example.liran.tbookandroid.LoginPage.JSONParser();


    private static String url_login = "http://localhost:8080/TBookServerSide/LoginServlet";
    //JSONArray incoming_msg = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_login, container, false);

        (...)

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User newUser = new User();
                String userName = userNameText.getText().toString();
                String password = passwordText.getText().toString();

                newUser.setUserName(userName);
                newUser.setPassword(password);

                Log.d("Press Button:","Login Button has been pressed");
                new LoginWithServlet(newUser).execute();
            }
        });

        return root;
    }

    private class LoginWithServlet extends AsyncTask<String, String, String> {
        JSONObject json;
        User user;
        boolean isUserExist = false;

        public LoginWithServlet(User user) {
            this.user = user;
        }

        @Override
        protected String doInBackground(String... params2) {
            // Getting username and password from user input
            String username = user.getUserName();
            String pass = user.getPassword();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("u", username));
            params.add(new BasicNameValuePair("p", pass));
            json = jParser.makeHttpRequest(url_login, "GET", params);
            String s = null;

            try {
                if (json != null) {
                    s = json.getString("info");
                    Log.d("Msg", json.getString("info"));
                    if (s.equals("success")) {
                        // SUCCEED LOGIN !!!!
                        Log.d("Login Servlet: "," Login Succeed");
                        ((MainActivity) getActivity()).openMainPageFragment();
                        ((MainActivity) getActivity()).showBarButtons();
                    } else {
                        // FAILED LOGIN
                        Log.d("Login Servlet: "," Login failed");
                    }
                } else {
                    Log.e("JSon:"," is NULL");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }
    }

}

JSONParser.java

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    static InputStream iStream = null;
    static JSONArray jarray = null;
    //static String json = "";

    // constructor
    public JSONParser() {}

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // check for request method
            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 (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;

    }
}

LogCat:

com.example.liran.tbookandroid E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
com.example.liran.tbookandroid E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
com.example.liran.tbookandroid E/JSon::  is NULL

I have no idea why it doesn't work as expected, I'd really appreciate your help guys.

Tomasz Dzieniak
  • 2,765
  • 3
  • 24
  • 42
liranahum
  • 143
  • 3
  • 13

3 Answers3

3

http://localhost:8080/ is only being identified by your computer because it is hosted on that machine. Here, localhost means the machine where you have configured your server, and thus your browser is able to locate/find it.

When you call the same on your mobile device, localhost means your mobile device NOT your computer. That's why its not working.

You can still use the local server for development. Try to connect like this.

Community
  • 1
  • 1
Rohit Arya
  • 6,751
  • 1
  • 26
  • 40
  • i'm working with an emulator, so technicaly this is the computer who is asking for the httpresponse – liranahum Mar 21 '16 at 12:36
  • if so, so what should i write instead of localhost? – liranahum Mar 21 '16 at 12:37
  • you should connect your mobile device on the same network as your computer is connected and then find the IP of the computer (the one which local network provides NOT external IP). You can use that IP. – Rohit Arya Mar 21 '16 at 12:39
1

If you are running windows find the computer's ip : press windows key + R then type CMD and then Type ipconfig and press enter

After that you can see your IP address in front of IPv4-Address

type it instead of localhost

M4HdYaR
  • 1,124
  • 11
  • 27
1

Do you know the meaning of localhost?It is a local ip for your personal computer,so you can do it success in your browser.

If you just want do a test in your app.You should open a hotspot by your pc,then make your android phone connect on it.

Or change your local url to a external url like this:http://wthrcdn.etouch.cn/weather_mini?citykey=101010100

banking
  • 480
  • 2
  • 9