Autore Topic: Aggiungere azione ad ogni riga di una listview  (Letto 207 volte)

Offline newbie2016

  • Utente junior
  • **
  • Post: 79
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Cubot X9
  • Sistema operativo:
    Windows 7
Aggiungere azione ad ogni riga di una listview
« il: 25 Luglio 2016, 18:59:04 CEST »
0
Salve, dovrei aggiungere ad ogni riga di una listview una azione che permetta di visualizzare la scheda dell'item cliccato.

Ho il seguente codice per elencare la listview dopo una ricerca:
CercaActivity.java
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://vps278343.ovh.net/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.id = json_data.getString("id");
                        fishData.Img= json_data.getString("img");
                        fishData.Cognome = json_data.getString("cognome");
                        fishData.Nome = json_data.getString("nome");
                        fishData.paese = json_data.getString("paese");
                        fishData.professione = json_data.getString("professione");
                        fishData.sesso = json_data.getString("sesso");
                        fishData.zodiacale = json_data.getString("zodiacale");
                        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();
                }

            }

        }

    }
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ViewEmployee.class);
        HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
        String empId = map.get(Config.TAG_ID).toString();
        intent.putExtra(Config.EMP_ID,empId);
        startActivity(intent);
    }
}

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));
        myHolder.textSesso.setText(current.sesso);
        myHolder.textProfessione.setText(current.professione);
        myHolder.textZodiacale.setText(current.zodiacale);
    }

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


    class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView textId;
        ImageView ivImg;
        TextView textCognome;
        TextView textNome;
        TextView textPaese;
        TextView textSesso;
        TextView textProfessione;
        TextView textZodiacale;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textId= (TextView) itemView.findViewById(R.id.textId);
            ivImg= (ImageView) itemView.findViewById(R.id.ivImg);
            textCognome= (TextView) itemView.findViewById(R.id.textCognome);
            textNome = (TextView) itemView.findViewById(R.id.textNome);
            textPaese = (TextView) itemView.findViewById(R.id.textPaese);
            textSesso = (TextView) itemView.findViewById(R.id.textSesso);
            textProfessione = (TextView) itemView.findViewById(R.id.textProfessione);
            textZodiacale = (TextView) itemView.findViewById(R.id.textZodiacale);
            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();

        }
    }

}
Adesso se clicco su qualsiasi item mi appare il Toast "You clicked an item".

Dovrei far aprire una schermata con i dati dell'item selezionato.

Ho provato a fare così ma non mi da nessun risultato:
Codice (Java): [Seleziona]
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ViewEmployee.class);
        HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
        String empId = map.get(Config.TAG_ID).toString();
        intent.putExtra(Config.EMP_ID,empId);
        startActivity(intent);
    }

Suggerimenti?

Grazie

Post unito: [time]25 Luglio 2016, 23:43:34 CEST[/time]
nel file AdapterFish.java ho fatto così:
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));
        myHolder.textSesso.setText(current.sesso);
        myHolder.textProfessione.setText(current.professione);
        myHolder.textZodiacale.setText(current.zodiacale);
    }

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


    class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView textId;
        ImageView ivImg;
        TextView textCognome;
        TextView textNome;
        TextView textPaese;
        TextView textSesso;
        TextView textProfessione;
        TextView textZodiacale;
        ArrayList<Context> context = new ArrayList<Context>();
        Context data;
         // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            this.context = context;
            this.data = data;
            itemView.setOnClickListener(this);
            textId= (TextView) itemView.findViewById(R.id.textId);
            ivImg= (ImageView) itemView.findViewById(R.id.ivImg);
            textCognome= (TextView) itemView.findViewById(R.id.textCognome);
            textNome = (TextView) itemView.findViewById(R.id.textNome);
            textPaese = (TextView) itemView.findViewById(R.id.textPaese);
            textSesso = (TextView) itemView.findViewById(R.id.textSesso);
            textProfessione = (TextView) itemView.findViewById(R.id.textProfessione);
            textZodiacale = (TextView) itemView.findViewById(R.id.textZodiacale);
        }

        // Click event for all items
        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            Context data = this.context.get(position);
            Intent intent = new Intent(this.data,UserDetails.class);
            intent.putExtra("textId",textId.getId());
            this.data.startActivity(intent);

        }
    }

}

parte l'applicazione quando vado a cliccare su un item della ListView l'applicazione si chiude e nel logCat mi da questo errore:
Codice: [Seleziona]
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.mariorossi.search, PID: 31454
                                                                           java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                                                               at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                               at java.util.ArrayList.get(ArrayList.java:308)
                                                                               at com.mariorossi.search.AdapterFish$MyHolder.onClick(AdapterFish.java:101)
Che errore è?
Come posso risolverlo?

Grazie

Post unito: 26 Luglio 2016, 10:14:51 CEST
Un pratica devo aprire un'altra activity inviando un dato (id o e-mail) per visualizzare i dati dell'utente cliccato.
« Ultima modifica: 26 Luglio 2016, 10:14:51 CEST da newbie2016, Reason: Merged DoublePost »