在项目单击时从列表视图中检索“_ID”值

时间:2016-06-14 13:56:17

标签: java listview android-cursoradapter android-cursor android-database

我使用适配器填充列表视图,并使用方法“GetItemId”从所点击项目的数据库中获取_ID。

但是,该值未进入详细信息活动(显示listview上单击项目的详细信息),我在此错误中搜索了很多内容,我无法修复它。

我没有错误,但详细信息活动为空,因为它没有获取id / incocrrect id来获取数据。

我的适配器:

public class RegistosCursorAdapter extends CursorAdapter {
    public RegistosCursorAdapter (Context context, Cursor cursor, int flags) {
        super(context, cursor, 0);
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    // The newView method is used to inflate a new view and return it,
    // you don't bind any data to the view at this point.
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.registos_layout, parent, false);
    }

    // The bindView method is used to bind all data to a given view
    // such as setting the text on a TextView.
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // Find fields to populate in inflated template
        TextView um = (TextView) view.findViewById(R.id.um);
        TextView dois = (TextView) view.findViewById(R.id.dois);
        // Extract properties from cursor
        String body = cursor.getString(cursor.getColumnIndexOrThrow("Sintoma"));
        String priority = cursor.getString(cursor.getColumnIndexOrThrow("Dinicio"));
        // Populate fields with extracted properties
        um.setText(body);
        dois.setText(String.valueOf(priority));
    }
}

包含listview的活动

    public class TabSintomas extends Fragment {

    private DAL dal;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final RelativeLayout rootView = (RelativeLayout) inflater.inflate(R.layout.fragment_tab_sintomas, container, false);

        dal = new DAL(getActivity());
        dal.connect(DBAccessMode.READ);

        // Vai usar um cursor para percorrer a base de dados, usando o metodo "selectALLFromRegSintomas()" que vem da classe "DAL".
        Cursor cursor = dal.selectALLFromRegSintomas();
        // é precisar declarar o layout do fragment com que estamos a trabalhar
        final View v = inflater.inflate(R.layout.fragment_tab_sintomas, container, false);

        // Declarar a listview onde vao aparecer os dados
        ListView lv = (ListView) v.findViewById(R.id.listv);
        // Declarar o adapter que define como aparecem os dados na listview
        final RegistosCursorAdapter todoAdapter = new RegistosCursorAdapter(getActivity(), cursor, 0);
        // Ligar o adapter
        lv.setAdapter(todoAdapter);

        //  Nos fragments é preciso sempre fazer return do layout que queremos mostrar, neste caso (fragment_tab_sintomas);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                long idpos = todoAdapter.getItemId(position);// This is the _ID value

                Intent intent = new Intent(getActivity(), DetalhesSintoma.class);
                intent.putExtra("myExtras", idpos);
                startActivity(intent);
                //Toast.makeText(getActivity(),"clique",
                //        Toast.LENGTH_SHORT).show();
            }
        });
        return v;
    }
}

DetailsActivity(需要点击项目中的ID以显示该项目的详细信息)

    public class DetalhesSintoma extends AppCompatActivity {

    private DAL dal;
    private TextView DataInicio;
    private EditText HoraIncio;
    private TextView DataFim;
    private EditText HoraFim;
    private TextView Intensidade;
    private TextView Motivo;
    private TextView Medicacao;
    private Button Apagar;
    private Button Concluido;
    private long idpos;

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

        DataInicio = (TextView) findViewById(R.id.DiaInicioText);
        // HoraIncio = (EditText) findViewById(R.id.HoraInicioText);
        DataFim = (TextView) findViewById(R.id.DiaFimText);
        //  HoraFim = () findViewById(R.id.HoraFimText);
        Intensidade = (TextView) findViewById(R.id.IntensidadeText);
        Motivo = (TextView) findViewById(R.id.MotivoText);
        Medicacao = (TextView) findViewById(R.id.MedicacaoText);
        Apagar = (Button) findViewById(R.id.btnApagar);

        Concluido = (Button) findViewById(R.id.btnConcluido);

        Intent intent = getIntent();
        idpos = intent.getLongExtra("myExtras", 0);

        dal = new DAL(this);
        dal.connect(DBAccessMode.READ);

        Cursor res = dal.selectFromRegSintomasWhereId(idpos);
        res.moveToFirst();
        StringBuilder datahora = new StringBuilder();
        while (!res.isAfterLast()) {
            Intensidade.setText(res.getString(res.getColumnIndex(DBContract.Reg_sintomas.COL_Intensidade)));
            String Data = res.getString(res.getColumnIndex(DBContract.Reg_sintomas.COL_D_Inicio));
            String Hora = res.getString(res.getColumnIndex(DBContract.Reg_sintomas.COL_H_Inicio));
            res.moveToNext();
            DataInicio.setText(datahora.append(Data + " ás " + Hora));
        }

        Cursor res1 = dal.selectFromRegSintomasWhereId(idpos);
        res1.moveToFirst();
        StringBuilder datahoraF = new StringBuilder();
        while (!res1.isAfterLast()) {
            String Data = res1.getString(res1.getColumnIndex(DBContract.Reg_sintomas.COL_D_Fim));
            String Hora = res1.getString(res1.getColumnIndex(DBContract.Reg_sintomas.COL_H_Fim));
            res1.moveToNext();
            DataFim.setText(datahoraF.append(Data + " ás " + Hora));
        }

        Cursor res2 = dal.selectFromMotivoSintomassWhereId(idpos);
        res2.moveToFirst();
        StringBuilder sb = new StringBuilder();
        while (!res2.isAfterLast()) {
            sb.append(res2.getString(res2.getColumnIndex(DBContract.Motivo_sintomas.COL_Motivo)));
            res2.moveToNext();
        }
        Motivo.setText(sb.toString());

        Cursor res3 = dal.selectMedicacaoWhereId(idpos);
        res3.moveToFirst();
        StringBuilder sb2 = new StringBuilder();
        while (!res3.isAfterLast()) {
            sb2.append(res3.getString(res3.getColumnIndex(DBContract.Medicacao.COL_Medicacao)));
            res3.moveToNext();
        }
        Medicacao.setText(sb2.toString());


        Concluido.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(DetalhesSintoma.this, VerRegsSintomas.class);
                startActivity(intent);
            }
        });


        Apagar.setOnClickListener(new View.OnClickListener()

        {
            public void onClick(View v) {

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(DetalhesSintoma.this);

                // Setting Dialog Title
                alertDialog.setTitle("Apagar");

                // Setting Dialog Message
                alertDialog.setMessage("Tem a certeza que quer apagar este registo ? ");

                // Setting Icon to Dialog

                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dal.deleteFromRegSintomasWhereId(idpos);
                        Intent intent = new Intent(DetalhesSintoma.this, VerRegsSintomas.class);
                        startActivity(intent);
                        Toast.makeText(getApplicationContext(), "Registo apagado !", Toast.LENGTH_SHORT).show();
                    }
                });

                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("Não", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Write your code here to invoke NO event
                        Toast.makeText(getApplicationContext(), "Acção cancelada", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                });

                // Showing Alert Message
                alertDialog.show();
            }
        });
    }
}

我尝试从列表视图获取ID的代码,上面的代码,为了您更轻松:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            long idpos = todoAdapter.getItemId(position);// This is the _ID value

            Intent intent = new Intent(getActivity(), DetalhesSintoma.class);
            intent.putExtra("myExtras", idpos);
            startActivity(intent);
            //Toast.makeText(getActivity(),"clique",
            //        Toast.LENGTH_SHORT).show();
        }
    });

如果我设置idpos = 1,他会向我显示satabase上第一项的详细信息,所以我假设他没有通过antything

1 个答案:

答案 0 :(得分:0)

1)来自here

getItemAtPosition(position);
    // ListView Item Click Listener
    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {

            // ListView Clicked item index
            int itemPosition     = position;

            // ListView Clicked item value
            String  itemValue    = (String) listView.getItemAtPosition(position);

            // Show Alert 
            Toast.makeText(getApplicationContext(),
                 "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                 .show();

        }

    }); 

尝试使用:myListData.get(position).getId()其中myListData是制作列表的数组。

  

我想指出getItemId()ArrayAdapter()总是返回   -1与assert false : "TODO"; return -1;

来源:SO Question

检查getPosition()getItem()getItemId()

的Android参考

请参阅此处:android-reference