0

I am trying to authenticate an app from android studio to mySQL using Json through a servlet. I Keep getting this parsing error.. Following are the snippets of my code. please help me.

MainActivity class written android studio

--------------
public class MainActivity extends ActionBarActivity {
    EditText uname, password;
    Button submit;

    JSONParser jParser = new JSONParser();

    JSONObject json;

    private static String url_login = "http://192.168.10.125:8080/CabbCallLogin/LoginServlet";
    //JSONArray incoming_msg = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewsById();
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View args0) {
                // execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL
                //and get output response from InputStream and return it.
                new Login().execute();

            }
        });
    }
    private void findViewsById() {

        uname = (EditText) findViewById(R.id.txtUser);
        password = (EditText) findViewById(R.id.txtPass);
        submit = (Button) findViewById(R.id.button1);
    }

    private class Login extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... args) {
            Log.e("Error001" , "I am in background");
            // Getting username and password from user input
            String username = uname.getText().toString();
            String pass = password.getText().toString();
            Log.e("Error004", "I have got the uname,pass");
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("u",username));

            params.add(new BasicNameValuePair("p",pass));
            Log.e("Error00", "I have got the name value pairs");

            json = jParser.makeHttpRequest(url_login, "GET", params);
            Log.e("Error00" , "I have sent the request");

            String s=null;

            try{
                s= json.getString("info");
                Log.e("Msg", json.getString("info"));
                Log.e("Error" , "I am in the try catch");
                if(s.equals("success")){
                    Log.e("Error1" , "I am in the if try catch");
                    Intent login = new Intent(getApplicationContext(), Welcome.class);
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    finish();

                }else{
                    Log.e("Error2" , "I am in the else try catch");
                       ErrorMessage("Error" , "I m in the else part of login");
                }

            }catch (JSONException e){
                Log.e("Error3" , "I am in the json try catch");
                e.printStackTrace();
                ErrorMessage("Error", "I m in the json exception part of login");
            }

                  return null;

        }
    }
    private void ErrorMessage(String Title , String Message){

        AlertDialog.Builder alertbuilder = new AlertDialog.Builder(MainActivity.this);

        alertbuilder.setMessage("Incorrect Credentials");
        alertbuilder.setPositiveButton("Ok", null);
        alertbuilder.show();

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

------------------------------------------

JSONParser class 
public class JSONParser {

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

    static InputStream iStream = null;
    static JSONArray jarray = null;

    public JSONParser() {

    }


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

        // Making HTTP request

        Log.e("Error003" , "I am in the JSONOBJECT class");
        try {

            if(method == "POST"){
                // request method is POST
                // defaultHttpClient

                Log.e("Error003" , "I am in the JSONOBJECT post method");
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url_login);
                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
                Log.e("Error003" , "I am in the JSONOBJECT get method");
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url_login += "?" + paramString;
                HttpGet httpGet = new HttpGet(url_login);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

                Log.e("Error004" , "I am at end the JSONOBJECT get method");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            Log.e("Error003" , "I am in the Buffer class");
            BufferedReader reader = new BufferedReader(new InputStreamReader (is, "UTF-8"), 8);
            Log.e("Error004" , "I am in the Buffer class");
            StringBuilder sb = new StringBuilder();
            Log.e("Error005" , "I am in the Buffer class");
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();

        }catch (Exception e) {
            Log.e("Buffer Error1", "Error converting result " + e.toString());
        }
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser1", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }


    public JSONArray getJSONFromUrl(String url_login,String method,  List<NameValuePair> params) {



        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url_login);

        try{

            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser2", "Error parsing data " + e.toString());
        }
// return JSON Object
        return jarray;
    }

    public JSONObject makeHttpRequest2(String url_login) {


        // 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_login);
            //  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, "UTF-8"), 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 Error2", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser3", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
    }
7
  • 1
    Error is not in your code, but in your data. Check the text you're trying to parse as JSON for some non-ASCII characters (e.g. letters with accents or something like that) and try to eliminate them in some way Commented Sep 28, 2015 at 9:53
  • You are parsing a String by a json Commented Sep 28, 2015 at 9:55
  • @MisaLazovic exactly where are you saying i m passing a non ASCII? can u please pin point? Commented Sep 28, 2015 at 9:57
  • @Gunaseelan Can u please elaborate? Commented Sep 28, 2015 at 10:35
  • @NofalIdrees In any input your app takes. I can't tell exactly, could be info... Try logging any input as string before trying to parse the json Commented Sep 28, 2015 at 10:46

1 Answer 1

0

your code expect a json object , when the data it receives is a string . unless you want your android to receive string , you should check the service / data source

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

1 Comment

Sister, i want my android to receive the string how should i do that can u please elaborate?

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.