Я пытаюсь создать пользовательский listview с одним изображением и 3 текстовыми экранами, но я получаю эту ошибку NullPointException в строке «listView.setAdapter (адаптер)»; моего кода. Отлаживая приложение, я мог видеть, что мои produtos List получают все необходимые данные из моей базы данных SQLite, поэтому я не верю, что проблема там отсутствует. Я устанавливаю исправление, потому что это был мой первый тест с таможней. Поэтому я пытался сделать это первым, тогда я реализую все остальное.NullPointerException CustomList ViewAdapter с базовым адаптером Android
`Моя деятельность, которая должна реализовать пользовательские listview--
public class ShowAllProdutosActivity extends ActionBarActivity {
ListView listView;
ArrayList<Produto> produtos;
String[] titleArray;
String[] descriptionArray;
String[] priceArray;
int[] imagensArray;
CustomListViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO: Implement this method
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_procura); /*Fixed*/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
produtos = new ArrayList<>();
listView = (ListView) findViewById(R.id.listaProdutos);
final DatabaseHelper db = new DatabaseHelper(this);
produtos = db.getAllProdutos();
db.closeDB();
if (!produtos.isEmpty()) {
adapter = new CustomListViewAdapter(this,produtos);
listView.setAdapter(adapter);
} else {
Toast.makeText(this, "Nenhum Produto Encontrado", Toast.LENGTH_LONG);
}
}
}`
` CustomListViewAdapter.java--
public class CustomListViewAdapter extends BaseAdapter {
Context context;
protected List<Produto> listProds;
LayoutInflater inflater;
public CustomListViewAdapter(Context context, List<Produto> listProds) {
this.listProds = listProds;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
public int getCount() {
return listProds.size();
}
public Produto getItem(int position) {
return listProds.get(position);
}
public long getItemId(int position) {
return listProds.get(position).getId();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View row = convertView;
if (row == null) {
holder = new ViewHolder();
row = this.inflater.inflate(R.layout.listview_item,
parent, false);
holder.txtName = (TextView) row
.findViewById(R.id.txtViewNomeProduto);
holder.txtDesc = (TextView) row
.findViewById(R.id.txtViewDescricaoProduto);
holder.txtPrice = (TextView) row
.findViewById(R.id.txtViewPrecoProduto);
holder.imgProd = (ImageView) row
.findViewById(R.id.produtoImgView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Produto prod = listProds.get(position);
holder.txtName.setText(prod.getProd_name());
holder.txtDesc.setText(prod.getProd_desc());
holder.txtPrice.setText(prod.getProd_price() + " R$");
holder.imgProd.setImageResource(R.mipmap.ic_launcher);
return convertView;
}
private class ViewHolder {
TextView txtName;
TextView txtDesc;
TextView txtPrice;
ImageView imgProd;
}
Моя раскладка деятельность listview_procura.xml--
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/listaProdutos"
android:layout_alignParentTop="true" />
</RelativeLayout>
My layout layout listview_item.xml--
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/produtoImgView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/txtViewNomeProduto"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/produtoImgView"
android:layout_toEndOf="@+id/produtoImgView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/txtViewDescricaoProduto"
android:layout_toRightOf="@+id/produtoImgView"
android:layout_below="@+id/txtViewNomeProduto"
android:layout_above="@+id/txtViewPrecoProduto"
android:layout_toLeftOf="@+id/txtViewPrecoProduto"
android:layout_toStartOf="@+id/txtViewPrecoProduto" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/txtViewPrecoProduto"
android:layout_alignBottom="@+id/produtoImgView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
И журнал Я getting--
04-12 20:36:30.533 28463-28463/com.paum.pechinchamercado E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.paum.pechinchamercado, PID: 28463
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paum.pechinchamercado/com.paum.pechinchamercado.activities.ShowAllProdutosActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.paum.pechinchamercado.activities.ShowAllProdutosActivity.onCreate(ShowAllProdutosActivity.java:50)
at android.app.Activity.performCreate(Activity.java:5426)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
`
добавить обработчик исключений в ваш метод getView, чтобы поймать любые исключения там, поставить точку останова на (исключение e) и посмотреть, произошло ли исключение. – faljbour
Существует проблема с неправильным выбором макета. – Piyush
Piyush Gupta, вы были правы, я уже исправил, но теперь ничего не представляет. fljabour Я установил try catch и отлаживал его с точкой прерывания int catch (исключение), хотя он не прошел через него во время работы –