0

我有一个应用程序,当用户单击按钮时,在列表视图上单击的项目将保存到 MySQL 数据库中。我创建了一个数组,还编写了一个类来执行异步 http post 操作。但是,没有任何内容被发布到数据库中,并且我得到了一个响应,即得到一个无效的 json 解析异常

下面是代码:

//array to hold the data
ArrayList <String>friends = new ArrayList<String>();

  //listview click event
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
            .toString();
          friends.add(pid);
            }
     // Button to save array
   Button fr=(Button)findViewById(R.id.savefriends);
    fr.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            }
         new SaveFriends().execute();

    }


});          
     // Asynch Class To Store Array

    class SaveFriends extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog=ProgressDialog.show(AllFriends.this, "", "Saving Friends List. Please wait...", true, false);
    }

    /**
     * Creating friendlist
     * */
    protected String doInBackground(String... args) {
        String user_id ="23";
        String friend_id =friends.toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("user_id", user_id));
        params.add(new BasicNameValuePair("friend_id", friend_id));
                    // getting JSON Object
                    JSONObject json = jParser.makeHttpRequest(url_create_friends,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
                Intent i = new Intent(getApplicationContext(), FriendsList.class);
                startActivity(i);

                // closing this screen
                finish();
            } else {
                // failed to create friends
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }


}
   //JSONParser Class For HttpRequests
      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 method
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;

}

  //php script 
 <?php       
  // array for JSON response
  $response = array();

  // check for required fields
 if (isset($_POST['user_id']) && isset($_POST['friend_id'])) {

  $user_id = $_POST['user_id'];
  $friend_id = $_POST['friend_id'];

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

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

// mysql inserting a new row
  foreach($_POST['friend_id'] as $val) {


$result = mysql_query("INSERT INTO friends(primary_friend,friend_id)       
 VALUES('$user_id', '$val')");
    }
// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
     echo json_encode($response);
       } else {
      // failed to insert row
      $response["success"] = 0;
      $response["message"] = "Oops! An error occurred.";

      // echoing JSON response
    echo json_encode($response);
   }
 } else {
// required field is missing
 $response["success"] = 0;
 $response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
  }
  ?>
4

1 回答 1

0
method == "POST" 

将不起作用,因为您正在尝试比较字符串。改为使用method.equals("POST")


为了确保这样的错误不会再次出现,我建议您开始遵循我使用的约定,而不是比较字符串,而应该使用数字比较。让我演示一下:

 private static final int METHOD_POST = 1;
 private static final int METHOD_GET = 2;

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

    if (method == METHOD_POST) {

    }

    else if (method == METHOD_GET) {

    }

}


 makeHttpRequest("url", METHOD_POST, params);

为什么使用数字是因为它不易出错,因为数字是数字,而字符串通常包含更多字符。在我看来,它看起来也更专业。

于 2013-03-08T15:56:30.473 回答