加载JSON对象时出错

时间:2016-07-13 17:03:58

标签: java android json

在本地,当我点击按钮"登录"我有这个例外吗?

> W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

这是我的代码;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;

DBConnect.php:

class DB_Connect {
    private $conn;

    // Connecting to database
    public function connect() {
        require_once 'include/Config.php';

        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

        // return database handler
        return $this->conn;
    }
}

DBFunction.php:

class DB_Functions {

    private $conn;

    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $db = new Db_Connect();
        $this->conn = $db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt

        $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
        $result = $stmt->execute();
        $stmt->close();

        // check for successful store
        if ($result) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            return $user;
        } else {
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {

        $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");

        $stmt->bind_param("s", $email);

        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            // verifying user password
            $salt = $user['salt'];
            $encrypted_password = $user['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $user;
            }
        } else {
            return NULL;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");

        $stmt->bind_param("s", $email);

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // user existed 
            $stmt->close();
            return true;
        } else {
            // user not existed
            $stmt->close();
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

注册ACTIVITY.java:

public class RegisterActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnRegister;
    private Button btnLinkToLogin;
    private EditText inputFullName;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        inputFullName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // Session manager
        session = new SessionManager(getApplicationContext());

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(RegisterActivity.this,
                    MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String name = inputFullName.getText().toString().trim();
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                    registerUser(name, email, password);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Please enter your details!", Toast.LENGTH_LONG)
                            .show();
                }
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * Function to store user in MySQL database will post params(tag, name,
     * email, password) to register url
     * */
    private void registerUser(final String name, final String email,
                              final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_REGISTER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

登录ACTIVITY.java:

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

这是AppConfig.java

public class AppConfig {
    // Server user login url
//  public static String URL_LOGIN = "http://192.168.0.102/android_login_api/login.php";
    //public static String URL_LOGIN = "http://10.0.2.2:8888/android_login_api/login.php";
    public static String URL_LOGIN = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/login.php";



    // Server user register url
    //public static String URL_REGISTER = "http://10.0.2.2:8888/android_login_api/register.php";
    public static String URL_REGISTER = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/register.php";

}

register.php:

require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {

    // receiving the post params
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // check if user is already existed with the same email
    if ($db->isUserExisted($email)) {
        // user already existed
        $response["error"] = TRUE;
        $response["error_msg"] = "User already existed with " . $email;
        echo json_encode($response);
    } else {
        // create a new user
        $user = $db->storeUser($name, $email, $password);
        if ($user) {
            // user stored successfully
            $response["error"] = FALSE;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user failed to store
            $response["error"] = TRUE;
            $response["error_msg"] = "Unknown error occurred in registration!";
            echo json_encode($response);
        }
    }
} else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters (name, email or password) is missing!";
    echo json_encode($response);
}

的login.php:

require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['email']) && isset($_POST['password'])) {

    // receiving the post params
    $email = $_POST['email'];
    $password = $_POST['password'];

    // get the user by email and password
    $user = $db->getUserByEmailAndPassword($email, $password);

    if ($user != false) {
        // use is found
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        echo json_encode($response);
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        echo json_encode($response);
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters email or password is missing!";
    echo json_encode($response);
}

logcat的:

07-13 19:55:24.137 11917-11917/ W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-13 19:55:24.137 11917-11917/ W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
07-13 19:55:24.137 11917-11917/ W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:158)
07-13 19:55:24.137 11917-11917/ W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:171)
07-13 19:55:24.137 11917-11917/ W/System.err:     at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:127)
07-13 19:55:24.137 11917-11917/ W/System.err:     at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:119)
07-13 19:55:24.137 11917-11917/ W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
07-13 19:55:24.137 11917-11917/ W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
07-13 19:55:24.137 11917-11917/ W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
07-13 19:55:24.137 11917-11917/ W/System.err:     at android.os.Handler.handleCallback(Handler.java:605)
07-13 19:55:24.137 11917-11917/ W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:92)
07-13 19:55:24.137 11917-11917/ W/System.err:     at android.os.Looper.loop(Looper.java:137)
07-13 19:55:24.137 11917-11917/ W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:4424)
07-13 19:55:24.137 11917-11917/W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
07-13 19:55:24.137 11917-11917/ W/System.err:     at java.lang.reflect.Method.invoke(Method.java:511)
07-13 19:55:24.137 11917-11917/ W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-13 19:55:24.137 11917-11917/ W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-13 19:55:24.137 11917-11917/ W/System.err:     at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:0)

输出

json_encode()然后尝试解析它。它将解决您的问题。

答案 1 :(得分:0)

我遇到了同样的情况,我为它创建了模块。我附加了一个示例代码,如何将json对象从php恢复到android。 你的PHP代码必须是: -

<?php 
 // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();

$class_id="2";
     function getClassById($class_id) {
$ss="SELECT * FROM student WHERE class_id = '$class_id'";
        $result = mysql_query($ss) or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
                return $result;
            }
         else {
            // user not found
            return false;
        }
    }


 $user =getClassById($class_id);
        if ($user != false) {
            $response["success"] = 1;
            $response["user"]["class_id"] = $user["class_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["enrolment"] = $user["enrolment"];
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }

    ?>

现在你的代码可以是你想要的任何东西但它必须有json_encode()来获取android中的json对象。 现在你的android编码必须像。

public class UserFunctions {
    private JSONParser jsonParser;
    private static final String TAG_RESULTS="result";
    private static final String TAG_ID = "id";
    private static final String TAG_YEAR = "yearof";
    private static final String TAG_BRANCH ="branchof";
    private static final String TAG_SECTION ="sectionof";
    private static final String TAG_ClassKey ="classkey";
    private static final String TAG_cordinator ="coordinatoremail";
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    //URL of the PHP API
    private static String GetbunkstudentURL = "http://169.254.90.189/learn2crack_login_api/getabsentstudent/getabsentstudent.php";
    private static String bunk_tag = "bunk";
    private static String register_tag = "register";      // constructor
    public UserFunctions(){
        jsonParser = new JSONParser();
    }
  public JSONObject getBunkStudent(String lecture1, String lecture2) {
          // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", bunk_tag));
        params.add(new BasicNameValuePair("lec1", lecture1));
        params.add(new BasicNameValuePair("lec2", lecture2));
        JSONObject json = jsonParser.getJSONFromUrl(GetbunkstudentURL, params);
        return json;
    }
}

现在你的jsonparser.java类必须是: -

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

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

        // Making HTTP request
        try {
            // 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();

        } 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 sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } 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;

    }
}

在活动或片段中调用这些函数的代码在这里,

public class seeBunkedStudentFragment extends ListFragment {
    String myJSON;
    private static final String KEY_STUDENT="student";
    private static final String TAG_RESULTS="result";
    private static final String TAG_ID = "id";
    private static final String TAG_ClassDet = "classdetails";
    private static final String TAG_YEAR = "yearof";
    private static final String TAG_BRANCH ="branchof";
    private static String KEY_SUCCESS = "success";
    private static String KEY_UID = "uid";
    private static String KEY_USERNAME = "uname";
    private static String KEY_FIRSTNAME = "fname";
    private static String KEY_LASTNAME = "lname";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";
    private static final String TAG_SECTION ="sectionof";
    //////tags
    private static final String TAG_TID = "tid";
    private  static final String Tag_Classid="classid";
    private  static final String Tag_Classkey="classkey";
    private  static final String Tag_schedid="scheduleid";
    ////////
    JSONArray peoples = null;
    JSONArray contacts = null;


    ArrayList<HashMap<String, String>> contactList;
    public  ArrayList<HashMap<String, String>> personList;

    ListView list;
    private HashMap<String, String> singleclass;
    String userdetail[]=new String[5];
    private String todayda;
    private String result;
    private String ccid,ssid;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v= inflater.inflate(R.layout.bunkstudentlist,null);

        list = (ListView) v.findViewById(R.id.list);



        NetAsync(v);

        contactList = new ArrayList<HashMap<String, String>>();

        personList = new ArrayList<HashMap<String,String>>();




        return v;
    }

    private class NetCheck extends AsyncTask<String,String,Boolean>
    {
        private ProgressDialog nDialog;

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            nDialog = new ProgressDialog(getActivity());
            nDialog.setTitle("Checking Network");
            nDialog.setMessage("Loading..");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();
        }
        @Override
        protected Boolean doInBackground(String... args){


/**
 * Gets current device state and checks for working internet connection by trying Google.
 **/
            /*
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(3000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }*/
            // return false;
            return true;
        }
        @TargetApi(Build.VERSION_CODES.CUPCAKE)
        @Override
        protected void onPostExecute(Boolean th){

            if(th == true){
                nDialog.dismiss();
                new ProcessLogin().execute();
            }
            else{
                nDialog.dismiss();
                Toast.makeText(getActivity().getApplicationContext(), "Error in Network Connection", Toast.LENGTH_LONG).show();
            }
        }
    }

    private class ProcessLogin extends AsyncTask<String, String, JSONObject> {


        private ProgressDialog pDialog;


        String uniq;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setTitle("Contacting Servers");
            pDialog.setMessage("Logging in ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) {
            String lecture1="1";
            String lecture2="2";


            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.getBunkStudent(lecture1,lecture2);
            try {
                if (json.getString(KEY_SUCCESS) != null) {


                    String res = null;
                    try {
                        res = json.getString(KEY_SUCCESS);
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    res= json.getString("success");
                    JSONArray json_user = json.getJSONArray("user");
                    int llenggt=json_user.length();
                    if(Integer.parseInt(res) == 1){

                        for (int i = 0; i < json_user.length(); i++) {
                            JSONObject c = json_user.getJSONObject(i);

                            String tid = c.getString("teacherid");
                            String classid= c.getString("enrollmentnumber");
                            String classkey= c.getString("classid");

                            Log.d("firstjson",tid+""+classid+""+classkey);
                            // tmp hashmap for single contact
                            HashMap<String, String> contact = new HashMap<String, String>();

                            //TAG_TID, Tag_Classid,                Tag_Classkey                           // adding each child node to HashMap key => value
                            contact.put(TAG_TID, tid);
                            contact.put(Tag_Classid, classid);
                            contact.put(Tag_Classkey, classkey);

// adding contact to contact list
                            contactList.add(contact);



                        }
                    }
                }
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            ////
            myJSON=result;


            return json;



        }

        @Override
        protected void onPostExecute(JSONObject json) {

            if (pDialog.isShowing())
                pDialog.dismiss();

            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), contactList,
                    R.layout.item_fetch_lec2, new String[]{TAG_TID, Tag_Classid,
                    Tag_Classkey}, new int[]{R.id.name,
                    R.id.email, R.id.mobile});
            setListAdapter(adapter);

        }
    }

    public void NetAsync(View view){
        new NetCheck().execute();
    }

//////code for othere async task
}

我认为这会有所帮助,您只需参考这些代码即可。

答案 2 :(得分:0)

在JSONObject的行之前添加此代码,

Log.i("tagconvertstr", "["+response+"]");

然后你就可以知道你的错误是什么了。

别忘了在Manifest.xml中调用AppController类