Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7617379
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T03:08:14+00:00 2026-05-31T03:08:14+00:00

there. i’m a student who start learning building an android app… i’m having difficulties

  • 0

there. i’m a student who start learning building an android app…

i’m having difficulties on my code here….

i’ve read many page how to solve the problem and i haven’t found it…or maybe i’m not understand. hahah

the logcat always like this :

03-10 11:12:43.057: D/dalvikvm(636): GC_EXTERNAL_ALLOC freed 1001 objects / 69352 bytes in 99ms
03-10 11:12:46.458: E/JSON Parser(636): Error parsing data org.json.JSONException: Names must be strings, but [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] is of type org.json.JSONArray at character 200 of {[{"user_mobile":"affan","pass_mobile":"affanganteng"},{"user_mobile":"affandroid","pass_mobile":"affandroid1"},{"user_mobile":"tes","pass_mobile":"tes"},{"user_mobile":"tes2","pass_mobile":"tesdua"}]}
03-10 11:35:00.868: D/dalvikvm(644): GC_EXTERNAL_ALLOC freed 1014 objects / 69872 bytes in 71ms
03-10 11:35:03.629: E/JSON Parser(644): Error parsing data org.json.JSONException: Value [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] of type org.json.JSONArray cannot be converted to JSONObject
03-10 11:40:58.798: D/dalvikvm(671): GC_EXTERNAL_ALLOC freed 744 objects / 59488 bytes in 80ms
03-10 11:41:03.128: E/JSON Parser(671): Error parsing data org.json.JSONException: Value [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] of type org.json.JSONArray cannot be converted to JSONObject

actually i wanna get data from my sql and then parse it to listview using JSON.
i hope you can help me!

here’s my main activity :

package last.project.CuliGUI;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

    // url to make request
    private static String url = "http://10.0.2.2/culigui/getdatausermobile_2.php";

    // JSON Node names
    //private static final String TAG_LISTUSERMOBILE = "listusermobile";
    private static final String TAG_USER_MOBILE = "user_mobile";
    private static final String TAG_PASS_MOBILE = "pass_mobile";

    // contacts JSONArray
    JSONArray listusermobile = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_view_all);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            //listusermobile = json.getJSONArray(TAG_LISTUSERMOBILE);
            listusermobile = json.getJSONArray(null);

            // looping through All Contacts
            for(int i = 0; i < listusermobile.length(); i++){
                JSONObject c = listusermobile.getJSONObject(i);

                // Storing each json item in variable
                String username = c.getString(TAG_USER_MOBILE);
                String password = c.getString(TAG_PASS_MOBILE);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_USER_MOBILE, username);
                map.put(TAG_PASS_MOBILE, password);
                // adding HashList to ArrayList
                userList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, userList,
                R.layout.menu_view_all,
                new String[] { TAG_USER_MOBILE, TAG_PASS_MOBILE}, new int[] {
                        R.id.name, R.id.pass });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView)  view.findViewById(R.id.name)).getText().toString();
                String pass = ((TextView) view.findViewById(R.id.pass)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(TAG_USER_MOBILE, name);
                in.putExtra(TAG_PASS_MOBILE, pass);
                startActivity(in);

            }
        });



    }

}

and here my JSONParser Class :

package last.project.CuliGUI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            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, "iso-8859-1"), 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 Error", "Error converting result " + e.toString());
        }

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

        // return JSON String
        return jObj;

    }
}

and here’s the php :

<?php

    $link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
    mysql_select_db('culigui', $link) or die('Cannot select the DB');



    $result = sql2json("SELECT * FROM data_mobile");

    echo $result;

    //Function will take an SQL query as an argument and format the resulting data as a 
//    json(JavaScript Object Notation) string and return it.
function sql2json($query) {
    $data_sql = mysql_query($query) or die("'';//" . mysql_error());// If an error has occurred, 
            //    make the error a js comment so that a javascript error will NOT be invoked
    $json_str = ""; //Init the JSON string.

    if($total = mysql_num_rows($data_sql)) { //See if there is anything in the query
        $json_str .= "[\n";

        $row_count = 0;    
        while($data = mysql_fetch_assoc($data_sql)) {
            if(count($data) > 1) $json_str .= "{\n";

            $count = 0;
            foreach($data as $key => $value) {
                //If it is an associative array we want it in the format of "key":"value"
                if(count($data) > 1) $json_str .= "\"$key\":\"$value\"";
                else $json_str .= "\"$value\"";

                //Make sure that the last item don't have a ',' (comma)
                $count++;
                if($count < count($data)) $json_str .= ",\n";
            }
            $row_count++;
            if(count($data) > 1) $json_str .= "}\n";

            //Make sure that the last item don't have a ',' (comma)
            if($row_count < $total) $json_str .= ",\n";
        }

        $json_str .= "]\n";
    }

    //Replace the '\n's - make it faster - but at the price of bad redability.
    $json_str = str_replace("\n","",$json_str); //Comment this out when you are debugging the script

    //Finally, output the data
    return $json_str;
}


?>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T03:08:15+00:00Added an answer on May 31, 2026 at 3:08 am

    First of All, the following is NOT a valid JSON Object :

    {
        [
            {
                "user_mobile": "affan",
                "pass_mobile": "affanganteng"
            },
            {
                "user_mobile": "affandroid",
                "pass_mobile": "affandroid1"
            },
            {
                "user_mobile": "tes",
                "pass_mobile": "tes"
            },
            {
                "user_mobile": "tes2",
                "pass_mobile": "tesdua"
            }
        ]
    }
    

    In your JAVA code, you are iterating over JSON Object, and getting Sub JSON Object..

    JSONObject c = listusermobile.getJSONObject(i);
    

    But inside a JSON Object ,you are holding a JSON Array ( [] ), not a JSON Object ( {} ) ..But you are trying TypeCast JSON Array into JSON Object..that is what causing the Error…

    Note : You can always verify “a VALID JSONObject” and a “VALID JSONArray” at JSONLint.com

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
There is something I miss with the notion of Synchronizing code in Android. Scenario
There are numerous libraries providing Linq capabilities to C# code interacting with a MySql
There is a text file with 1,000,000 lines of code floating around and Ctrl+F
There are lots of posts on here about moving a folder out of one
There was some code like this: // Convenience to make things more legible in
There's a combobox event in my code: self.combobox1.Bind(wx.EVT_COMBOBOX, self.onActionCombobox1) It executes the function def
There is a conversion process that is needed when migrating Visual Studio 2005 web
There are two weird operators in C#: the true operator the false operator If
There are two popular closure styles in javascript. The first I call anonymous constructor

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.