0

I am coding the login functionality for my android app where it check against my online sql and present the user to the page if login is successful.

But I keep having this error:

E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5 at these lines: Log.d("Login attempt", json.toString()) and class AttemptLogin extends AsyncTask

How do I solve it? Attached below is the code. Thanks in advance!

JSONParser.java

package com.test.qingyong.test;

/**
 * Created by QingYong on 09/08/2015.
 */
import org.apache.http.HttpEntity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

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

    // default no argument constructor for jsonpaser class
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Executing POST request & storing the response from server  locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();

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

        try {


            // Create a BufferedReader
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declaring string builder
            StringBuilder str = new StringBuilder();
            //  string to store the JSON object.
            String strLine = null;

            // Building while we have string !equal null.
            while ((strLine = reader.readLine()) != null) {
                str.append(strLine + "\n");
            }

            // Close inputstream.
            is.close();
            // string builder data conversion  to string.
            json = str.toString();
        } catch (Exception e) {
            Log.e("Error", " something wrong with converting result " + e.toString());
        }

        // Try block used for pasrseing String to a json object
        try {
            jsonObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("json Parsering", "" + e.toString());
        }

        // Returning json Object.
        return jsonObj;

    }



    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Make HTTP request
        try {

            // checking request method
            if(method == "POST"){

                // now defaultHttpClient object
                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 str = new StringBuilder();
            String strLine = null;
            while ((strLine = reader.readLine()) != null) {
                str.append(strLine + "\n");
            }
            is.close();
            json = str.toString();
        } catch (Exception e) {

        }

        // now will try to parse the string into JSON object
        try {
            jsonObj = new JSONObject(json);
        } catch (JSONException e) {

        }


        return jsonObj;

    }

}

Login.java

package com.test.qingyong.test;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener{

    private EditText user, pass;
    private Button bLogin;
    // Progress Dialog
    private ProgressDialog pDialog;
    // JSON parser class
    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = "http://powerbankk.16mb.com/test.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
        bLogin = (Button)findViewById(R.id.login);
        bLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.login:
                new AttemptLogin().execute();
                // here we have used, switch case, because on Login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , menu than this we could also do this without switch //case.
            default:
                break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting for Login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // here Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");

                JSONObject json = jsonParser.makeHttpRequest(
                        LOGIN_URL, "POST", params);

                // checking  log for json response
                Log.d("Login attempt", json.toString());

                // success tag for json
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Successfully Login!", json.toString());

                    Intent ii = new Intent(Login.this,OtherActivity.class);
                    finish();
                    // this finish() method is used to tell android os that we are done with current //activity now! Moving to menu activity
                    startActivity(ii);
                    return json.getString(TAG_MESSAGE);
                }else{

                    return json.getString(TAG_MESSAGE);

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

            return null;
        }
        /**
         * Once the background process is done we need to  Dismiss the progress dialog asap
         * **/
        protected void onPostExecute(String message) {

            pDialog.dismiss();
            if (message != null){
                Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
            }
        }
    }
}

Login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:orientation="vertical" >

    <Button
        android:id="@+id/login"
        android:layout_width="118dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/password"
        android:layout_alignRight="@+id/password"
        android:layout_below="@+id/password"
        android:text="login" />

    <EditText
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/password"

        android:ems="10"
        android:focusable="true"
        android:hint="Enter username"
        android:imeOptions="actionNext"
        />

    <EditText
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Enter Password"
        android:imeOptions="actionDone"
        />

</RelativeLayout>

test.php

<?php
  mysql_connect("mysql.hostinger.in","username","password");
  $db= mysql_select_db("db");
  $password=$_POST["password"];
  $username=$_POST["username"];

  if (!empty($_POST)) {
  if (empty($_POST['username']) || empty($_POST['password'])) {
  // Create some data that will be the JSON response 
          $response["success"] = 0;
          $response["message"] = "One or both of the fields are empty .";

          //die is used to kill the page, will not let the code below to be executed. It will also
          //display the parameter, that is the json data which our android application will parse to be //shown to the users
          die(json_encode($response));
      }
  $query = " SELECT * FROM test WHERE username = '$username'and password='$password'";

     $sql1=mysql_query($query);
  $row = mysql_fetch_array($sql1);
  if (!empty($row)) {
       $response["success"] = 1;
          $response["message"] = "You have been sucessfully login";
         die(json_encode($response));
  }
  else{

  $response["success"] = 0;
          $response["message"] = "invalid username or password ";
  die(json_encode($response));
  }



  }
  else{

  $response["success"] = 0;
          $response["message"] = " One or both of the fields are empty ";
  die(json_encode($response));
  }

  mysql_close();
  ?>
Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29
Qing Yong
  • 127
  • 3
  • 15
  • 1
    Probably `json` is `null` – ρяσѕρєя K Aug 10 '15 at 04:38
  • Does it work without that line of code? – SaNtoRiaN Aug 10 '15 at 04:49
  • JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params); this is not returning a JsonObject, it simply failed to return probably null – King of Masses Aug 10 '15 at 04:56
  • Log the value of the String returned before you try to create the JSONObject with the result. Also, FWIW, I made an updated version of the JSONParser class that uses HttpURLConnection instead of the deprecated DefaultHttpClient that the old one uses, take a look at my blog post about it, which also includes sample AsyncTasks: http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html – Daniel Nugent Aug 10 '15 at 05:08
  • @DanielNugent Ok after changing the JSONParser I got this new error: List params = new ArrayList(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); Log.d("request!", "starting"); JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params); paramas has an invalid 3rd argument type and BasicNameValuePair is deprecated. any soln? – Qing Yong Aug 10 '15 at 05:39
  • Try to debug and check value in json object ... – Iamat8 Aug 10 '15 at 05:42
  • @qing look at the AsyncTasks in the blog post, BasicNameValuePair is deprecated so I used a HashMap instead. – Daniel Nugent Aug 10 '15 at 05:58
  • You should also be passing in the username and password through the execute() method, it's not good to reference UI elements in a background thread. Again, look at all of the code in the blog post. – Daniel Nugent Aug 10 '15 at 06:03
  • Ok i have implemented what u wanted me to do. But my parser still have this error: Error parsing data org.json.JSONException: Value tt
    – Qing Yong Aug 10 '15 at 12:55
  • That is html, looks like your server is returning an error message. – Daniel Nugent Aug 10 '15 at 14:05
  • @DanielNugent I logged in successfully with the result: {"success":1,"message":"You have been sucessfully login"} but I am not sure why the result returned from the server cannot convert it into a json obj – Qing Yong Aug 10 '15 at 14:27
  • @DanielNugent If you don't mind can i have a working copy of the code? – Qing Yong Aug 10 '15 at 14:53
  • @DanielNugent Hey sorry for the no reply but I am glad to say after referencing to your code, it works now! :D Thanks alot! – Qing Yong Aug 14 '15 at 11:03
  • Nice, glad to hear you got it working! – Daniel Nugent Aug 14 '15 at 14:54
  • @DanielNugent Just to ask if u have a guide to do something like to display nearby markers where the user is currently at. – Qing Yong Aug 15 '15 at 16:20
  • Here is an example of using the google places web service API: http://stackoverflow.com/questions/30161395/im-trying-to-search-nearby-places-such-as-banks-restaurants-atms-inside-the-d – Daniel Nugent Aug 15 '15 at 16:47
  • @DanielNugent Thanks for the example but I am looking at self-created markers on the map and using nearest location to detect these markers. – Qing Yong Aug 16 '15 at 04:27
  • @DanielNugent Hi Daniel, could you drop me an email at masterong10@hotmail.com? Got some jsonparser stuff to ask u. Thanks. – Qing Yong Sep 11 '15 at 15:00

1 Answers1

0

Try using Volley or Retrofit .They are faster and error handling is a lot easier than async task.

Jawad Ahmed
  • 306
  • 1
  • 5
  • 9