android org.json.JSONArray не может быть преобразован в JSONObject (не может отобразить URL) - PullRequest
0 голосов
/ 01 июня 2018

Я новичок в Android. Я работаю над приложением веб-сервиса и бэкэндом в laravel. Я хочу прочитать сделки и в соответствии с заданием я нахожу задачи, но не могу отобразить данные, которые показывают мне эту ошибку.

"org.json.JSONArray cannot be converted to JSONObject"

enter image description here

   public static final String TacheNamearray = "libelle_tache";
   public static final String TacheName  = "libelle_tache";
   public static final String JSON_ARRAY_TACHE = "result";
   public static final String MetierNamearray = "libelle_metier";
   public static final String MetierName  = "libelle_metier";
   public static final String JSON_ARRAY = "result";
   private JSONArray result;
   private ArrayList<String> arrayListTache;
   TextView tacheename;
   Spinner spinner_tache;
   Spinner spinner;
   Button button;
   private GpsTracker gpsTracker;
   private TextView tvLatitude,tvLongitude;
   String URL_Post = "http://192.168.1.233/projet/public/api/getmetier";
   private ArrayList<String> arrayList;
   TextView employeename;
   private TextView tvUsername, tvEmail;
   private UserInfo userInfo;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recherche);
    spinner= (Spinner) findViewById(R.id.spnrEmployee);
    spinner_tache= (Spinner) findViewById(R.id.spnrTache);
    tacheename= (TextView) findViewById(R.id.tvTache);
    employeename= (TextView) findViewById(R.id.tvName);
    button = (Button) findViewById(R.id.button);
    tvLatitude = (TextView)findViewById(R.id.latitude);
    tvLongitude = (TextView)findViewById(R.id.longitude);
    arrayListTache = new ArrayList<String>();
    userInfo        = new UserInfo(this);
    tvEmail         = (TextView)findViewById(R.id.key_email);
    String email    = userInfo.getKeyEmail();


    tvEmail.setText(email);

    arrayList = new ArrayList<String>();
    getMetiers();
    spinner.setOnItemSelectedListener(new 
    AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int 
    position, long id) {
            //Setting the values to textviews for a selected item
            String metier= arrayList.get(position);
            getTaches(metier);
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            employeename.setText("");

        }
    });
    }
    private void getMetiers() {
    StringRequest stringRequest = new 
    StringRequest("http://192.168.1.233/projet/public/api/getmetier",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        j = new JSONObject(response);
                        result = j.getJSONArray(JSON_ARRAY);
                        empdetails(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
    }
     private void empdetails(JSONArray j) {
    for (int i = 0; i < j.length(); i++) {
        try {
            JSONObject json = j.getJSONObject(i);
            arrayList.add(json.getString(MetierNamearray));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    // arrayList.add(0,"Select Employee");
    spinner.setAdapter(new ArrayAdapter<String>(RechercheActivity.this, 
   android.R.layout.simple_spinner_dropdown_item, arrayList));
   }
   //Method to get student name of a particular position
   private String getemployeeName(int position){
    String name="";
    try {
        //Getting object of given index
        JSONObject json = result.getJSONObject(position);
        //Fetching name from that object
        name = json.getString(MetierName);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //Returning the name
    return name;
     }

    public void getLocation(View view){
    gpsTracker = new GpsTracker(RechercheActivity.this);

    insert();
    if(gpsTracker.canGetLocation()){
        double latitude = gpsTracker.getLatitude();
        double longitude = gpsTracker.getLongitude();
        tvLatitude.setText(String.valueOf(latitude));
        tvLongitude.setText(String.valueOf(longitude));

    }else{
        gpsTracker.showSettingsAlert();
    }
    Intent intent = new Intent(RechercheActivity.this, 
    TechnicienActivity.class);
    startActivity(intent);

   }


    public void insert(){
    StringRequest stringRequest = new StringRequest(Request.Method.POST, 
    URL_Post, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

    Toast.makeText(getApplication(),response,Toast.LENGTH_LONG).show();
        }
    }, new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

   Toast.makeText(RechercheActivity.this,error+"",Toast.LENGTH_LONG).show();
        }
    }

    ){
        @Override
        protected Map<String,String>getParams()throws AuthFailureError {
            Map<String,String> params = new HashMap<String,String>();
            String text1 = spinner.getSelectedItem().toString();
            String lon = tvLongitude.getText().toString().trim();
            String lat = tvLatitude.getText().toString().trim();
            params.put("libelle_metier",text1);

            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

    }

     private void getTaches(String metier) {
     StringRequest stringRequest = new
     StringRequest("http://192.168.1.233/projet/public/api/gettaches",
                new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        j = new JSONObject(response);
                        result= j.getJSONArray(JSON_ARRAY_TACHE);
                        tachedetails(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
          RequestQueue requestQueue = Volley.newRequestQueue(this);
          requestQueue.add(stringRequest);
           }

     private void tachedetails(JSONArray j) {
     for (int i = 0; i < j.length(); i++) {
        try {
            JSONObject json = j.getJSONObject(i);
            arrayListTache.add(json.getString(TacheNamearray));
        } catch (JSONException e) {
            e.printStackTrace();
       }
       // arrayListTache.add(0,"Select Employee");
      spinner_tache.setAdapter(new ArrayAdapter<String> 
     (RechercheActivity.this,
            android.R.layout.simple_spinner_dropdown_item, arrayListTache));
        }

   //Method to get student name of a particular position
    private String gettacheName(int position){
    String libelle_tache="";
    try {
        //Getting object of given index
        JSONObject json = result.getJSONObject(position);
        //Fetching name from that object
        libelle_tache = json.getString(TacheName);
       } catch (JSONException e) {
        e.printStackTrace();
           }
    //Returning the name
    return libelle_tache;
     }

, и часть JSON дает мне это ..

[{"id":1,"libelle_metier":"metier 1","deleted_at":null,"created_at":"2018-04-03 09:12:37","updated_at":"2018-04-03 09:12:37"},{"id":2,"libelle_metier":"metier 2","deleted_at":null,"created_at":"2018-04-03 09:12:44","updated_at":"2018-04-03 09:12:44"},{"id":3,"libelle_metier":"metier 4","deleted_at":null,"created_at":"2018-04-03 09:46:36","updated_at":"2018-04-04 14:15:06"}]

и мой код PHP и

class TechniciensController extends Controller
  {
public function GetTechniciens() 
  {
    return Technicien::all();
  }

1 Ответ

0 голосов
/ 01 июня 2018
 return json_encode(Technicien::all());

тогда вы можете использовать json_decode.

эту строку:

  j = new JSONObject(response);

обновить его:

   JSONArray jsonarray = new JSONArray(response);

я думаю, что это работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...