Ошибка jsonexception value at activity of type org json jsonarray cannot be converted to jsonobject

I have been trying to fix this error for 2 days now, searched and tried multiple coding types from stackoverflow.com. I have checked my JSON http://jsonformatter.curiousconcept.com/#jsonformatter. But I am still unable to find out why my code is doing this. I have 3 files. MainACtivity.java that should get the information from my test.json files on my server and then process it to the Events.java. Events.java just displays the information, but the app doesn’t make it that far.

UPDATED CODE IN CASE ANYONE ELSE NEEDS THE FIX FOR THIS.

My Error:

 01-14 22:18:08.165: E/JSON Response:(419): > { "event":[ 
    01-14 22:18:08.165: E/JSON Response:(419):      {
    01-14 22:18:08.165: E/JSON Response:(419):       "event_name":"Test Event",
    01-14 22:18:08.165: E/JSON Response:(419):       "event_time":"7:00pm",
    01-14 22:18:08.165: E/JSON Response:(419):       "event_price":"$15.00"
    01-14 22:18:08.165: E/JSON Response:(419):      }
    01-14 22:18:08.165: E/JSON Response:(419):   ] 
    01-14 22:18:08.165: E/JSON Response:(419): }
    01-14 22:18:08.175: E/Json Error(419): Error: org.json.JSONException: Value         [{"event_price":"$15.00","event_time":"7:00pm","event_name":"Test Event"}] at event of type     org.json.JSONArray cannot be converted to JSONObject 

MainActivity.java

package com.example.dba;

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

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity 
{

String event_name, event_time, event_price;
static JSONObject object =null;

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

    new PrefetchData().execute();
}

/**
 * Async Task to make http call
 */
private class PrefetchData extends AsyncTask<Void, Void, Void> 
{

    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();      
    }

    @Override
    protected Void doInBackground(Void... arg0) 
    {

        JsonParser jsonParser = new JsonParser();
        String json = jsonParser.getJSONFromUrl("http://www.website/test.json");

        Log.e("JSON Response: ", "> " + json);

        if (json != null) 
        {
           try 
            {
                JSONObject parent = new JSONObject(json);
                JSONArray eventDetails = parent.getJSONArray("event");

                for(int i=0; i < eventDetails.length(); i++)
                {
                    object = eventDetails.getJSONObject(i);
                    event_name = object.getString("event_name");
                    event_time = object.getString("event_time");
                    event_price = object.getString("event_price");

                    Log.e("JSON", "> " + event_name + event_time + event_price );
                }
            }  catch (JSONException e) 
                {
                Log.e("Json Error", "Error: " + e.toString());
                    e.printStackTrace();
                }

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) 
    {           
        super.onPostExecute(result);

        Intent i = new Intent(MainActivity.this, Events.class);
        i.putExtra("event_name", event_name);
        i.putExtra("event_time", event_time);
        i.putExtra("event_price", event_price);
        startActivity(i);

        // close this activity
        finish();
    }

}

}


}

I have been trying to fix this error for 2 days now, searched and tried multiple coding types from stackoverflow.com. I have checked my JSON http://jsonformatter.curiousconcept.com/#jsonformatter. But I am still unable to find out why my code is doing this. I have 3 files. MainACtivity.java that should get the information from my test.json files on my server and then process it to the Events.java. Events.java just displays the information, but the app doesn’t make it that far.

UPDATED CODE IN CASE ANYONE ELSE NEEDS THE FIX FOR THIS.

My Error:

 01-14 22:18:08.165: E/JSON Response:(419): > { "event":[ 
    01-14 22:18:08.165: E/JSON Response:(419):      {
    01-14 22:18:08.165: E/JSON Response:(419):       "event_name":"Test Event",
    01-14 22:18:08.165: E/JSON Response:(419):       "event_time":"7:00pm",
    01-14 22:18:08.165: E/JSON Response:(419):       "event_price":"$15.00"
    01-14 22:18:08.165: E/JSON Response:(419):      }
    01-14 22:18:08.165: E/JSON Response:(419):   ] 
    01-14 22:18:08.165: E/JSON Response:(419): }
    01-14 22:18:08.175: E/Json Error(419): Error: org.json.JSONException: Value         [{"event_price":"$15.00","event_time":"7:00pm","event_name":"Test Event"}] at event of type     org.json.JSONArray cannot be converted to JSONObject 

MainActivity.java

package com.example.dba;

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

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity 
{

String event_name, event_time, event_price;
static JSONObject object =null;

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

    new PrefetchData().execute();
}

/**
 * Async Task to make http call
 */
private class PrefetchData extends AsyncTask<Void, Void, Void> 
{

    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();      
    }

    @Override
    protected Void doInBackground(Void... arg0) 
    {

        JsonParser jsonParser = new JsonParser();
        String json = jsonParser.getJSONFromUrl("http://www.website/test.json");

        Log.e("JSON Response: ", "> " + json);

        if (json != null) 
        {
           try 
            {
                JSONObject parent = new JSONObject(json);
                JSONArray eventDetails = parent.getJSONArray("event");

                for(int i=0; i < eventDetails.length(); i++)
                {
                    object = eventDetails.getJSONObject(i);
                    event_name = object.getString("event_name");
                    event_time = object.getString("event_time");
                    event_price = object.getString("event_price");

                    Log.e("JSON", "> " + event_name + event_time + event_price );
                }
            }  catch (JSONException e) 
                {
                Log.e("Json Error", "Error: " + e.toString());
                    e.printStackTrace();
                }

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) 
    {           
        super.onPostExecute(result);

        Intent i = new Intent(MainActivity.this, Events.class);
        i.putExtra("event_name", event_name);
        i.putExtra("event_time", event_time);
        i.putExtra("event_price", event_price);
        startActivity(i);

        // close this activity
        finish();
    }

}

}


}

I keep on getting this error. I get the error JSONArray cannot be converted to JSONObject. I have parsed the JSON file which contains array of objects, but still getting this error. Here is the code:

JAVA Code:

public class DetailActivity extends AppCompatActivity {

ImageView imageView;
TextView options, bio, noBio;
private final String JSON_URL = "https://run.mocky.io/v3/987b97bd-6895-40d1-9d37-ce404162c491";
private JsonObjectRequest jsonObjectRequest;
private RequestQueue requestQueue;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    getSupportActionBar().setTitle("");
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    imageView = (ImageView) findViewById(R.id.iv_image);
    options = (TextView) findViewById(R.id.tv_options);
    bio = (TextView) findViewById(R.id.tv_bio);
    noBio = (TextView) findViewById(R.id.tv_no_bio);

    getDetails();
}

private void getDetails() {
    jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSON_URL,null ,new Response.Listener<JSONObject>() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = new JSONArray(response.toString());
                for (int i = 0; i<jsonArray.length(); i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String type = jsonObject.getString("type");
                    boolean isVisible = jsonObject.getBoolean("isVisible");

                    if (!isVisible){
                        imageView.setVisibility(View.GONE);
                        options.setText("API response is false. So data will not be shown.");
                        bio.setText("API response is false. So data will not be shown.");
                    }
                    else{
                        imageView.setVisibility(View.VISIBLE);
                        options.setVisibility(View.VISIBLE);
                        bio.setVisibility(View.VISIBLE);

                        Intent intent = getIntent();
                        Glide.with(getApplicationContext()).load((Bitmap) intent.getParcelableExtra("image")).into(imageView);
                        options.setText("Choosen Option : " + getIntent().getStringExtra("options"));
                        String str_bio = getIntent().getStringExtra("comments");
                        if (str_bio == null){
                            bio.setVisibility(View.GONE);
                            noBio.setVisibility(View.VISIBLE);
                        }
                        else{
                            bio.setText("Bio : " + str_bio);
                            noBio.setVisibility(View.GONE);
                        }
                    }
                }
            } catch (JSONException e) {
                Toast.makeText(DetailActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("Exception", e.getMessage());
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(DetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            Log.d("Error", error.getMessage());
        }
    });
    requestQueue = Volley.newRequestQueue(DetailActivity.this);
    requestQueue.add(jsonObjectRequest);
}

}

XML File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F0E6FD"
android:orientation="vertical"
tools:context=".DetailActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="15dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp">
    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:scaleType="fitXY"/>
    <TextView
        android:id="@+id/tv_options"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choosen option : "
        android:textSize="17dp"
        android:fontFamily="@font/notoserif_bold"
        android:layout_marginTop="15dp"
        android:textColor="@color/black"/>
    <TextView
        android:id="@+id/tv_bio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bio :"
        android:textSize="17dp"
        android:fontFamily="@font/notoserif_bold"
        android:layout_marginTop="15dp"
        android:textColor="@color/black"/>
    <TextView
        android:id="@+id/tv_no_bio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No Bio provided"
        android:gravity="center"
        android:textSize="15dp"
        android:fontFamily="@font/notoserif_regular"
        android:layout_marginTop="15dp"
        android:textColor="@color/black"/>
</LinearLayout>

Here is the JSON File:

[
   {
      "type":"PHOTO",
      "isVisible":true
   },
   {
      "type":"SINGLE_CHOICE",
      "isVisible":true
   },
   {
      "type":"COMMENT",
      "isVisible":true
   }
]

I keep on getting this error. I get the error JSONArray cannot be converted to JSONObject. I have parsed the JSON file which contains array of objects, but still getting this error. Here is the code:

JAVA Code:

public class DetailActivity extends AppCompatActivity {

ImageView imageView;
TextView options, bio, noBio;
private final String JSON_URL = "https://run.mocky.io/v3/987b97bd-6895-40d1-9d37-ce404162c491";
private JsonObjectRequest jsonObjectRequest;
private RequestQueue requestQueue;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    getSupportActionBar().setTitle("");
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    imageView = (ImageView) findViewById(R.id.iv_image);
    options = (TextView) findViewById(R.id.tv_options);
    bio = (TextView) findViewById(R.id.tv_bio);
    noBio = (TextView) findViewById(R.id.tv_no_bio);

    getDetails();
}

private void getDetails() {
    jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSON_URL,null ,new Response.Listener<JSONObject>() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = new JSONArray(response.toString());
                for (int i = 0; i<jsonArray.length(); i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String type = jsonObject.getString("type");
                    boolean isVisible = jsonObject.getBoolean("isVisible");

                    if (!isVisible){
                        imageView.setVisibility(View.GONE);
                        options.setText("API response is false. So data will not be shown.");
                        bio.setText("API response is false. So data will not be shown.");
                    }
                    else{
                        imageView.setVisibility(View.VISIBLE);
                        options.setVisibility(View.VISIBLE);
                        bio.setVisibility(View.VISIBLE);

                        Intent intent = getIntent();
                        Glide.with(getApplicationContext()).load((Bitmap) intent.getParcelableExtra("image")).into(imageView);
                        options.setText("Choosen Option : " + getIntent().getStringExtra("options"));
                        String str_bio = getIntent().getStringExtra("comments");
                        if (str_bio == null){
                            bio.setVisibility(View.GONE);
                            noBio.setVisibility(View.VISIBLE);
                        }
                        else{
                            bio.setText("Bio : " + str_bio);
                            noBio.setVisibility(View.GONE);
                        }
                    }
                }
            } catch (JSONException e) {
                Toast.makeText(DetailActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("Exception", e.getMessage());
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(DetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            Log.d("Error", error.getMessage());
        }
    });
    requestQueue = Volley.newRequestQueue(DetailActivity.this);
    requestQueue.add(jsonObjectRequest);
}

}

XML File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F0E6FD"
android:orientation="vertical"
tools:context=".DetailActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="15dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp">
    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:scaleType="fitXY"/>
    <TextView
        android:id="@+id/tv_options"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choosen option : "
        android:textSize="17dp"
        android:fontFamily="@font/notoserif_bold"
        android:layout_marginTop="15dp"
        android:textColor="@color/black"/>
    <TextView
        android:id="@+id/tv_bio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bio :"
        android:textSize="17dp"
        android:fontFamily="@font/notoserif_bold"
        android:layout_marginTop="15dp"
        android:textColor="@color/black"/>
    <TextView
        android:id="@+id/tv_no_bio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No Bio provided"
        android:gravity="center"
        android:textSize="15dp"
        android:fontFamily="@font/notoserif_regular"
        android:layout_marginTop="15dp"
        android:textColor="@color/black"/>
</LinearLayout>

Here is the JSON File:

[
   {
      "type":"PHOTO",
      "isVisible":true
   },
   {
      "type":"SINGLE_CHOICE",
      "isVisible":true
   },
   {
      "type":"COMMENT",
      "isVisible":true
   }
]

Я знаю, что есть несколько похожих тем, но ни одна из них не помогает. Я пытаюсь разобрать цикл PHP foreach на Json, а затем на Android. Есть список URL-адресов, по которым можно загрузить файлы apk, и это то, что я просматриваю.
Это ошибка, с которой я сталкиваюсь каждый раз, когда запускаю программу.

Error :- org.json.JSONException: Value ["xxxx.apk"] of type org.json.JSONArray cannot be converted to JSONObject

Код PHP:

$fileList = glob('xxxx/xxx/appstore_php/*');
   foreach($fileList as $filename)
   {
      if ( is_file ( $filename ) )
      {
         $bname = basename ( $filename);
         $b = array($bname);    
         echo json_encode($b);
      }
   }

Вывод: — [«xxxx.apk»] [«xxy.apk»]
Код Android:

  private void getAppData(){
        //Creating a string request
        StringRequest stringRequest = new StringRequest(URLAddress.SHOW_ALL_APK,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result = j.getJSONArray(URLAddress.JSON_ARRAY);

                        getApps(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });

        //Creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

    private void getApps(JSONArray j){
        //Traversing through all the items in the json array
        for(int i=0;i<j.length();i++){
            try {
                //Getting json object
                JSONObject json = j.getJSONObject(i);
                appList.add( json.toString() );

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }       

Я создаю приложение для генерации otp, поэтому я использовал php и свой sql. WAMP в качестве локального хост-провайдера. Мой файл cat cat содержит

11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at com.techrefic.app1611.MainActivity$2.onResponse(MainActivity.java:178)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at com.techrefic.app1611.MainActivity$2.onResponse(MainActivity.java:172)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:67)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at android.os.Looper.loop(Looper.java:148)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at java.lang.reflect.Method.invoke(Native Method)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-18 13:27:23.766 30362-30362/com.techrefic.app1611 W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-18 13:27:23.776 1620-1943/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@7b87dab attribute=null, token = android.os.BinderProxy@ba60539
11-18 13:27:26.741 1317-1603/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 5574322 , only wrote 5436064
11-18 13:28:00.085 1212-1272/? D/hwcomposer: hw_composer sent 84 syncs in 60s
11-18 13:29:00.061 1212-1272/? D/hwcomposer: hw_composer sent 4 syncs in 60s

Файл xml activity_main.xml содержит:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.techrefic.app1611.MainActivity"
android:fitsSystemWindows="true">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:orientation="vertical">

<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Email"/>
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextPassword"
android:inputType="textPassword"
android:hint="Password"/>

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextPhone"
android:inputType="textEmailAddress"
android:hint="Mobile Number"/>

</android.support.design.widget.TextInputLayout>

<android.support.v7.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonRegister"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Register"
android:textSize="24sp"/>

<TextView android:id="@+id/linkLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:gravity="center"
android:text="Already have an account? Login here"
android:textSize="16sp"/>

</LinearLayout>

</ScrollView>

dialog_confirm.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="48dp"
android:paddingRight="24dp"
android:paddingBottom="24dp"
android:paddingLeft="24dp"
android:layout_marginTop="80dp"
android:layout_marginBottom="80dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="@color/colorAccent">

<TextView
android:layout_width="wrap_content"
android:text="Enter OTP"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/editTextOtp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"/>

<android.support.v7.widget.AppCompatButton
android:id="@+id/buttonConfirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginTop="24dp"
android:background="@color/colorPrimary"
android:padding="12dp"
android:text="Confirm Otp"
android:textColor="#fff"
android:textSize="24sp"/>

</LinearLayout>

и мои java файлы: 1. MainActivity.java

   public class MainActivity extends AppCompatActivity implements View.OnClickListener {

// Creating views
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextPhone;
private EditText editTextConfirmOtp;

private AppCompatButton buttonRegister;
private AppCompatButton buttonConfirm;

//Volley RequestQueue
private RequestQueue requestQueue;

//String variables to hold email, password and phone number
private String username;
private String password;
private String phone;

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

//Initializing Views
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextPhone = (EditText) findViewById(R.id.editTextPhone);

buttonRegister = (AppCompatButton) findViewById(R.id.buttonRegister);

//Initializing the RequestQueue
requestQueue = Volley.newRequestQueue(this);

//Adding a listener to button
buttonRegister.setOnClickListener((View.OnClickListener) this);
}

// This method would confirm the OTP

private void confirmOtp() throws JSONException {

//Creating a Layout Inflater object for the dialog box
LayoutInflater li = LayoutInflater.from(this);

//Creating a view to get the dialog box

View confirmDialog = li.inflate(R.layout.dialog_confirm, null);

// Initialing confirm button for dialog box and edittext of dialog box

buttonConfirm = (AppCompatButton) confirmDialog.findViewById(R.id.buttonConfirm);
editTextConfirmOtp = (EditText) confirmDialog.findViewById(R.id.editTextOtp);

//Creating an alert dialog builder
AlertDialog.Builder alert = new AlertDialog.Builder(this);

//Adding our dialog box to the view of alert dialog
alert.setView(confirmDialog);

//Creating an alert dialog
final AlertDialog alertDialog = alert.create();

//Displaying the alert dialog
alertDialog.show();

// Onclick of the confirm button from alert dialog
buttonConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Hiding the alert dialog
alertDialog.dismiss();

//Displaying a progressbar
final ProgressDialog loading = ProgressDialog.show(MainActivity.this, "Authenticating ", "Please wait while we check the entered code", false, false);

//Getting the user entered otp from edittext
final String otp = editTextConfirmOtp.getText().toString().trim();

//Creating an string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.CONFIRM_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.equalsIgnoreCase("success")) {
loading.dismiss();

//Start a new activity
startActivity(new Intent(MainActivity.this, Success.class));
} else {
//Displaying a toast if the otp entered is wrong
Toast.makeText(MainActivity.this, "Wrong OTP Please try Again", Toast.LENGTH_LONG).show();
try {
//Asking user to enter otp again
confirmOtp();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
alertDialog.dismiss();
}
}){

@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//Adding the parameters otp and email

params.put(Config.KEY_OTP, otp);
params.put(Config.KEY_USERNAME, username);
return params;
}
};
//Adding the request to the queue
requestQueue.add(stringRequest);
}
});
}

//this method will get register the user
private void register() {
//Displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Registering", "Please wait...", false, false);

//Getting user data
username = editTextEmail.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
phone = editTextPhone.getText().toString().trim();

//Again creating the request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
loading.dismiss();
try {
//Creating the json object from the response
JSONObject jsonResponse = new JSONObject(response);

//IF it is success
if (jsonResponse.getString(Config.TAG_RESPONSE).equalsIgnoreCase("success")) {
//Asking user to confirm otp
confirmOtp();
} else {
//If not successful user may already have registerd
Toast.makeText(MainActivity.this, "Username or Phone Number already registered", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();

}
}) {
@Override
protected Map<String, String> getParams()throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Adding the params to the request
params.put(Config.KEY_USERNAME, username);
params.put(Config.KEY_PASSWORD, password);
params.put(Config.KEY_PHONE, phone);
return params;
}
};

//Adding request to the queue
requestQueue.add(stringRequest);
}

@Override
public void onClick(View v){
//calling refgister method on register button click
register();
}
}

И Config.java

public class Config {

public static final String REGISTER_URL = "http://192.168.0.4/famous/register.php";
public static final String CONFIRM_URL = "http://192.168.0.4/famous/confirm.php";

//Keys to send username, password, phone and otp
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PHONE = "phone";
public static final String KEY_OTP = "otp";

//JSON Tag from response from server
public static final String TAG_RESPONSE= "ErrorMessage";
}

мой файл gradle содержит зависимости:

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

compile 'com.android.support:design:26.1.0'
compile 'com.mcxiaoke.volley:library:1.0.19'
}

и php файлы я использовал register.php

<?php
// Constants for our API
// this is applicable only when you are using SMS API
define('SMSUSER', $_POST[username]);
define('PASSWORD', $_POST[password]);
define('PHONE', $_POST[phone]);
// define('SENDERID', 'EDCRTZ');

// This function will send the otp

$otp = int rand(100000, 999999);

// This is the sms text that will be sent via sms
$sms_content = "Welcome ".SMSUSER.", to DEMO Tp RTA app: Your verification code is".$otp ;

// This is the Actual API URL concatnated with required values
$api_url ="http://mymessageapi".$sms_content."&senderId=EDCRTZ&routeId=1&mobileNos=".PHONE."&smsContentType=english";

//Envoking the API url and getting the response
$response = file_get_contents($api_url);

//Returning the response
return $response;

//If a past request comes to this script
if ($_SERVER['REQUEST_METHOD']=='POST') {
// getting username password and phone number
$username = $_POST['username'];
$password = $_POST['password'];
$phone = $_POST['phone'];

//Generating a 6 digits OTP or verification code
$otp = rand(100000, 999999);

//Importing the db connection script

require_once('dbConnect.php');

//Creating an SQL Query
$sql = "INSERT INTO famous (username, password, phone, otp) values('$username','$password','$phone','$otp')";

//If the query executed on the db successfully
if (mysql_query($con,$sql)) {
// printing the failure message in json
echo '{"ErrorMessage":"Failure"}';
}
//Closing the databse connection
mysqli_close($con);
}
?>

confirm.php

<?php

//If a post request is detected
if ($_SERVER['REQUEST_METHOD']=='POST') {

//gETTING THE username and otp
$username = $_POST['username'];
$otp = $_POST['otp'];

// Importing the dbConnect script
require_once('dbConnect.php');

//Creating an SQL to fetch the otp from the table
$sql = "SELECT otp FROM test-table WHERE username = '$username'";

//Getting the result array from databse
$result = mysqli_fetch_array(mysqli_query($con,$sql));

//Getting the otp from the array
$realotp = $result['otp'];

//Getting the otp given is equal to otp fetched from database
if ($otp == $realotp) {
// Creating an sql query to update the column verified to 1 for the specified user

$sql = "UPDATE test-table SET verified= '1' WHERE username ='$username'";

//If the table is updated
if (mysqli_query($con,$sql)) {
//displaying failure
echo 'success';
}else{
//displaying failure
echo "failure";
}
}else{
//displaying failure if otp is not equal to the otp fetched from databse
echo 'failure';
}
//Closing the database
mysql_close($con);

}
?>

Файл dbConnect.php

<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', 'famous');

//connecting to database
$con = mysqli_connect(HOST, USER, PASS, DB) or die('Unable to Connect');
?>

я использовал мой wamp для сервера localhost для запуска локального приложения с моим приложением на одном и том же ip-адресе любому, кто может решить эту проблему

org.json.JSONException: Value [] at args of type org.json.JSONArray cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:100) at org.json.JSONObject.getJSONObject(JSONObject.java:613) at com.rastating.droidbeard.net.FetchShowSummariesTask.doInBackground(FetchShowSummariesTask.java:56) at com.rastating.droidbeard.net.FetchShowSummariesTask.doInBackground(FetchShowSummariesTask.java:38) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) 
{ "data": { "args": [], "error_msg": "error Connection error HTTPConnectionPool(host='services.tvrage.com', port=80): Max retries exceeded with url: /feeds/search.php?show=the+closer (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known) while loading URL http://services.tvrage.com/feeds/search.php", "kwargs": {} }, "message": "SickBeard encountered an internal error! Please report to the Devs", "result": "fatal" } 

Я пытаюсь сделать страницу регистрации из андроида активности connectiong данных в мою sqldatabase, я получаю эту ошибку “org.json.JSONException: Значение

Я знаю, что я видел все подобные вопросы на SO. Я устал, чтобы решить эту ошибку за последние 7 часов. я пробовал почти все, искал в Интернете и много, но не смог найти решение этой ошибки:

Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

**** **** JSONParser.java

public class JSONParser {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
StrictMode.setThreadPolicy(policy);
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
// check for request method
if(method.equals("POST")){
Log.d("my", "method equals POST is working");
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d("my", "HTTp client is working");
HttpPost httpPost = new HttpPost(url);
Log.d("my", "HTTp post is working");
httpPost.setEntity(new UrlEncodedFormEntity(params));
Log.d("my", "url encoded");
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.d("my", "HTTp response is working");
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("my", "HTTp entity is working");
is = httpEntity.getContent();
Log.d("my", "getcontent is working");
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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);
Log.d("my", "buffer reader crated");
StringBuffer sb = new StringBuffer();
Log.d("my", "string buffer object crated");
String line = null;
while ((line = reader.readLine())!= null) {
sb.append(line + "n");
Log.d("my", "line appended");
}
is.close();
Log.d("my", "inputstram closed");
json = sb.toString();
Log.d("my", "string buffer to string conversion");
} 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;
}

}

TAP_Cliente_nuevo.java

enter code here public class Tap_Cliente_Nuevo extends Activity {

JSONParser parseadorJson = new  JSONParser();
Button btn;
EditText RFC;
EditText Nombre;
EditText ApellidoP;
EditText ApellidoM;
EditText Telefono;
EditText Calle;
EditText Numero;
EditText Colonia;
EditText Municipio;
EditText Estado;
EditText CP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tap__cliente__nuevo);
RFC = (EditText)findViewById(R.id.txtRFCCliente);
Nombre = (EditText)findViewById(R.id.txtNombreCliente);
ApellidoP = (EditText)findViewById(R.id.txtApellidoPCliente);
ApellidoM = (EditText)findViewById(R.id.txtApellidoMCliente);
Telefono = (EditText)findViewById(R.id.txtTelefonoCliente);
Calle = (EditText)findViewById(R.id.txtCalleCliente);
Numero = (EditText)findViewById(R.id.txtNumeroCliente);
Colonia = (EditText)findViewById(R.id.txtColoniaCliente);
Municipio = (EditText)findViewById(R.id.txtMunicipioCliente);
Estado = (EditText)findViewById(R.id.txtEstadoCliente);
CP = (EditText)findViewById(R.id.txtCPCliente);
btn = (Button)findViewById(R.id.btnRegistrarCliente);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(RFC.getText().length()==0 ||
Nombre.getText().length()==0 ||
ApellidoP.getText().length()==0 ||
ApellidoM.getText().length()==0 ||
Telefono.getText().length()==0 ||
Calle.getText().length()==0 ||
Numero.getText().length()==0 ||
Colonia.getText().length()==0 ||
Municipio.getText().length()==0 ||
Estado.getText().length()==0 ||
CP.getText().length()==0){
Toast.makeText(getApplicationContext(), "Por favor llena los campos obligatorios", Toast.LENGTH_SHORT).show();
}else{
List<NameValuePair> parametros = new ArrayList<NameValuePair>();
parametros.add(new BasicNameValuePair("inRFC", RFC.getText().toString()));
parametros.add(new BasicNameValuePair("inNombre", Nombre.getText().toString()));
parametros.add(new BasicNameValuePair("inApPat", ApellidoP.getText().toString()));
parametros.add(new BasicNameValuePair("inApMat", ApellidoM.getText().toString()));
parametros.add(new BasicNameValuePair("inTel", Telefono.getText().toString()));
parametros.add(new BasicNameValuePair("inCalle", Calle.getText().toString()));
parametros.add(new BasicNameValuePair("inNum", Numero.getText().toString()));
parametros.add(new BasicNameValuePair("inCol", Colonia.getText().toString()));
parametros.add(new BasicNameValuePair("inMuni", Municipio.getText().toString()));
parametros.add(new BasicNameValuePair("inEsta", Estado.getText().toString()));
parametros.add(new BasicNameValuePair("inCP", CP.getText().toString()));
Log.e("Registro", obtenIpServidor());
parseadorJson.makeHttpRequest("http://192.168.1.72/tractofer/alta_clientes.php", "POST", parametros);
Toast.makeText(getApplicationContext(), "Datos Insertados correctamente", Toast.LENGTH_SHORT).show();
RFC.setText("");
Nombre.setText("");
ApellidoP.setText("");
ApellidoM.setText("");
Telefono.setText("");
Calle.setText("");
Numero.setText("");
Colonia.setText("");
Municipio.setText("");
Estado.setText("");
CP.setText("");
}
}
});
}
public String obtenIpServidor()
{
String ip=null;
SharedPreferences pref = getSharedPreferences("com.example.tractopartesycamiones_preferences",MODE_PRIVATE);
Log.e("Registro",  "tipo_conexion: " + pref.getString("tipo_conexion", "1"));
if (pref.getString("tipo_conexion", "1").equals( "1"))
ip="192.168.1.72";
else
ip = pref.getString("ip_servidor", "0.0.0.0");
return ip;
}

}

alta_cliente.php

<?php
//Constantes
$db_usuario = "root";
$db_pass    = "";
$db_host    = "localhost";
$db_schema  = "tractofer";
//Conexion con la base de datos
$enlace = mysql_connect($db_host, $db_usuario, $db_pass)
or die (' No se conecto al servidor');
mysql_select_db($db_schema,$enlace)
or die('Error al seleccionar la base de datos');
$respuesta = array();
$RFC = $_POST['inRFC'];
$Nombre = $_POST['inNombre'];
$ApPat = $_POST['inApPat'];
$ApMat = $_POST['inApMat'];
$Tel = $_POST['inTel'];
$Calle = $_POST['inCalle'];
$Num = $_POST['inNum'];
$Col = $_POST['inCol'];
$Muni = $_POST['inMuni'];
$Esta = $_POST['inEsta'];
$CP = $_POST['inCP'];
$db_query =
"INSERT INTO cliente VALUES('$RFC', '$Nombre', '$ApPat', '$ApMat', '$Tel', '$Calle', '$Num', '$Col', '$Muni', '$Esta', '$CP')";
//Ejecutamos el Query
$resultado = mysql_query($db_query,$enlace)
or die('Error en el query: ' .$db_query);
if($resultado)
{
$respuesta["success"]=1;
$respuesta["message"]="Usuario agregado";
echo json_encode($respuesta);
}
else
{ echo 'Error en el json'; }
//desconexion de la base de datos
@mysql_close($enlace);
?>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 
{"timestamp":1470379316,"type":"news","rows":[{"categorytitle":"Происшествия","dateline":"1470378720","media":[{"width":"200","filename":"https://www.***.ru/media/80/63/money_dengi_b10(1)__0.jpg","height":"133"}],"text":" В Армавире возбудили уголовное дело в отношении инспектора ДПС, которого заподозрили в получении взятки.   rn По версии следствия, 23 июня полицейский патрулировал поселок Заветный. Он остановил автомобиль с пьяным водителем и сказал, что готов не отправлять его на освидетельствование за 25 тыс. рублей, сообщает пресс-служба СУ СК РФ по Краснодарскому краю.   rn Водитель согласился, отдал требуемую сумму, но потом сообщил о случившемся в правоохранительные органы. Расследование уголовного дела продолжается.   rn По итогам служебной проверки принято решение об увольнении инспектора ДПС из МВД по отрицательным мотивам. Его руководителей привлекут к дисциплинарной ответственности, бывший полицейский понесет наказание в соответствии с действующим законодательством, сообщает пресс-служба ГУ МВД РФ по Краснодарскому краю.   ","link":"https://www.***.ru/news/401542/","username":"Anton","categoryid":"7","title":"В Армавире полицейского заподозрили в получении взятки в 25 тыс. рублей","anouns":"Инспектор ДПС предлагал за деньги не отправлять пьяного водителя на освидетельствование","newsid":"401542"},{"categorytitle":"Образование","dateline":"1470378360","media":[{"width":"200","filename":"https://www.***.ru/media/c0/1c/money_dengi_b8__0.jpg","height":"133"}],"text":" На подготовку 73 городских образовательных организаций столицы Адыгеи Адыгеи к новому учебному году было направлено свыше 19 млн рублей, часть из которых – депутатские средства. Об этом сообщили в пресс-службе администрации Майкопа.   rn "В зданиях школ и детских садов проводится косметический ремонт спортивных и актовых залов, столовых, учебных и медицинских кабинетов, рекреаций. Производится замена дверных и оконных блоков, ремонтируются крыши и ограждения, приобретается мебель и необходимое оборудование", – отметили в администрации города.   rn Кроме того, в рамках федерального проекта, направленного на создание условий для занятий спортом в сельских образовательных организациях, из федерального бюджета получена субсидия на ремонт спортзала в СОШ №18 поселка Гавердовского.    "Соответствующие мероприятия в рамках муниципальной программы "Доступная среда" будут выполнены в ДОУ №26, ДОУ №37, ДОУ№39, а также в МКОУ "Специальная (коррекционная) общеобразовательная школа VIII вида". Качество выполняемых работ – на контроле мэра города Александра Наролина", – уточнили в пресс-службе мэрии Майкопа.   ","link":"https://www.yuga.ru/news/401541/","username":"Дарья","categoryid":"120","title":"В Майкопе на косметический ремонт школ выделили 19 млн рублей","anouns":"В Майкопе на косметический ремонт 73 образовательных организаций выделили 19 млн рублей","newsid":"401541"},{"categorytitle":"Курорты и туризм","dateline":"1470378060","media":[{"width":"200","filename":"https://www.***.ru/media/2f/95/sea_beach_b25__0.jpg","height":"133"}],"text":" В министерстве по курортов, туризма и олимпийского наследия Краснодарского края сообщили, что загрузка пляжей черноморских курортов Кубани превысила 100%.   rn Основной наплыв отдыхающих в пик курортного сезона наблюдают в Сочи, Геленджике и Анапе. При этом пляжи Азовского моря заполнены менее чем на половину, сообщает "Интерфакс".   rn

У меня есть файл JSON с двумя JSON-массивами: один массив для маршрутов и один массив для достопримечательностей.

Маршрут должен состоять из нескольких достопримечательностей, к которым перемещается пользователь. К сожалению, я получаю сообщение об ошибке:

JSONException: значение типа java.lang.String не может быть преобразовано в JSONObject.

Вот мои переменные и код, который анализирует JSON-файл:

private InputStream is = null;
private String json = "";
private JSONObject jObj = null;
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();
// hier habe ich das JSON-File als String
json = sb.toString();
Log.i("JSON Parser", json);
} 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;
}

Log.i(«Парсер JSON», json); показывает мне, что в начале сгенерированной строки есть странный знак: Введите описание изображения здесь

но ошибка происходит здесь:

try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

04-22 14:01:05.043: E/JSON Parser(5868): ошибка при синтаксическом анализе данных org.json.JSONException: значение //СТРАННЫЙ ЗНАК ЗДЕСЬ//типа java.lang.String не может быть преобразовано в JSONObject

кто-нибудь знает, как избавиться от этих знаков, чтобы создать JSONObject?

Я знаю, что есть несколько похожих тем, но ни одна из них не помогает. Я пытаюсь разобрать цикл PHP foreach на Json, а затем на Android. Есть список URL-адресов, по которым можно загрузить файлы apk, и это то, что я просматриваю.
Это ошибка, с которой я сталкиваюсь каждый раз, когда запускаю программу.

Error :- org.json.JSONException: Value ["xxxx.apk"] of type org.json.JSONArray cannot be converted to JSONObject

Код PHP:

$fileList = glob('xxxx/xxx/appstore_php/*');
   foreach($fileList as $filename)
   {
      if ( is_file ( $filename ) )
      {
         $bname = basename ( $filename);
         $b = array($bname);    
         echo json_encode($b);
      }
   }

Вывод: — [«xxxx.apk»] [«xxy.apk»]
Код Android:

  private void getAppData(){
        //Creating a string request
        StringRequest stringRequest = new StringRequest(URLAddress.SHOW_ALL_APK,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result = j.getJSONArray(URLAddress.JSON_ARRAY);

                        getApps(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });

        //Creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

    private void getApps(JSONArray j){
        //Traversing through all the items in the json array
        for(int i=0;i<j.length();i++){
            try {
                //Getting json object
                JSONObject json = j.getJSONObject(i);
                appList.add( json.toString() );

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }       

Issue

I want to use Volley send JSON payload to REST API. But I get an error

«com.android.volley.ParseError: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject»

Payload from Magento
https://devdocs.magento.com/guides/v2.4/rest/tutorials/inventory/create-cart-add-products.html

JSON Payload

{
  "cartItem": {
    "sku": "10-1001",
    "qty": 5,
    "quote_id": "3"
  }
}

Volley Code

// Create JSON
val itemsObject = JSONObject()
itemsObject.put("sku", "10-1001")
itemsObject.put("qty", 5)
itemsObject.put("quote_id", "3")

val itemsArray = JSONObject()
itemsArray.put("cartItem", itemsObject)


val jsonRequest = object : JsonObjectRequest(
        Request.Method.POST, url, itemsArray,

        Response.Listener { response ->

            try {

                binding.txtStatus.text = response.toString()

            } catch (e: JSONException) {
                e.printStackTrace()
                binding.txtStatus.text = e.toString()
            }

        },

        Response.ErrorListener { error ->

            binding.txtStatus.text = error.toString()

        }) {
        @Throws(AuthFailureError::class)
        override fun getBodyContentType(): String {
            return "application/json"
        }

        override fun getHeaders(): Map<String, String> {
            val apiHeader = HashMap<String, String>()
            apiHeader["Authorization"] = "Bearer $cusToken"
            return apiHeader
        }

    }

    val queue = Volley.newRequestQueue([email protected])
    queue.add(jsonRequest)

Solution

You should use JSONArray instead of JSONObject. Your itemsArray must be like this:

val itemsArray = JSONArray()

Your request payload must look like this and can have multiple objects:

[
   {
      "sku":"10-1001",
      "qty":5,
      "quote_id":"3"
   },
   {
      "sku":"10-1002",
      "qty":1,
      "quote_id":"2"
   }
]

The reason is because the payload now contains multiple items. You can add multiple JSONObject in the JSONArray.

Another approach can be if you want to send some other information in the request payload then you might need to use in the following manner:

{
   "cartItems":[
      {
         "sku":"10-1001",
         "qty":5,
         "quote_id":"3"
      },
      {
         "sku":"10-1002",
         "qty":1,
         "quote_id":"2"
      }
   ],
   "otherInfo":"sampleInfo"
}

Answered By — Mohit Ajwani

I am new to JSON and I am getting the follwoing Exception:

org.json.JSONArray cannot be converted to JSONObject in the first line of try section itself.

Please help me to remove this. Here’s my code:

try {   
    JSONObject json = new JSONObject(strResponse);

    //Get the element that holds the internship ( JSONArray )
    JSONArray name = json.names();
    JSONArray  internships = json.toJSONArray(name);

    //Loop the Array
    for(int i=0;i < internships.length();i++) {     
        Log.e("Message","loop");
        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject e = internships.getJSONObject(i);
        map.put("id",  String.valueOf("id"));
        map.put("title", "Title :" + e.getString("title"));
        map.put("company", "Company : " +  e.getString("company"));
        map.put("category", "Category : " +  e.getString("category"));
        mylist.add(map);
    } 
} catch(JSONException e) {
    Log.e("log_tag", "Error parsing data "+e.toString());
}

this is the json I am getting from my php file

[
 {
    "id": "31",
    "title": "Business Development - Executive",
    "company": "Indidelights",
    "category": "Sales and Business Development"
 },
 {
    "id": "40",
    "title": "Business Development - Ecommerce MH",
    "company": "Ram Gopal & Co",
    "category": "Sales and Business Development"
 },
 {
    "id": "41",
    "title": "Sales and Business development intern",
    "company": "Esanchalak",
    "category": "Sales and Business Development"
 },
 {
    "id": "42",
    "title": "Purchase Executive",
    "company": "Winni.in",
    "category": "Marketing"
 },
 {
    "id": "43",
    "title": "Marketing Intern",
    "company": "Walkover Web Solutions Pvt. Ltd.",
    "category": "Marketing"
 },
 {
    "id": "44",
    "title": "Marketing Intern",
    "company": "SkillKindle Learning Pvt Ltd",
    "category": "Marketing"
 },
 {
    "id": "45",
    "title": "Graphic Designer",
    "company": "Stylopa",
    "category": "Graphic Design / Art Work"
 },
 {
    "id": "46",
    "title": "Graphic Designer",
    "company": "LycondonFX",
    "category": "Graphic Design / Art Work"
 },
 {
    "id": "47",
    "title": "Web Designer",
    "company": "Xapify LLC",
    "category": "Software"
 },
 {
    "id": "48",
    "title": "Web Designer (Frontend)",
    "company": "gotrademark.in",
    "category": "Web Design and Development"
 },
 {
    "id": "49",
    "title": "Content Writing Intern",
    "company": "National Entrepreneurship Network",
    "category": "Content Writing / Journalism"
 },
 {
    "id": "50",
    "title": "Content Writing Intern",
    "company": "Pragmatum Training Pvt Ltd",
    "category": "Content Writing / Journalism"
 },
 {
    "id": "51",
    "title": "HR Intern",
    "company": "GATI Kintetsu Express Pvt Ltd",
    "category": "HR / Recruitment"
 },
 {
    "id": "52",
    "title": "Pharma Intern",
    "company": "Qlinics Health Care Pvt Ltd",
    "category": "BioTechnology / Pharma"
 },
 {
    "id": "53",
    "title": "Android Developer",
    "company": "InoXapps Mobile Solutions Pvt Ltd",
    "category": "Mobile App Development"
 },
 {
    "id": "54",
    "title": "Mobile App developer",
    "company": "RV Media Inc",
    "category": "Mobile App Development"
 },
 {
    "id": "55",
    "title": "Electronics Intern",
    "company": "GA SOFTWARE TECHNOLOGIES PVT LTD",
    "category": "Electronics Engineering"
 }
 ]

  • Ошибка json что это
  • Ошибка json не определено
  • Ошибка json parse error
  • Ошибка jrpcexception asn 1 decode error offset 0 unexpected end of buffer encountered перевод
  • Ошибка jrpcexception asn 1 decode error offset 0 unexpected end of buffer encountered как исправить