0

I've create a web service with JSON and I want to parse it then put them on listview. but when I run the application, it force close and shows error message. please review my code, is there something wrong?

Here is the error message when i try to run my aplication:

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

Here is my code:

public class WeeklyFlashActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        JSONObject json = JSONfunctions.getJSONfromURL("http://www.greenfields.co.id:502/Service1.svc/json/weeklyflash");

        try{

            JSONArray  weeklyflash = json.getJSONArray("GetReportResult");

            for(int i=0;i<weeklyflash.length();i++){                        
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = weeklyflash.getJSONObject(i);

                //map.put("type",  String.valueOf(i));
                map.put("type", e.getString("type"));
                map.put("total", e.getString("total"));

                mylist.add(map);            
            }       
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                        new String[] { "type", "total" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(WeeklyFlashActivity.this, "Type " + o.get("type") + " was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });
    }
}

here is my JSON variable:

{"GetReportResult":[{"total":"249319","type":"ESL500ML"},{"total":"19802","type":"CHEESE1K"},{"total":"3179380","type":"ESL"},{"total":"201243","type":"WHP"},{"total":"736744.136","type":"UHT"}]}

here is my JSONfunction:

public class JSONfunctions {
    public static JSONObject getJSONfromURL(String url){

        //initialize
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

        //convert response to string
        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();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

        //try parse the string to a JSON object
        try{
                jArray = new JSONObject(result);
        }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }

}

UPDATE: I've check my result and the result is a html code and says Method not allowed. maybe the problem comes from my wcf service. do you have any solution for this?

here is my wcf service:

[WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "/json/weeklyflash")]
blankon91
  • 521
  • 3
  • 15
  • 39
  • are you sure you are getting json from server ?..... – Dheeresh Singh Jun 25 '12 at 09:46
  • yeah, I've test my web service remotely, and it works here is the JSON `{"GetReportResult":[{"total":"249319","type":"ESL500ML"},{"total":"19802","type":"CHEESE1K"},{"total":"3179380","type":"ESL"},{"total":"201243","type":"WHP"},{"total":"736744.136","type":"UHT"}]}` – blankon91 Jun 25 '12 at 09:46
  • can you provide getJSONfromURL function code... – Dheeresh Singh Jun 25 '12 at 09:49
  • yes, I've update my thread to provide my JSONFunction code – blankon91 Jun 25 '12 at 09:53
  • have a look here: http://stackoverflow.com/questions/11186683/parse-json-in-android – rosco Jun 25 '12 at 09:57
  • it's looks fine ....can you put Log.e("check Data", "result is ---> "+result); before try{ jArray this line and check this once – Dheeresh Singh Jun 25 '12 at 09:57
  • @DheereshSingh ok, the result is a html code and says `Method not allowed.` maybe the problem comes from my wcf service. do you have any solution for this? sorry yesterday my internet connection having problem so I can't check your comment..thank you – blankon91 Jun 26 '12 at 01:29
  • @blankon91 I have the same problem, everything was working fine, but suddenly appeared Value  and even deleting the last changes i cant find the solution. – Ricardo Aug 28 '13 at 23:03

4 Answers4

6

This error has been encounter by many. It could be resolved by changing the charSet. Try using UTF-8 instead of iso-8859-1.

Change the following line:

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

to

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
Arun George
  • 18,352
  • 4
  • 28
  • 28
  • thank you @Arun, but it's still get error, but the error message change into `06-26 08:22:28.695: E/AndroidRuntime(368): at report.weeklyflash.WeeklyFlashActivity.onCreate(WeeklyFlashActivity.java:33) ` – blankon91 Jun 26 '12 at 01:24
  • UPDATE: I've check my result and the result is a html code and says `Method not allowed.` maybe the problem comes from my wcf service. do you have any solution for this? – blankon91 Jun 26 '12 at 01:30
2

finally I solved my own problem, the problem is on my http connection method, on my recent post, it used HttpPost and my wcf service method is GET, that's why I get error from wcf service that says Method not allowed

so I find the solution by change my http method on http connection with HttpGet like this:
HttpGet httpget = new HttpGet(url);

and it works fine for me. Thank you for everyone who comment an answer my question :)

blankon91
  • 521
  • 3
  • 15
  • 39
1

as looks you are using HttpPost method to getting the data from serer

        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);

but as per error Method not allowed. and

[WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "/json/weeklyflash")]

1- looks you should use HttpGet instead of HttpPost.

2- use response.getStatusLine().getStatusCode() == HttpStatus.SC_OK or 200 (for OK )and other to handle the response like

HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
     inst statusCode= statusLine.getStatusCode();
    if( statusCode== HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString();
        //..more logic
    }else if(statusCode == HttpStatus.SC_BAD_REQUEST){
             //error bad request shoe message BAD_REQUEST

       }else if(statusCode == HttpStatus.SC_BAD_GATEWAY){
             //error bad request shoe message BAD_GATEWAY

       }     

and more but all are not must only HttpStatus.SC_OK is mast important one ...

Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
-2

Questioion: value  of type java lang string cannot be converted to jsonobject

Answer : Do this work Properly BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); to

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);