-2

I am trying to fetch json data in android application using REST services of c#. it is throwing an error:

org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject

I have searched on SO in previous question but couldn't find any useful.

What I have tried is:-

In c#

 public DataTable TestCheckEgrasUserLogin()
    {
        DataTable dt = new DataTable();
        GenralFunction gf = new GenralFunction();
        SqlParameter[] PM = new SqlParameter[2];
        PM[0] = new SqlParameter("@UserName", SqlDbType.VarChar, 50) { Value = UserName };
        PM[1] = new SqlParameter("@Password", SqlDbType.VarChar, 50) { Value = Password };
        dt = gf.Filldatatablevalue(PM, "TestegAndroidUserLoginInfo", dt, null);
        return dt;
    }

I have tested it by running in visual studio, it is working fine and bringing data.

In android:-

   public class MainActivity extends Activity {
   private final static String SERVICE_URI = "`serviceUrl`";

    @Override
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try
                {

                    final EditText usernametxt = (EditText) findViewById(R.id.txtUser);
                    final EditText passwordtxt = (EditText) findViewById(R.id.txtPassword);

                    String username;
                    String Password;
                    username=usernametxt.getText().toString();
                    Password=passwordtxt.getText().toString();


                    if(username=="" || Password=="")
                    {
                        MessageBox("Please Enter UserName or Password");
                    }
                    else if (username.length()<1 || Password.length()<1)
                    {
                        MessageBox("Please Enter Credential Details");
                    }
                    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
                    final    HttpGet request = new HttpGet(SERVICE_URI+username+"/Password/"+Password);
                    request.setHeader("Accept", "application/json");
                    request.setHeader("Content-type","application/json; charset=utf-8");

                    final    DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

                     final   HttpResponse response = httpClient.execute(request);

                    final    HttpEntity responseEntity = response.getEntity();

                    // Read response data into buffer

                    char[] buffer = new char[(int)responseEntity.getContentLength()];
                    String tmpStr10 =  String.valueOf(buffer.length);

                    InputStream stream = responseEntity.getContent();

                    InputStreamReader reader = new InputStreamReader(stream);
                    int sizeOfJSONFile = stream.available();
                                            reader.read(buffer);
                    stream.close();

                    JSONObject vehicle = new JSONObject(new String(buffer));  ** /////Error Comes here**

                    JSONArray plates=new JSONArray(vehicle.getString("CheckEgrasLoginResult"));

                    Bundle B=new Bundle();

                    String UserName= null;
                    String UserId =null;

                    Intent i = new Intent(getApplicationContext(), com.example.nic.newdemosecond.detailsact.class);
                    for (int j = 0; j < plates.length(); ++j) {
                        JSONObject Veh = new JSONObject(plates.getString(j));
                        UserName =  Veh.getString("UserName");
                        UserId =  Veh.getString("UserId");
                    }

                    i.putExtra("UserName", UserName);
                    i.putExtra("UserId", UserId);

                    startActivity(i);
                }
                catch (Exception e)
                {
                    MessageBox("Invalid Login");

                }
            }
        }) ;
}

error is coming at where I declared JsonObject. As I am newbie on android, I am unable to catch this error.

Any help would be appreciated !

Priya
  • 1,359
  • 6
  • 21
  • 41
  • You are reading `XML` and trying to de-serialize as JSON object. – Shree Krishna Mar 30 '16 at 10:04
  • I din't get, can you pls elaborate ? where I am reading xml here ? – Priya Mar 30 '16 at 10:18
  • Simply the error is clear itself you are getting XML data instead of Json data. – Shree Krishna Mar 30 '16 at 10:20
  • Yeah, I can see that, but i am not able to trace it. where m doing wrong :( – Priya Mar 30 '16 at 10:22
  • OK I've added the answer as per your request, And it is sure that you are returning XML from c# code. So that this error was shown. See the answer as well as reference but don't copy and paste. Just modify your codes as that answer. – Shree Krishna Mar 30 '16 at 10:30
  • Why aren't you giving any feedback to answers, either solved or not or anything other error raised. Someone downvoted the answer without telling any reason neither you are giving any response. I was here to help you. – Shree Krishna Mar 31 '16 at 05:00
  • Thanks, But its not helping me. I am not returning xml data from service. it is giving json as well.. yet same error is continue :( – Priya Mar 31 '16 at 06:57

2 Answers2

0

HttpClient, DefaultHttpClient are deprecated they drain battery, more bandwidth in android. use HttpURLConnection instead follow this tutorial http://terrapinssky.blogspot.in/2015/10/android-get-and-parse-json-file-from.html

pavan kvch
  • 153
  • 1
  • 13
-1

You have to return Json instead of XML by using JavaScriptSerializer like shown here

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }

and at last return Json like,

return serializer.Serialize(rows);

NOTE: see this answer for details, and modify this as required.

Community
  • 1
  • 1
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
  • I am using n-tier in service, I think thats why you couldn't get. Its already returning json data. I am not able to understand your answer. where should i change or anything.. – Priya Mar 31 '16 at 07:03
  • is `TestCheckEgrasUserLogin` the method that returns Json ? Can you log your JSon data and paste it please. – Shree Krishna Mar 31 '16 at 07:36
  • Nope, `Filldatatablevalue` is a function. `TestCheckEgrasUserLogin` is a stored procedure name only. – Priya Mar 31 '16 at 09:39
  • @Priya I can find out the error only after seeing JSON. So Kindly paste it. OR you can paste it after modifying. – Shree Krishna Mar 31 '16 at 09:53
  • Actually it is checking whether for login credential whether it exists or not, it is working fine. I have mentioned where my error is coming. error is coming while parsing – Priya Mar 31 '16 at 10:38
  • hehe.. I understood that, But I was saying to post value of `buffer`as string by logging it. – Shree Krishna Mar 31 '16 at 11:09