0

Я пытаюсь получить данные из SQLite в ListView, поэтому я последовал примеру в ответ на этот адрес Make listview from SQLite databaseAndroid: ListView нагрузки дает Исключение нулевого указателя

CustomCursorAdapter будет как то

public class CustomCursorAdapter extends SimpleCursorAdapter { 
    private int layout; 
    private LayoutInflater inflater; 
    private Context context; 

    public CustomCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) { 
     super(context, layout, c, from, to); 
     this.layout = layout; 
     this.context = context; 
     inflater = LayoutInflater.from(context); 

    } 


    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 

     View v = inflater.inflate(R.layout.topics, parent, false); 

     return v; 
    } 

    @Override 
    public void bindView(View v, Context context, Cursor c) { 
       //1 is the column where you're getting your data from 
     String name = c.getString(1); 
     /** 
     * Next set the name of the entry. 
     */ 
     TextView name_text = (TextView) v.findViewById(R.id.listLabel); 
     if (name_text != null) { 
      name_text.setText(name); 
     } 
    } 
} 

но OnCreate у меня есть этот код

ListView listView = (ListView)findViewById(R.layout.topics); 
    connectToDB(); 
    from = new String[] { "topicTitle" }; 
    to = new int[] { R.id.listLabel }; 

    CustomCursorAdapter adapter = new CustomCursorAdapter(this, 
      R.layout.topics, cursor, from, to); 
    listView.setAdapter(adapter); 

с XML следующим

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="5dp" > 

    <ImageView 
     android:id="@+id/listLogo" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:layout_marginLeft="5dp" 
     android:layout_marginRight="20dp" 
     android:layout_marginTop="5dp" 
     > 
    </ImageView> 

    <TextView 
     android:id="@+id/listLabel" 
     android:layout_width="250dp" 
     android:layout_height="wrap_content" 
     android:text="@+id/label" 
     android:textSize="15sp" > 
    </TextView> 

</LinearLayout> 

проблема есть .. listView - Null !! .. что я не знаю почему !!

+0

опубликовать ошибку LogCat. – rajeshwaran

+0

Установили ли вы ContentView перед получением справки по списку – Pragnani

+0

И где ListView в вашем макете? – Egor

ответ

2

Вы ссылаетесь на свои макеты. Вы должны иметь listview, определенный в xml с идентификатором. В вашей деятельности onCreate() после setCOntentView (R.layout.topics), плагирует идентификатор списка и устанавливает адаптер в ваш список.

В вашем XML сказать topics.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:background="#0095FF"> 
    <ListView android:id="@+id/list" 
    android:layout_width="fill_parent" 
    android:layout_height="100dp" 
    android:id="@+id/lv"> 
    </ListView> 
    // other ui elements 
</LinearLayout> 

Тогда в вашей деятельности OnCreate()

setContentview(R.layout.topics); 
    ListView listView = (ListView)findViewById(R.id.lv); 
    connectToDB(); 
    from = new String[] { "topicTitle" }; 
    to = new int[] { R.id.listLabel }; 


    CustomCursorAdapter adapter = new CustomCursorAdapter(this, 
     R.layout.topics, cursor, from, to); 
    listView.setAdapter(adapter); 

Из обсуждения в чате

EDIT:

Определение основной. xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:background="#0095FF"> 

<ListView android:id="@+id/list" 
android:layout_width="fill_parent" 
android:layout_height="0dip" 
android:focusableInTouchMode="false" 
android:listSelector="@android:color/transparent" 
android:layout_weight="2" 
android:headerDividersEnabled="false" 
android:footerDividersEnabled="false" 
android:dividerHeight="8dp" 
android:divider="#000000" 
android:cacheColorHint="#000000" 
android:drawSelectorOnTop="false"> 
</ListView> 
</LinearLayout> 

В вашем activivity

public class MainActivity extends Activity { 

ListView lv; 
CustomCursorAdapter cus; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    lv = (ListView) findViewById(R.id.list); 
    cus= new CustomCursorAdapter(parameters); 
    lv.setAdapter(cus); 

} 
} 

Определить customCursor адаптер надуть пользовательский макет. Установите изображение для просмотра изображения и текста для текстового просмотра.

+0

ваше решение дает мне ошибку 04-09 08: 24: 23.687: E/AndroidRuntime (26971): FATAL EXCEPTION: main 04-09 08: 24: 23.687: E/AndroidRuntime (26971): java.lang.RuntimeException: Не удалось запустить Activity ComponentInfo {com.thedarkdimension.StrangeInfo/com.thedarkdimension.StrangeInfo.Topics}: java.lang.RuntimeException: двоичная строка XML-файла # 9: вы должны указать атрибут layout_height. –

+0

@MohamedEmadHegab udated мой ответ. При копировании кода xml я пропустил высоту списка. добавьте android: layout_height = "100dp" в список. Упоминайте высоту в dp или fill_parent. – Raghunandan

+0

@MohamedEmadHegab попробуйте отредактировать. – Raghunandan

0

Try редактировать XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:padding="5dp" 
android:id="@+id/main" 
> 

<ImageView 
    android:id="@+id/listLogo" 
    android:layout_width="50dp" 
    android:layout_height="50dp" 
    android:layout_marginLeft="5dp" 
    android:layout_marginRight="20dp" 
    android:layout_marginTop="5dp" 
    > 
</ImageView> 

<TextView 
    android:id="@+id/listLabel" 
    android:layout_width="250dp" 
    android:layout_height="wrap_content" 
    android:text="@+id/label" 
    android:textSize="15sp" > 
</TextView> 

<ListView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/topics" 
     ></ListView> 

</LinearLayout> 

В OnCreate активность

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    ListView listView = (ListView)findViewById(R.layout.topics); 
    connectToDB(); 
    from = new String[] { "topicTitle" }; 
    to = new int[] { R.id.listLabel }; 

    CustomCursorAdapter adapter = new CustomCursorAdapter(this, 
      R.layout.topics, cursor, from, to); 
    listView.setAdapter(adapter); 
} 
+0

ваше решение дает мне ошибку в setContentView 04-09 08: 24: 23.687: E/AndroidRuntime (26971): FATAL EXCEPTION: main 04-09 08: 24: 23.687: E/AndroidRuntime (26971): java.lang.RuntimeException : Не удалось запустить Activity ComponentInfo {com.thedarkdimension.StrangeInfo/com.thedarkdimension.StrangeInfo. Topics}: java.lang.RuntimeException: двоичная строка XML-файла # 9: вы должны указать атрибут layout_height. - –

+0

@MohamedEmadHegab Я обновил свой ответ. Не забывайте о ID LinearLayout. – jimpanzer

+0

Я думаю, setContentView (R.layout.main); будет setContentView (R.layout.topics); также –

Смежные вопросы