Как передать строку в OnItemClick ListView? - PullRequest
2 голосов
/ 03 мая 2011

Как получить строку из моего курсора в мой вызов putExtra в onItemClick для ListView? Мне нужно взять строку из моего столбца БД с именем 'gotoURL' в:

 i.putExtra("Url", ???). 

... моего onItemНажмите в разделе Активность. Пример кода будет полезен для обучения. Thnx !!

Моя активность:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.list_view2);

    final ListView lv = getListView();

    activityTitle = (TextView) findViewById(R.id.titleBarTitle);
    activityTitle.setText("ADVISORY CIRCULATORS");

    displayResultList();

    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {
        // @Override
        public void onItemClick(AdapterView<?> a, View v, int position,long id) 
        {
            Toast.makeText(List_AC.this, "Clicked!", Toast.LENGTH_LONG).show();
            Object o = lv.getItemAtPosition(position);
            Adapter_AC fullObject = (Adapter_AC)o;
            Intent i = new Intent(List_AC.this, DocView.class);
            //i.putExtra("url", Adapter_AC.gotoURL);
            startActivity(i);
        }
    });
}

private void displayResultList() {

    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED)) {
        extStorageDirectory = Environment.getExternalStorageDirectory()
                .toString();

        File dbfile = new File(extStorageDirectory
                + "/XXX/XXX/dB/XXX.db");

        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
                null);

        Cursor databaseCursor = db.rawQuery(
                "SELECT * FROM AC_list ORDER BY `label` ASC", null);

        Adapter_AC databaseListAdapter = new Adapter_AC(this,
                R.layout.list_item, databaseCursor, new String[] { "label",
                        "title", "description" }, new int[] { R.id.label,
                        R.id.listTitle, R.id.caption });

        databaseListAdapter.notifyDataSetChanged();
        this.setListAdapter(databaseListAdapter);

    } else if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_UNMOUNTED)) {
        Log.i("tag", "SDCard is NOT writable/mounted");
        Alerts.sdCardMissing(this);
    }
}
}

И мой адаптер:

public class Adapter_AC extends SimpleCursorAdapter {

private Cursor dataCursor;
private LayoutInflater mInflater;

public Adapter_AC(Context context, int layout, Cursor dataCursor,
        String[] from, int[] to) {
    super(context, layout, dataCursor, from, to);
    this.dataCursor = dataCursor;
    mInflater = LayoutInflater.from(context);
}

public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item, null);

        holder = new ViewHolder();
        holder.text1 = (TextView) convertView.findViewById(R.id.label);
        holder.text2 = (TextView) convertView.findViewById(R.id.listTitle);
        holder.text3 = (TextView) convertView.findViewById(R.id.caption);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    dataCursor.moveToPosition(position);

    int label_index = dataCursor.getColumnIndex("label");
    String label = dataCursor.getString(label_index);

    int title_index = dataCursor.getColumnIndex("title");
    String title = dataCursor.getString(title_index);

    int description_index = dataCursor.getColumnIndex("description");
    String description = dataCursor.getString(description_index);

    int goto_index = dataCursor.getColumnIndex("gotoURL");
    String gotoURL = dataCursor.getString(goto_index);

    holder.text1.setText(label);
    holder.text2.setText(title);
    holder.text3.setText(description);

    return convertView;
}

static class ViewHolder {
    TextView text1;
    TextView text2;
    TextView text3;
}
} 

Ответы [ 2 ]

2 голосов
/ 03 мая 2011

Вы можете использовать метод CursorAdapter getItem(), чтобы получить курсор, указывающий на текущий идентификатор. Вот так:

...
Cursor cursor = adapter.getItem(id);
i.putExtra("url", cursor.getString(cursor.getColumnIndex("gotoURL")));
...

Обратите внимание, что я подозреваю, что вам нужно будет включить этот столбец в вашу проекцию, например:

    Adapter_AC databaseListAdapter = new Adapter_AC(this,
            R.layout.list_item, databaseCursor, new String[] { "label",
                    "title", "description", "gotoURL" }, new int[] { R.id.label,
                    R.id.listTitle, R.id.caption, R.id.dummy });

И создайте для него фиктивное (View.GONE) невидимое поле, чтобы данные перемещались в курсоре.

1 голос
/ 28 декабря 2011

Вы можете попробовать использовать поле 'Tag' в ListView: установите его на правильное значение при создании и чтении, чтобы получить правильное значение при нажатии ...

...