Autore Topic: problema Search View with PHP and MySQL  (Letto 195 volte)

Offline newbie2016

  • Utente junior
  • **
  • Post: 79
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Cubot X9
  • Sistema operativo:
    Windows 7
problema Search View with PHP and MySQL
« il: 21 Luglio 2016, 13:52:03 CEST »
0
Salve, ho un problema con una SearchView, ho seguito un tutorial per l'implementazione e non mi da nessun problema però quando vado a fare una ricerca mi da un messaggio
org.json.JSONException: Value Connection of type.java.lang.String cannot be converted to JSONArray

nel logcat mi da questa riga di errore
07-21 13:37:41.727 4461-4461/com.newbie.search E/RecyclerView: No adapter attached; skipping layout

il codice java che utilizzo per la ricerca è il seguente:
Codice (Java): [Seleziona]
public class CercaActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFish;
    private AdapterFish mAdapter;

    SearchView searchView = null;


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // adds item to action bar
        getMenuInflater().inflate(R.menu.search_main, menu);

        // Get Search item from action bar and Get Search service
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchManager searchManager = (SearchManager) CercaActivity.this.getSystemService(Context.SEARCH_SERVICE);
        if (searchItem != null) {
            searchView = (SearchView) searchItem.getActionView();
        }
        if (searchView != null) {
            searchView.setSearchableInfo(searchManager.getSearchableInfo(CercaActivity.this.getComponentName()));
            searchView.setIconified(false);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    // Every time when you press search button on keypad an Activity is recreated which in turn calls this function
    @Override
    protected void onNewIntent(Intent intent) {
        // Get search query and create object of class AsyncFetch
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            if (searchView != null) {
                searchView.clearFocus();
            }
            new AsyncFetch(query).execute();

        }
    }

    // Create class AsyncFetch
    private class AsyncFetch extends AsyncTask<String, String, String> {

        ProgressDialog pdLoading = new ProgressDialog(CercaActivity.this);
        HttpURLConnection conn;
        URL url = null;
        String searchQuery;

        public AsyncFetch(String searchQuery){
            this.searchQuery=searchQuery;
        }

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

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your php file resides
                url = new URL("http://www.sito.com/cerca/utenti_search.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");

                // setDoInput and setDoOutput to true as we send and recieve data
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // add parameter to our above url
                Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {
                    return("Connection error");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread
            pdLoading.dismiss();
            List<DataFish> data=new ArrayList<>();

            pdLoading.dismiss();
            if(result.equals("no rows")) {
                Toast.makeText(CercaActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
            }else{

                try {

                    JSONArray jArray = new JSONArray(result);

                    // Extract data from json and store into ArrayList as class objects
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json_data = jArray.getJSONObject(i);
                        DataFish fishData = new DataFish();
                        fishData.Cognome = json_data.getString("cognome");
                        fishData.Nome = json_data.getString("nome");
                        fishData.paese = json_data.getString("paese");
                        data.add(fishData);
                    }

                    // Setup and Handover data to recyclerview
                    mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                    mAdapter = new AdapterFish(CercaActivity.this, data);
                    mRVFish.setAdapter(mAdapter);
                    mRVFish.setLayoutManager(new LinearLayoutManager(CercaActivity.this));

                } catch (JSONException e) {
                    // You to understand what actually error is and handle it appropriately
                    Toast.makeText(CercaActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                    Toast.makeText(CercaActivity.this, result.toString(), Toast.LENGTH_LONG).show();
                }

            }

        }

    }
}

Il codice java dell'adapter è AdapterFish.java:
Codice (Java): [Seleziona]
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataFish> data= Collections.emptyList();
    DataFish current;

    // create constructor to initialize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFish> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when ViewHolder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in RecyclerView to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        DataFish current=data.get(position);
        myHolder.textCognome.setText(current.Cognome);
        myHolder.textNome.setText(current.Nome);
        myHolder.textPaese.setText(current.paese);
        myHolder.textPaese.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }


    class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView textCognome;
        TextView textNome;
        TextView textPaese;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textCognome= (TextView) itemView.findViewById(R.id.textCognome);
            textNome = (TextView) itemView.findViewById(R.id.textNome);
            textPaese = (TextView) itemView.findViewById(R.id.textPaese);
            itemView.setOnClickListener(this);
        }

        // Click event for all items
        @Override
        public void onClick(View v) {

            Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();

        }

    }

}


il file php per la ricerca è il seguente
Codice: [Seleziona]
if(isset($_POST['searchQuery']))
     {
               require_once('configdb.php');
          $search_query=$_POST['searchQuery'];
          $sql = 'SELECT * from utenti where MATCH(cognome,nome,paese,provincia) AGAINST(:search_query)';
          $statement = $connection->prepare($sql);
          $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
          $statement->execute();
          if($statement->rowCount())
          {
            $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            header('Content-type: application/json');
               echo json_encode($row_all);
          } 
          elseif(!$statement->rowCount())
          {
            echo "no rows";
          }
     }

 Come posso risolvere questo problema?

Grazie

Offline tonno16

  • Utente storico
  • *****
  • Post: 1169
  • Respect: +56
    • Mostra profilo
  • Dispositivo Android:
    moto g
  • Play Store ID:
    Diego Tonini
  • Sistema operativo:
    OpenSuse
Re:problema Search View with PHP and MySQL
« Risposta #1 il: 21 Luglio 2016, 17:17:46 CEST »
0
Accade spesso. Quando hai un json con una certa struttura se per esempio il campo palla è un intero tu non puoi parsarlo come fosse un array.

Offline newbie2016

  • Utente junior
  • **
  • Post: 79
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Cubot X9
  • Sistema operativo:
    Windows 7
Re:problema Search View with PHP and MySQL
« Risposta #2 il: 21 Luglio 2016, 17:49:30 CEST »
0
Grazie per la risposta.
Ma io sto passando dei campi testo.
Come modificarlo?
Grazie


Post unito: 21 Luglio 2016, 21:43:36 CEST
Ho risolto.

nella riga del file php
Codice: [Seleziona]
$sql = 'SELECT * from utenti where MATCH(cognome,nome,paese,provincia) AGAINST(:search_query)';
ho lasciato solo paeseed eliminato tutto il resto.
« Ultima modifica: 21 Luglio 2016, 21:43:36 CEST da newbie2016, Reason: Merged DoublePost »