How to get rowID of custom ListView's selected row's child?

依然范特西╮ 提交于 2019-12-10 11:35:18

问题


I've a custom list view with 4 textViews and 2 buttons,which i am filling up via database,

TV NAME | TV EMAIL | TV NO | TV ID(database primary key,set invisible) | ButtonEDIT | ButtonDelete.

I successfully got the id from the database,which is set as primary key.

Now what i want to do is,when i PRESS ButtonEDIT,it should toast a message something like "Edit selected for ID :" + TVID.getText().toString(),so basically i want to display the value which is stored in the TVID(i.e. my database id).

But when i am trying to do it,it only displays the firstID (0) for buttons of different rows,please do help asap.

Am linking code below

Custom ListView Adapter :

package com.iwill.Database_add_display;

import java.io.ObjectOutputStream.PutField;
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyAdapter extends BaseAdapter
{

        private ArrayList<userdetails> data;
        private static LayoutInflater minflater=null;
        private int[] userArray;
        public MyAdapter(Context context,ArrayList<userdetails> results)
        {
            data = results;
            minflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() 
        {
              return data.size();
        }

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

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

        public int getUserArray(int position){
            return userArray[position];
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) 
        {
            ViewHolder holder;
              if (convertView == null) 
              {
                   convertView = minflater.inflate(R.layout.row, null);
                   holder = new ViewHolder();
                   holder.tvname = (TextView) convertView.findViewById(R.id.textname);
                   holder.tvemail = (TextView) convertView.findViewById(R.id.textemail);
                   holder.tvno = (TextView) convertView.findViewById(R.id.textno);
                   holder.tvID = (TextView)convertView.findViewById(R.id.textID);                  
                   holder.b1 = (Button) convertView.findViewById(R.id.btnEdit);
                   holder.b2 = (Button) convertView.findViewById(R.id.btnDelete);

                   //convertView.setTag(holder);
                   convertView.setTag(holder);
              } 
              else 
              {
                  holder = (ViewHolder) convertView.getTag();
              }
              holder.tvname.setText(data.get(position).getName());
              holder.tvemail.setText(data.get(position).getMail());
              holder.tvno.setText(data.get(position).getNo());
              holder.tvID.setText(String.valueOf(data.get(position).getID()));
              return convertView;
        }
        static class ViewHolder 
        {
              TextView tvname;
              TextView tvemail;
              TextView tvno;
              Button b1;
              Button b2;
              TextView tvID;
             }
}

ListActivity :

package com.iwill.Database_add_display;

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

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class viewnameactivity extends Activity 
{
    ArrayList<userdetails> mylist = new ArrayList<userdetails>();

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    ListView listView;
    MyAdapter adapter;
    int pos;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewname);


        mDbHelper = new DatabaseHelper(this);

        final List<userdetails> List = mDbHelper.selectAll();
            for (int i = 0; i < List.size(); i++) 
        {
            //Log.i("List of Data....", List.get(i));
        }

        for (int j = 0; j < List.size(); j++) 
        { 
            mylist.add(List.get(j));
            Log.i("List View :", mylist.get(j).toString());
        }

        listView = (ListView)findViewById(R.id.listView);
        adapter = new MyAdapter(this,mylist);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

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

                Toast.makeText(viewnameactivity.this,"Edit button of ID : "+ adapter.getUserArray(position)+" selected.",
                        Toast.LENGTH_SHORT).show();

                pos = adapter.getUserArray(position);
            }
        });

        mDbHelper.close();   

    Button btnBack = (Button)findViewById(R.id.btnBack);
    btnBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent i = new Intent(viewnameactivity.this,MainActivity.class);
            startActivity(i);

        }
    });

/*  Button btnEdit = (Button)findViewById(R.id.btnEdit);
    btnEdit.setOnClickListener(new OnClickListener() {

        //TextView strID = (TextView)findViewById(R.id.textID);
        //long lngID = Long.parseLong(strID.getText().toString());

        @Override
        public void onClick(View v) {
            Toast.makeText(viewnameactivity.this,"Edit button of ID :  selected.",
                    Toast.LENGTH_SHORT).show();

        }
    });

    Button btnDelete = (Button)findViewById(R.id.btndelete);

    btnDelete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(viewnameactivity.this,"Delete button of ID :  selected.",
                    Toast.LENGTH_SHORT).show();             

        }
    });*/


    }
    public void OnClickEdit(View v){


        //TextView strID = (TextView)this.findViewById(R.id.textID);
        //long lngID = Long.parseLong(strID.getText().toString());


        Toast.makeText(viewnameactivity.this,"Edit button of ID : "+ pos +" selected.",
                Toast.LENGTH_SHORT).show();

    }

    public void OnClickDelete(View v){
        TextView strID = (TextView)findViewById(R.id.textID);
        long lngID = Long.parseLong(strID.getText().toString());        
        Toast.makeText(viewnameactivity.this,"Delete button of ID :"+ lngID + "selected.",
                Toast.LENGTH_SHORT).show(); 
    }
}

DatabaseOpenHelper Class :

package com.iwill.Database_add_display;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper 
{
    public static final String KEY_NAME = "NAME";
    public static final String KEY_MAIL = "EMAIL";
    public static final String KEY_NO ="NO";
    public static final String KEY_ID = "ID";
    private static final String DATABASE_NAME = "info.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "user";

    private static String DB_PATH = "/data/data/com.iwill.Database_add_display";   
    private static String DB_NAME = "info.db";

    private static Context context;
    private static SQLiteDatabase db;
    private static final String TAG = "MEDIA";
    public DatabaseHelper(Context context) 
    {
        this.context = context;
        OpenHelper openHelper = new OpenHelper(this.context);
        this.db = openHelper.getWritableDatabase();
        //this.insertStmt = this.db.compileStatement(INSERT);
    }
    public long insert(String uname,String mail,String no)
    {

        ContentValues CV = new ContentValues();
        CV.put(KEY_NAME, uname);
        CV.put(KEY_MAIL , mail);
        CV.put(KEY_NO, no);
        long rawId =  db.insert(TABLE_NAME, null, CV);
        return rawId;
    }
    public void update(long _ID,String updateuname,String updatemail,String updateno)
    {
        Log.i("tag","_ID"+_ID);
        ContentValues cvupdate=new ContentValues();
        cvupdate.put(KEY_NAME,updateuname);
        cvupdate.put(KEY_MAIL, updatemail);
        cvupdate.put(KEY_NO, updateno);
        db.update(TABLE_NAME, cvupdate, "_id"+" = ?",new String[]{String.valueOf(_ID)});
        Log.i("tag", "Item Updated Database Helper");
    }

    public void delete(long _ID)
       {   
           this.db.delete(TABLE_NAME, "_id"+" = ?", new String[]{String.valueOf(_ID)});
           Log.i("tag", "Item deleted");
       }

     public List<userdetails> selectAll(){
         List<userdetails> list = new ArrayList<userdetails>();
         Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "NAME", "EMAIL", "NO"},
                 null, null, null, null, "_id asc");
         if(cursor.moveToFirst()){
             do {
                   userdetails usd= new userdetails();
                   usd.setName(cursor.getString(1));
                   usd.setMail(cursor.getString(2));
                   usd.setNo(cursor.getString(3));
                   usd.setID(cursor.getLong(0));
                   list.add(usd);

             } while (cursor.moveToNext());
         }
         if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
         return list;
     } 

     public void close(){
            db.close();
        } 

     public List<String> selectAllid(){
         List<String> list = new ArrayList<String>();
         Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "NAME"},
                 null, null, null, null, "_id asc");
         if(cursor.moveToFirst()){
             do {
                   //list.add(cursor.getInt(0) + " "+cursor.getString(1));  
                   list.add(cursor.getString(0));
                   Log.i("List 0 (id)....", cursor.getString(0));
                   Log.i("List 1 (URL)....", cursor.getString(1));

             } while (cursor.moveToNext());
         }
         if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
         return list;
     } 

     // TESTING

    private static class OpenHelper extends SQLiteOpenHelper
    {

        public OpenHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            // TODO Auto-generated method stub
            String str = "CREATE TABLE IF NOT EXISTS user(_id INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT,EMAIL TEXT,NO TEXT)";
            db.execSQL(str);            
        }

        private boolean checkDatabase(){
            SQLiteDatabase checkDB = null;
            try{
                String myPath = DB_PATH + DB_NAME;
                checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
            }catch(SQLiteException e){
                //database does't exist yet.
            }

            if(checkDB != null){
                checkDB.close();
            }
            return checkDB != null ? true : false;

        }
        public void createNewDatabase() {
              InputStream assetsDB = null;
              try {
                  assetsDB = context.getAssets().open(DB_NAME);
                  OutputStream dbOut = new FileOutputStream(DB_PATH + DB_NAME);

                  byte[] buffer = new byte[1024];
                  int length;
                  while ((length = assetsDB.read(buffer)) > 0) {
                      dbOut.write(buffer, 0, length);
                  }

                  dbOut.flush();
                  dbOut.close();
                  assetsDB.close();
                  Log.i("New Database created.......", "New database created...");
              } catch (IOException e) {
                  Log.e("Could not create new database...", "Could not create new database...");
                  e.printStackTrace();
              }
       }
        @Override
        public synchronized void close() {
            if(db != null){
                db.close();
            super.close();
            }   
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        {
             //Log.w("Example", "Upgrading database, this will drop tables and recreate.");
             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
             onCreate(db);
        }
    }

}

Am kinda beginner and any help would be really appreciated. (:


回答1:


Try adding this to your adapter:

public class MyAdapter extends BaseAdapter
{
   public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
   ...
   @Override
   public View getView(final int position, View convertView, ViewGroup parent) 
   {
      ...
      myList.put(position,String.valueOf(data.get(position).getID()));     

      return convertView;
   }      
   ...
}

Now in your activity,

public class viewnameactivity extends Activity 
{
   ...
   listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent,View v,int position,long id) {                       
                pos = adapter.getUserArray(position);

                String TVID=MyAdapter.myList.get(position); // this will give you tvid for each listitem
            }
   });
   ...
}


来源:https://stackoverflow.com/questions/9475636/how-to-get-rowid-of-custom-listviews-selected-rows-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!