0

im making an app for a website. It has an JSON API. The URL im trying to fetch the result from is: http://api.bayfiles.net/v1/account/login/<user>/<password>

I get the error: java.lang.string cannot be converted to jsonarray when logging the error using logcat.

My main activity is:

public class MainActivity extends SherlockActivity {

    EditText un,pw;
    TextView error;
    Button ok;
    private ProgressDialog mDialog;

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

        un = (EditText)findViewById(R.id.user);
        pw = (EditText)findViewById(R.id.psw);
        ok = (Button)findViewById(R.id.button1);
        error = (TextView)findViewById(R.id.textView1);

        ok.setOnClickListener(new View.OnClickListener() {

             @Override
             public void onClick(View v) {
                 // TODO Auto-generated method stub
                 //error.setText("Clicked");
                 //Intent startNewActivityOpen = new Intent(LoginActivity.this, FilesActivity.class);
                 //startActivityForResult(startNewActivityOpen, 0);

                 JsonAsync asyncTask = new JsonAsync();
                // Using an anonymous interface to listen for objects when task
                // completes.
                asyncTask.setJsonListener(new JsonListener() {
                    public void onObjectReturn(JSONObject object) {
                        handleJsonObject(object);
                    }
                });
                // Show progress loader while accessing network, and start async task.
                //mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
                    //  getString(R.string.loading), true);
                asyncTask.execute("http://api.bayfiles.net/v1/account/login/spxc/mess2005");



             }
        });     
    }

    private void handleJsonObject(JSONObject object) {
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        try {

            JSONArray shows = object.getJSONArray("error");

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

                //map.put("video_id", String.valueOf(i));
                map.put("session", "" + e.getString("session"));
                mylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data: " + e.toString());
        }

        error.setText("session");

                /*
                //Intent myIntent = new Intent(ListMoviesController.this,
                    //  TestVideoController.class);
                myIntent.putExtra("video_title", o.get("video_title"));
                myIntent.putExtra("video_channel", o.get("video_channel"));
                myIntent.putExtra("video_location", o.get("video_location"));
                startActivity(myIntent); */
            }{

        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

}

And this is my adapter: JSONfunctions.java

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);

            try {
                // Add your data
                /*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("key", "stianxxs"));
                nameValuePairs.add(new BasicNameValuePair("secret", "mhfgpammv9f94ddayh8GSweji"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); */

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                //HttpResponse response = httpclient.execute(httppost);
                HttpEntity httpEntity = response.getEntity();
                is = httpEntity.getContent();

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }

        }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{

            jArray = new JSONObject(result);            
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }
}

Why im i getting this error? When using the right username and password in the url you would get: {"error":"","session":"RANDOM NUMBER"}

And as you can see i try to fetch this number. Any help is much appreciated!

1 Answer 1

1

You are getting this error because in line

JSONArray shows = object.getJSONArray("error");

you are trying to get value for key error and treat is as an array, whereas it's not - it's an empty string. Therefore you need to get it as a string:

String error = object.getString("error");

Similarly, if you need to get your "session", you can get it with

String session = object.getString("session");

P.S. Note that this is assuming that your JSONObject object actually contains the object represented by the string in your question.

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

5 Comments

Should i make it object then? If so how do i do that ?
@StianInstebo is your json string right? if so JSONObject job = new JSONOBject(result).
Thank you very much this helped! If i used: String session = object.getString("session");and set my textview to show session it worked! Hoever, it canges the result each time i hit the button, hoever when i use just the url in my browser it does not change on refresh. Why is it changing ? Thanks again!
@StianInstebo This is because your browser sends the session information back to the server with each subsequent request. You need to read the session cookie from the response header and then send it back with the next request. This is outside the scope of this question though.
@StianInstebo Read about session cookies and cookies in general.

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.