Blackjuker Blackjuker - 5 months ago
330 0

I'm new to android, i started coding an application but i have a message saying the value Villa cannot be converted to JSONObject. I tried debuging using Log i saw my json array from my server. i don't know why it is not showing in my recycler View. this is my php file

PHP

Value Villa of type java.lang.String cannot be converted to JSONObject

<?php
//session_start();
$db_user="root";
	$db_pass="";
	$db_host="localhost";
	$db_name="house_finder";

	$type =  isset($_POST['type'])?$_POST['type']:NULL;
	$ville =  isset($_POST['ville'])?$_POST['ville']:NULL;
	$con =mysqli_connect($db_host,$db_user,$db_pass,$db_name);
	
$type = "Villa";  // this value is to test rapidly in my application
$ville = "bamenda"; // this value is to test rapidly in my application
	/**
	*   On va ajouter l'image ici 
	**/
	echo $type;
	
	$query = "SELECT tb_article.quartier,tb_article.prix,tb_article.description,tb_article.etat, tb_bayeur.tel_bayeur FROM 
	tb_article JOIN tb_bayeur on tb_article.id_bailleur = tb_bayeur.id_bayeur WHERE tb_article.type='$type' AND tb_article.nomVille='$ville'";

	//$query = "SELECT * from tb_article"
	$result = mysqli_query($con,$query);
	
	$response = array();
	
	
	

	while($row=mysqli_fetch_array($result))
	{
		array_push($response,array('quartier'=>$row[0],'prix'=>$row[1],'description'=>$row[2],'etat'=>$row[3],'tel_bayeur'=>$row[4]));
		//array_push($response);
	}
	
	mysqli_close($con);
	
	echo json_encode(array('server_response'=>$response));
	
	?>



and this is is my java class 



package com.example.tantine1.housefindpro;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tantine1 on 4/28/2016.
 */
public class consulAffiche extends AppCompatActivity{
    /**
     * @param savedInstanceState
     * ici on affiche les maison a louer de moins detailler
     */
    private static final String TAG="RecyclerViewExample";
    String tabTypeVille [];
    RecyclerView recyclerView;
    globalVars globalVars = new globalVars();
    String json_string=globalVars.getUrl()+"consulAfficheMaison.php";
    ProgressBar progressBar;
    MyRecyclerAdapterConsul adapter;
    /**
     * Changer sa en maison après
     */
    private List<Maison> feedsList;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.consulaffiche);

        //Récupération du tableau venant de ConsulPrincipal avec le type et ville selectionner
        Intent intent = this.getIntent();
        tabTypeVille = intent.getStringArrayExtra("tableauValeur");

        Log.i("type",tabTypeVille[0]);
        Log.i("ville",tabTypeVille[1]);

        recyclerView = (RecyclerView)findViewById(R.id.my_recycler_view);

        //Layout manager for Recycler view
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        progressBar = (ProgressBar)findViewById(R.id.progress_bar);
        progressBar.setVisibility(View.VISIBLE);

        //Downloading data from below url
        AsyncHttpTask as =  new AsyncHttpTask();
       as.execute(json_string);

    }

    public class AsyncHttpTask extends AsyncTask<String, Void, Integer>{
        Integer result;
        @Override
        protected void onPreExecute() {
          setProgressBarIndeterminate(true);
        }

        @Override
        protected Integer doInBackground(String... params) {
            result = 0;
            HttpURLConnection urlConnection;

            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection)url.openConnection();
                int statusCode = urlConnection.getResponseCode();
                    Log.i("statusI", String.valueOf(statusCode));
                //200 represents HTTP Ok
                if(statusCode==200){
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line=r.readLine())!=null){
                        response.append(line);
                    }
                   // Log.i("response",response.toString());
                    Log.i("arnaud", "test");
                    parseResult(String.valueOf(response));
                    result=1; // Successful
                }else {
                    result = 0; //Failed to fetch data!
                }

            }catch (Exception e){
                Log.d(TAG,e.getLocalizedMessage());
            }

            return result;
        }

        @Override
        protected void onPostExecute(Integer integer) {

            //Download complete. let us update UI
            progressBar.setVisibility(View.GONE);

            if(result==1){
                adapter = new MyRecyclerAdapterConsul(getApplicationContext(),feedsList);
                recyclerView.setAdapter(adapter);
            }else{
                Toast.makeText(consulAffiche.this,"Failed to fetch data!",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void parseResult(String result){
        Maison item;
        String st;






        try {
            JSONObject response = new JSONObject(result);
            JSONArray jsonArray = response.getJSONArray("server_response");
            int count = 0;

            while (count<jsonArray.length()){
                JSONObject jo = jsonArray.getJSONObject(count);
                count++;
                item = new Maison();
                item.setQuartier(jo.getString("quartier"));


            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.i("arnaud0",e.getMessage());
        }


        //JSONArray posts = response.optJSONArray("server_response");
        feedsList = new ArrayList<>();
        // Log.i("arnaud1",posts.getString() );
          /*  for(int i=0;i<posts.length();i++){
                JSONObject post = posts.optJSONObject(i);
                item = new Maison();

                item.setQuartier(post.optString("quartier"));
                item.setPrix(post.optString("prix"));
                item.setDescription(post.optString("description"));
                item.setEtat(post.optString("etat"));
                item.setTel_bayeur(post.optString("tel_bayeur"));

                feedsList.add(item);
            }*/


    }


}