0

I have an EdiText i want to send it over web by using queryString(includes also special characters),I have used urlEncoder for it.

But when i am getting the entered text back from the web ,it gives me org.json.JSONException: Unterminated object at character error,It gives me error especially when i entered " "(comma) and single ' ' in request url,my code is as below.

Please help me how to get comma and single coma from web without any exception in android.

main.java

public class ChatHistoryActivity extends Activity {
    private ProgressDialog pDialog;
    JSONArray msgArry;
    JSONObject jsonObj;
    private ChatAdapter chatContent;
    ArrayList<HashMap<String, String>> msgList;
    ListView lv;
    JSONArray msgs = null;
    String pro_id, pro_name, pro_img, grup_id, sender_id, cust_id;
    TextView tv_switch;
    public boolean flag = false;
    Header header;
    Menu menu;
    Intent in;
    Button reply;
    RelativeLayout rl_reply;
    EditText et_reply;
    String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_chat_history);
        lv = (ListView) findViewById(R.id.list);
        tv_switch = (TextView) findViewById(R.id.tv_switch);
        header = (Header) findViewById(R.id.header_msg);
        menu = (Menu) findViewById(R.id.menu_msg);
        reply = (Button) findViewById(R.id.btn_reply);
        rl_reply = (RelativeLayout) findViewById(R.id.rl_reply);
        rl_reply.setVisibility(View.GONE);
        et_reply = (EditText) findViewById(R.id.et_reply);
        menu.setSelectedTab(3);
        header.title.setText("Conversation");
        msgList = new ArrayList<HashMap<String, String>>();

        pro_id = getIntent().getStringExtra(Const.TAG_PRODUCT_ID);
        sender_id = getIntent().getStringExtra(Const.TAG_CUSTOMER_ID);
        grup_id = getIntent().getStringExtra(Const.TAG_GROUP_ID);
        cust_id = Pref.getValue(ChatHistoryActivity.this, Const.PREF_CUSTOMER_ID, "");

        /* new GetChatHistory().execute(); */

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // getting values from selected ListItem
                rl_reply.setVisibility(View.VISIBLE);

            }

        });
        // message reply ...!!Chat api(conversation)
        reply.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                new DoReply().execute();
                // new GetChatHistory().execute();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        new GetChatHistory().execute();
    }

    private class GetChatHistory extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ChatHistoryActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            BackendAPIService sh = new BackendAPIService();
            String query = Const.API_CHAT_HISTORY;
            url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&sender_id=" + sender_id + "&product_id=" + pro_id;

            url = query + url;
            System.out.println(":::::::::::::My MESSGES URL::::::::::::::in chat" + url);

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);

            Log.d("Response: ", "> " + jsonStr);
            try {
                if (jsonStr != null) {
                    msgArry = new JSONArray(jsonStr);
                    if (msgArry != null && msgArry.length() != 0) {
                        // looping through All Contacts

                        System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
                        for (int i = 0; i < msgArry.length(); i++) {
                            JSONObject c = msgArry.getJSONObject(i);

                            String custID = c.getString(Const.TAG_CUSTOMER_ID);
                            String custName = c.getString(Const.TAG_CUSTOMER_NAME);
                            String proID = c.getString(Const.TAG_PRODUCT_ID);
                            String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
                            String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
                            String msg_body = c.getString(Const.TAG_MESSAGE_BODY);
                            /*msg_body = URLDecoder.decode(msg_body, "utf-8");*/
                            HashMap<String, String> message = new HashMap<String, String>();

                            message.put(Const.TAG_CUSTOMER_ID, custID);
                            message.put(Const.TAG_CUSTOMER_NAME, custName);
                            message.put(Const.TAG_PRODUCT_ID, proID);
                            message.put(Const.TAG_CUSTOMER_EMAIL, email);
                            message.put(Const.TAG_PHOTO, photo);
                            message.put(Const.TAG_MESSAGE_BODY, msg_body);

                            msgList.add(message);

                        }
                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Utils.showCustomeAlertValidation(ChatHistoryActivity.this, "No messgaes found", "yehki", "Ok");
                                msgList.clear();
                            }
                        });

                    }

                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog != null)
                pDialog.dismiss();
            System.out.println("::::::::::::inside post:::::::::::");
            chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
            chatContent.notifyDataSetChanged();
            lv.setStackFromBottom(true);
            lv.setAdapter(chatContent);

            et_reply.setText("");

        }
    }

    /*
     * GET CONVERSATION LIST.........REPLY
     */
    private class DoReply extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ChatHistoryActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            BackendAPIService sh = new BackendAPIService();
            String query = Const.API_MESSAGE_REPLY;
            String msg = et_reply.getText().toString().trim();

            try {
                msg = URLEncoder.encode(msg, "utf-8");

            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&receiver_id=" + sender_id + "&product_id=" + pro_id + "&message=" + msg;
            url = query + url;
            System.out.println(":::::::::::::My MESSGES URL::::::::::::::in doreply" + url);

            System.out.println(":::::::::::::::get chat history called:::::::::::::;;");
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);

            Log.d("Response: ", "> " + jsonStr);
            try {
                if (jsonStr != null) {
                    jsonObj = new JSONObject(jsonStr);
                    if (jsonObj.getString("status").equals("sucess")) {
                        // et_reply.setText("");
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(ChatHistoryActivity.this, "Message has been sent", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        // et_reply.setText("");
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(ChatHistoryActivity.this, "Message has not been sent", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            System.out.println("::::::::::::inside post:::::::::::");
            // Dismiss the progress dialog
            if (pDialog != null)
                pDialog.dismiss();

            chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);

            lv.setStackFromBottom(true);
            lv.setAdapter(chatContent);

            msgList.clear();
            chatContent.notifyDataSetChanged();
            new GetChatHistory().execute();

        }
    }

}
3
  • Can you give us the String that you're trying to parse ? May 5, 2014 at 12:05
  • @ShivamVerma - yep i am giving you url below:yehki.epagestore.in/app_api/…
    – Jigar jims
    May 5, 2014 at 12:07
  • 1
    @Jigarjims Your JSON is not valid. Use JSON Lint for that.
    – Piyush
    May 5, 2014 at 12:08

1 Answer 1

1

This is where the error is, because " is a special character for JSON. You'll need to escape the quotes.

{
    "customer_id": "41",
    "product_id": "72",
    "message_body": ""'"",  //Error 
    "customer_name": "Jigar makwana",
    "email": "[email protected]",
    "photo": "upload/jimmy.jpg"
}

Also, this : How to escape double quotes in JSON

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.