获取Arrayadapter列表中单击项的值

时间:2018-10-04 14:34:01

标签: android sqlite arraylist android-arrayadapter

我正在从事一个仅向listview显示数据来自数据库的项目。

我已经使用ArrayAdapter和AsyncTask来实现这一点。我的列表正在运行,但是单击时需要获取该特定列表项的值。

我已经将数据库唯一ID设置为listviewitem,我认为这有助于从视图中获取ID,但是我遇到了麻烦。我看了一些视频,他们获得了他们单击的每个列表项的确切数据库ID列。但是我对此概念知之甚少。

我的实际看法是这样的

enter image description here

这是我的数据库操作类

    package com.me.doctor.doctor_me;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteQueryBuilder;

    import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

    public class DatabaseOperation extends SQLiteAssetHelper {

        public static final int DB_VERSION = 1;
        public static final String DB_NAME= "app_db.db";

        public DatabaseOperation(Context context) {
            super(context, DB_NAME,null, DB_VERSION);
        }

        // Verify user Loggin
        public boolean loginUser(String email, String password) {
            SQLiteDatabase db = this.getReadableDatabase();
            SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

            String sqlTables = "user";
            qb.setTables(sqlTables);

            Cursor c = qb.query(db,null,"email = ? AND password = ?",new String[]{email,password},null,null,null);

            if (c.getCount() > 0) {
                return true;
            } else {
                return false;
            }
        }

        // Reg user
        public boolean registerUser(String user_name,String telephone,String nic,String gender,
                                    String email, String password){
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();

            contentValues.put("user_name", email);
            contentValues.put("telephone", telephone);
            contentValues.put("nic", nic);
            contentValues.put("gender", gender);
            contentValues.put("email", email);
            contentValues.put("password", password);

            long result = db.insert("user", null,contentValues);

            if(result == -1)
                return false;
            else
                return true;
        }

        // Get all infor from the doctor table to display in list view
        public Cursor getInformation(SQLiteDatabase db){
            String[] selectios = {"d_id","d_name","d_hospital","d_category"};
            Cursor cursor = db.query("doctor",selectios,null,null,null,null,null);

            return cursor;
        }

    }

保留列表视图的医生显示类

 package com.me.doctor.doctor_me;

 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;

 public class DisplayDoctor extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display_doctor_layout);
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute("get_info");
}

}

这是AsynTask类

package com.me.doctor.doctor_me;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class BackgroundTask extends AsyncTask<String,Doctor,String> {

Context ctx;
DoctorAdapter doctorAdapter;
Activity activity;
ListView listView;
Doctor doctor;

BackgroundTask(Context ctx){
    this.ctx = ctx;
    activity = (Activity) ctx;
    doctor = new Doctor();
}
@Override
protected String doInBackground(String... strings) {

    String method = strings[0];
    DatabaseOperation databaseOperation = new DatabaseOperation(ctx);
    if(method.equals("get_info")){
        listView = activity.findViewById(R.id.display_list_view);
        SQLiteDatabase db = databaseOperation.getReadableDatabase();
        Cursor cursor = databaseOperation.getInformation(db);
        doctorAdapter = new DoctorAdapter(ctx,R.layout.display_doctor_row);

        String name, category, hospital;
        int id;

        while(cursor.moveToNext()){
            id = cursor.getInt(cursor.getColumnIndex("d_id"));
            name = cursor.getString(cursor.getColumnIndex("d_name"));
            category = cursor.getString(cursor.getColumnIndex("d_category"));
            hospital = cursor.getString(cursor.getColumnIndex("d_hospital"));
            Doctor doctor = new Doctor(id,name,category,hospital);
            publishProgress(doctor);
        }
        return "get_info";
    }
    return null;
}

@Override
protected void onProgressUpdate(Doctor... values) {
    // add each of doctor class object add method inside the adapter class
    doctorAdapter.add(values[0]);
}

@Override
protected void onPostExecute(String s) {
    if(s.equals("get_info")){
        listView.setAdapter(doctorAdapter);

        listView.setOnItemClickListener(new  android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    final int position, long id) {

                // Stuck at here
            }
        });
    }else{
        Toast.makeText(ctx,s,Toast.LENGTH_LONG).show();
    }
}
}

这是适配器类

package com.me.doctor.doctor_me;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class DoctorAdapter extends ArrayAdapter {

List list = new ArrayList();
public DoctorAdapter(@NonNull Context context, int resource) {
    super(context, resource);
}

// Add each object of doctor to the list object
public void add(@Nullable Doctor object) {
    list.add(object);
    super.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View row = convertView;
    DoctorHolder doctorHolder;

    if(row == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflater.inflate(R.layout.display_doctor_row,parent,false);

        doctorHolder = new DoctorHolder();
        doctorHolder.tx_name = row.findViewById(R.id.t_name);
        doctorHolder.tx_category = row.findViewById(R.id.t_category);
        doctorHolder.tx_hospital = row.findViewById(R.id.t_hospital);
        doctorHolder.tx_id = row.findViewById(R.id.t_id);
        row.setTag(doctorHolder);
    }else{
        doctorHolder = (DoctorHolder) row.getTag();
    }

    Doctor doctor = (Doctor)getItem(position);
    doctorHolder.tx_id.setText(Integer.toString(doctor.getId()));
    doctorHolder.tx_name.setText(doctor.getName().toString());
    doctorHolder.tx_category.setText(doctor.getCategory().toString());
    doctorHolder.tx_hospital.setText(doctor.getHospital().toString());

    return row;
}
static class DoctorHolder{
    TextView tx_name, tx_category, tx_hospital, tx_id;
}
}

我认为不需要附加XML,因为我已经发布了最终视图。如果需要,请告诉我。实际上,我实际上需要获取每个可点击的项目数据库ID列值,因为使用该ID,我需要在其他活动中进行更多处理。

3 个答案:

答案 0 :(得分:1)

尝试一下

listView.setOnItemClickListener(new  android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                final int position, long id) {

           Doctor doctor = (Doctor)parent.getItemAtPosition(position);
           String ID = Integer.toString(doctor.getId());


        }
    });

答案 1 :(得分:1)

getView方法内的OnClickListener

        row.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
      Toast.makeText(view.getContext(),doctor.getHospital().toString(),Toast.LENGTH_LONG).show();


    }
});

希望这对您有帮助...祝您有美好的一天

答案 2 :(得分:0)

在您的onBindViewHolder内部,您需要致电OnClickListener

holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          String name = list.get(position).getValueName();

        }
    });