将数据解析为JSON对象时出错从000webhost.com返回

时间:2017-08-29 12:16:34

标签: php android json

我将php文件和数据库上传到000webhost.com。当我在localhost中测试时,我的adnroid应用程序工作正常。但在我将我的网址更改为“http://utyatanarponcybercity.000webhostapp.com/public_html/memberLogin.php”后,它开始显示“解析数据时出错org.json.JSONException:Value

这是memberlogin.php

<?php
$response = array();
if($_POST['user_name']==NULL || $_POST['password']==NULL) {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    //$response["usertype"]="null";

    // echoing JSON response
    echo json_encode($response);
}
else{
    $uname=$_POST['user_name'];
    $pas=$_POST['password'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    $result = mysql_query("SELECT * FROM user_account WHERE user_name='$uname' && password='$pas'") or die(mysql_error());
    $row = mysql_fetch_array($result);
    $no=mysql_num_rows($result);
    if($no ==0){
        $response["success"]=0;
        $response["message"]="Username or Password Incorrect";
        $response["usertype"]="null";



        // echoing JSON response
        echo json_encode($response);
    } else {
            $utype = $row["user_type"];
            $cId = $row["classID"];
            $uId= $row["userID"];
        // successfully login
        $response["success"] = 1;
        $response["message"] = "Successfully login.";
        $response["usertype"]=$utype;
        $response["classID"]=$cId;
        $response["userID"]=$uId;

        echo json_encode($response);
        }
    }

?>

这是MainActivity.class

package com.example.utyccschedulefinal;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    // Progress Dialog
    private ProgressDialog pDialog1;

    JSONParser jsonParser = new JSONParser();
    EditText uName;
    EditText pass;
    String existingInput;

    private static String url = "http://utyatanarponcybercity.000webhostapp.com/public_html/memberLogin.php";

    private static JSONObject json;
    private static String type,classid,userid,startdate,enddate;
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_USERTYPE = "usertype";
     public enum Command {Admin,Member};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Edit Text
        uName = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);

        // Create button
        Button login = (Button) findViewById(R.id.btnLogin);
        String checkLogin=checkFile("Login.txt");
                if(checkLogin.equals("yes")) {
                    Intent in = new Intent(MainActivity.this,
                            userPage.class);
                            in.putExtra("classid", classid);
                            startActivity(in);
                            finish();
                }
        // button click event
        login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new userLogin().execute();
            }
        });
    }
    private String checkFile(String s) {
        FileInputStream input=null;
        try {
               input=this.openFileInput(s);
               int maxBytes=input.available();
                byte[] data=new byte[maxBytes];
                input.read(data,0,maxBytes);
                while(input.read()!=-1){};
                existingInput=new String(data);
                //textmsg.setText(existingInput);    

        }
        catch (Exception e) {
               e.printStackTrace();
    }
         finally{
              if(input==null){
                  existingInput="Start";

              }
              else{
                  try {
                        input.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
              }
           }
        return existingInput;
    }
     private void writefile(String a,String b) {
            try {
                   FileOutputStream output=openFileOutput(a, MODE_PRIVATE);
                   byte[] data=b.getBytes();
                   output.write(data);
                   output.close();

                  //display file saved message
                   Toast.makeText(getBaseContext(), "File saved successfully!",
                           Toast.LENGTH_SHORT).show();

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

        }

    /**
     * Background Async Task to Create new product
     * */
    class userLogin extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog1 = new ProgressDialog(MainActivity.this);
            pDialog1.setMessage("Logging In..");
            pDialog1.setIndeterminate(false);
            pDialog1.setCancelable(true);
            pDialog1.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = uName.getText().toString();
            String password = pass.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user_name", name));
            params.add(new BasicNameValuePair("password", password));
            Log.d("work", "first");
            // getting JSON Object
            // Note that create product url accepts POST method
            json = jsonParser.makeHttpRequest(url, "POST", params);
            Log.d("work", "second");
            // check log cat for response
            Log.d("Create Response", json.toString());


            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {


            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                classid= json.getString("classID");
                userid=json.getString("userID");
                startdate=json.getString("startdate");
                enddate=json.getString("enddate");



                if (success == 1){
                    type = json.getString(TAG_USERTYPE);

                    Log.d("userType", type);
                    String file1="classid.txt";
                    String file2="notification.txt";
                    String file3="userid.txt";
                    writefile(file1,classid);
                    writefile(file2,"true");
                    writefile(file3,userid);
                    writefile("start.txt",startdate);
                    writefile("end.txt",enddate);
                    writefile("Login.txt","yes");
                        Log.d("Create response","user work");
                        Intent in = new Intent(MainActivity.this,
                                userPage.class);
                                in.putExtra("classid", classid);
                                startActivity(in);
                                finish();

                    }
                else {
                    // failed to login
                    type = json.getString("message");
                    Toast.makeText(getApplicationContext(), type, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();

            }
            // dismiss the dialog once done
            pDialog1.dismiss();

        }

    }

}

这是JSONParser.class

package com.example.utyccschedulefinal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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 jObj = 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 (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();
        } 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;

    }
}

1 个答案:

答案 0 :(得分:2)

您提供的链接不正确。 试试http://utyatanarponcybercity.000webhostapp.com/memberLogin.php

您必须删除 public_html ,因为它是托管您网站的服务器中的目录。 (根目录)

要访问根目录,只需使用http://utyatanarponcybercity.000webhostapp.com/