1

I am a beginner at java programming, I am trying to load the php result into a spinner and I have been having this problem of JSONObject cannot be converted to JSONArray. I have search on the website to try and convert this but i cannot seem to fix it.

php result:

{"ref_product_types":[{"product_type_code":"1","product_type_description":"Mobile Phone"},{"product_type_code":"2","product_type_description":"Toys"}]}

i have added this in the manifest

<uses-permission android:name="android.permission.INTERNET"/>

here is the java code:

package com.example.spinnert1;

public class Main extends Activity {

InputStream is=null;
String result=null;
String line=null;

String[] product_type_code, product_type_description;  

Spinner spinner1,spinner2;



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

spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
final List<String> list1 = new ArrayList<String>();
final List<String> list2 = new ArrayList<String>();

Button b=(Button) findViewById(R.id.button1);

b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v)
{
                // TODO Auto-generated method stub

try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/epos_connect/get_all_product_type.php");
HttpResponse response = httpclient.execute(httppost);
Log.e("Fail 1", "3");

HttpEntity entity = response.getEntity();
Log.e("Fail 1", "4");

is = entity.getContent();
Log.e("Pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",Toast.LENGTH_LONG).show();
finish();
}    


try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}    


try
{
JSONArray JA=new JSONArray(result);


JSONObject json= null;
product_type_code = new String[JA.length()];       
product_type_description = new String[JA.length()];

for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
product_type_code[i] = json.getString("product_type_code");
product_type_description[i]=json.getString("product_type_description");
}
Toast.makeText(getApplicationContext(), "sss",Toast.LENGTH_LONG).show();

for(int i=0;i<product_type_code.length;i++)
{
list1.add(product_type_code[i]);
list2.add(product_type_description[i]);
}

spinner_fn();

}
catch(Exception e)
{

Log.e("Fail 3", e.toString());
//login.this.finish();

}
}
});

}
private void spinner_fn() {
    // TODO Auto-generated method stub

    ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
                                    android.R.layout.simple_spinner_item, product_type_code);
    dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(dataAdapter1);


    ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getApplicationContext(),
                                    android.R.layout.simple_spinner_item, product_type_description);
    dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner2.setAdapter(dataAdapter2);


    spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
    {
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
    {
    // TODO Auto-generated method stub

    spinner2.setSelection(position);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0)
    {
    // TODO Auto-generated method stub
    }

    });


    spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
    // TODO Auto-generated method stub

    spinner1.setSelection(position);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
    }
    });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    }

layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/country_arrays"
    android:prompt="@string/country_prompt" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/btnSubmit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit" />

</LinearLayout>

thanks

1

2 Answers 2

1

It looks like the data that is being returned is indeed a JSON object, rather than a JSON array; the JSON array is nested within the outer objects, in the "ref_product_types" key.

You'll want to use something like:

JSONObject jsonObj = new JSONObject(result);
JSONArray ja = jsonObj.getJSONArray("ref_product_types")
Sign up to request clarification or add additional context in comments.

1 Comment

Fix! Thank you for a quick answer
1
{
   "ref_product_types": [
                          {"product_type_code":"1",
                           "product_type_description":"Mobile Phone"
                          },
                          {"product_type_code":"2",
                           "product_type_description":"Toys"
                          }
                        ]
}

So i did a little formatting in order to you see it clearly.

So at first you should know that multiset parenthesis { indicates JSONObject and bracket [ indicates JSONArray. So your String presents JSONObject and it stores JSONArray. So you need first create new JSONObject and then parse JSONArray.

JSONObject o = new JSONObject(sourceString);
JSONArray arr = o.getJSONArray("ref_product_types");

1 Comment

Wow very nice, thanks for the explanation, thanks to you I understand how to fix it now

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.