Android listview адаптер показать текст из sqlite - PullRequest
0 голосов
/ 03 октября 2011

Мне нужна небольшая помощь с моим настраиваемым адаптером представления списка. Я использую пример адаптера из vogella.de , но мне нужно найти способ, как установить текст и изображение из базы данных sqlite. Вот код адаптера, который я использую:

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyArrayAdapter extends ArrayAdapter<String> {
    private final Activity context;
    private final String[] names;
    Cursor cursor;

    public MyArrayAdapter(Activity context, String[] names) {
        super(context, R.layout.main_listview, names);
        this.context = context;
        this.names = names;
    }

    // static to save the reference to the outer class and to avoid access to
    // any members of the containing class
    static class ViewHolder {
        public ImageView imageView;
        public TextView textView,textView2;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // ViewHolder will buffer the assess to the individual fields of the row
        // layout

        ViewHolder holder;
        // Recycle existing view if passed as parameter
        // This will save memory and time on Android
        // This only works if the base layout for all classes are the same
        View rowView = convertView;
        if (rowView == null) {

            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.main_listview, null, true);

            holder = new ViewHolder();
            holder.textView = (TextView) rowView.findViewById(R.id.main_name);
            holder.textView2 = (TextView) rowView.findViewById(R.id.main_info);
            holder.imageView = (ImageView) rowView.findViewById(R.id.main_img);
            rowView.setTag(holder);

        } else {
            holder = (ViewHolder) rowView.getTag();
        }
        final Bitmap b = BitmapFactory.decodeFile("/sdcard/52dde26940e0d3081f6a086d4b54cd1c.jpg", null);

        holder.textView.setText("");
        holder.textView2.setText("");
        holder.imageView.setImageBitmap(b);


        return rowView;
    }

    public String[] getNames() {
        return names;
    }
}

И я пытаюсь установить текст в текстовое представление так:

 String sql = "SELECT title FROM collections";
        Cursor cursorTitle = userDbHelper.executeSQLQuery(sql);
        if(cursorTitle.getCount()==0){
            Log.i("Cursor Null","CURSOR TITLE NULL");
        } else if(cursorTitle.getCount()>0){
            cursorTitle.moveToFirst();
            String text = cursorTitle.getString(cursorTitle.getColumnIndex("title"));
            Log.i("title text","title text : "+text);
            String[] names = new String[] { text };
            listView.setAdapter(new MyArrayAdapter(this, names));
 }

, но когда я запускаю этот код, я ничего не получаю в списке просмотра.

Так может ли кто-нибудь подсказать мне, как я могу установить текст и изображение в режиме просмотра изображений и текста в своей деятельности с помощью этого адаптера.

Большое спасибо!

Ответы [ 3 ]

0 голосов
/ 03 октября 2011

Где вы использовали массив String в адаптере? я думаю, вы установили значение NULL в обоих текстовых представлениях. Вам нужно использовать его как holder.textview.setText (names [position]) в вашем адаптере. И второе, вы должны использовать цикл for для создания массива строк из курсора. Похоже, вы всегда получите только первый результат ваших данных курсора.

0 голосов
/ 03 октября 2011

Попробуйте сделать что-то вроде этого:

MyAddapterClass:

    private final Activity context;
    private final String[] names;
    private final Bitmap image;
    private final String text;
    private final String text2;
    Cursor cursor;

    public MyArrayAdapter(Activity context, String[] names, Bitmap image, String text, String text2) {
        super(context, R.layout.main_listview, names);
        this.context = context;
        this.names = names;
        this.image = image;
        this.text = text;
        this.text2 = text2;
    }

и установите image, text и text2 для своих владельцев:

    holder.textView.setText(text);
    holder.textView2.setText(text2);
    holder.imageView.setImageBitmap(image);

и инициализируйте его в своей Деятельности. Вот и все.

Надеюсь, это поможет!

0 голосов
/ 03 октября 2011

Проверьте это

String text = cursorTitle.getString(cursorTitle.getColumnIndex("title"));
Log.i("title text","title text : "+text);
String[] names = new String[] { text };

Каков результат «текста» в LogCat? Любое значение хранится в массиве 'names'?

...