1

I have the following code in my json parser . I have tried changing from iso-8859-1 to utf-8. But i always get this error.What have i done wrong?? I could not figure it out of what i have done wrong.

package com.iwantnew.www;    
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 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;

    }
}

I have used mysql for my database. I am new to android with database. help plz! My php file looks like this:

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */1

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['quantity']) && isset($_POST['price']) && isset($_POST['descriptions'])) {

    //$location = $_POST['location'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
    //$productID = $_POST['area'];
    $contact = $_POST['contact'];
    $descriptions = $_POST['descriptions'];

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

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

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO room_tb(quantity, price,description) VALUES('$quantity', '$price','$descriptions')");
    //$result1 = mysql_query("INSERT INTO users(userContactNumber) VALUES('$contact')");

    // check if row inserted or not
    if (($result)/*&& ($result1)*/) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Room added successfully.";

        // 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);
}
?>

MY java file look like this..i have used POST METHod here.

package com.iwantnew.www;

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.widget.Button;
import android.widget.EditText;

public class post_item extends Activity {
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    Button add_room;
    EditText contact_no;
    EditText no_of_room;
    EditText price_per_room;
    EditText description;

    private static String url_create_product = "http://10.0.2.2/android_iwant/android_add_room.php";

    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post_form);

        //contact_no = (EditText) findViewById(R.id.contact_no);
        no_of_room = (EditText) findViewById(R.id.no_of_room);
        price_per_room = (EditText) findViewById(R.id.price_per_room);
        description = (EditText) findViewById(R.id.description);

        add_room = (Button) findViewById(R.id.add_room);

        add_room.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // creating new product in background thread
                new add_new_room().execute();
            }
        });
    }
// suru...
    class add_new_room extends AsyncTask<String, String, String> {

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

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            //String contact = contact_no.getText().toString();
            String quantity = no_of_room.getText().toString();
            String price = price_per_room.getText().toString();
            String descriptions = description.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //params.add(new BasicNameValuePair("contact", contact));
            params.add(new BasicNameValuePair("quantity", quantity));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("descriptions", descriptions));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "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(), MainActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } 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();
        }

    }
}
9
  • Are you sure you are feeding valid JSON? Commented Aug 20, 2013 at 14:40
  • 1
    Do a log message of what the json string is before you try to create a JSON object and make sure it is valid JSON. Commented Aug 20, 2013 at 14:44
  • how to do a log message? Commented Aug 20, 2013 at 14:45
  • I'm not sure if it is a copy-paste error but your PHP script cannot be correctly parsed like that because you have the number 1 right at the top of the script (right after the header comment). That way PHP would give you an error message. Depending on the server configuration with HTML formattings such as "<br>". However, what blackbelt points out is also important. Your Java code does not work like that. And I really have yet to see a single PHP script here on SO without any SQL injection vulnerabilities :-( Commented Aug 20, 2013 at 14:55
  • @Nobu Games i removed that number 1 and the error is gone. But my values inserted are not going to database. Commented Aug 20, 2013 at 15:08

3 Answers 3

3

Blackbelt and Nizam covered the Java side of your problem. I'll cover the PHP side.

The biggest error in your PHP script seems to be the following (unless it's just a copy & paste error):

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */1
   ^
   |
  The number 1 does not belong here

Instead of a JSON string output your PHP script probably just aborts with a syntax error message.

On top of that you have a SQL injection vulnerability in your PHP script. Learn how to use prepared statements.

EDIT: Another mistake I spotted in your PHP script:

if (isset($_POST['quantity']) && isset($_POST['price']) && isset($_POST['descriptions'])) {

You check if the POST parameter "descriptions" is set. It should be "description" without 's' in the end.

Sign up to request clarification or add additional context in comments.

6 Comments

yes i have already removed 1 and the error is gone...but my data is not being inserted to database.
why is not the data going to database
Have you changed your Java code as blackbelt and Nizam pointed out?
yes i have done all the changes....checking post and get in blackbelt style...i have added my java code also ..please have a look
@enjal I edited my answer because I spotted another mistake in your PHP script which is probably the reason you do not see any database changes
|
2

Mostly your mistake is in those lines:

if(method == "POST"){
 }else if(method == "GET")

String comparison in java has to be performed with the equals or equalsIgnoreCase method. In your case, the InputStream is is null, and it is never initialize. So you are trying to convert an empty string, the one the StringBuilder.toString() is returning, into a JSONObject.

Edit:

Change

if(method == "POST"){
 }else if(method == "GET")

with

if(method.equalsIgnoreCase("POST")){
 // your code
 }else if(method.equalsIgnoreCase("GET"))
 // your code

and see if it makes any difference (at least the error should change)

1 Comment

i could not figure out what you are saying. can you plz elaborate it
2

First, make it if(method.equalsIgnoreCase("post")) as 'blackbelt' suggested. One more suggestion-

While receiving some text(whether JSON or not) from server, I'll prefer always check the response before doing any action with it.

Here, try

HttpEntity httpEntity=httpResponse.getEntity();
String all=EntityUtils.toString(httpEntity);
 Log.d("response",all);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.