Alertdialog gridview error - java

I need to show gridview in alert dialog. But i stuck with the error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
My code...
listView_prev.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, int arg2, long arg3) {
//listview click event handling
TextView id = (TextView) arg1.findViewById(R.id.textView17);
final int id_To_Search = Integer.valueOf(id.getText().toString());
Cursor item=mydb.singlecons(id_To_Search);
Cursor att=mydb.attrs(id_To_Search);
Cursor picloc=mydb.singleconspic(id_To_Search);
att.moveToFirst();
List<String> list = new ArrayList<>();
// Log.d("temp",att.getColumnName(1));
while (!att.isAfterLast())
{
int l=att.getColumnCount();
Log.d("length", String.valueOf(l));
for(int i=2;i<l;i++){
Log.d("for","for");
if(att.getString(i)!=null){
String b= att.getColumnName(i)+" "+att.getString(i);
list.add(b);
Log.d("att",b);
}
}
Log.d("while","while");
att.moveToNext();
}
att.close();
Log.d("list", String.valueOf(list));
picloc.moveToFirst();
FilePathStrings = new String[picloc.getCount()];
int i=0;
while (!picloc.isAfterLast()){
Log.d("picloc",picloc.getString(2));
FilePathStrings[i]=picloc.getString(2);
i++;
picloc.moveToNext();
}
item.moveToFirst();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Consultation.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
TextView con=(TextView)dialogView.findViewById(R.id.textView29);
con.setText("Consultation on "+item.getString(4));
TextView des=(TextView)dialogView.findViewById(R.id.textView28);
des.setText(item.getString(2));
TextView pre=(TextView)dialogView.findViewById(R.id.textView31);
pre.setText(item.getString(3));
TextView fee=(TextView)dialogView.findViewById(R.id.textView32);
fee.setText(item.getString(5));
adapter1 = new GridViewAdapter(FilePathStrings,getApplicationContext());
grid.setAdapter(adapter1);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Gridviewadapter.java
class GridViewAdapter extends BaseAdapter {
private String[] filepath;
private static LayoutInflater inflater = null;
GridViewAdapter(String[] fpath,Context context) {
filepath = fpath;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return filepath.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.gridview_item, null);
ImageView image = (ImageView) vi.findViewById(R.id.image);
Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);
image.setImageBitmap(bmp);
return vi;
}
}
Alertlabeleditor.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:paddingBottom="20dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView29"
android:layout_weight="1"
android:gravity="center"
android:textSize="24sp"
android:layout_marginBottom="10dp"
android:textStyle="normal|bold" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView27"
android:layout_weight="2" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView28"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Prescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView30"
android:layout_weight="2" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView31"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="fee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView33"
android:layout_weight="2" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView32"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
How can i resolve this issue.? Where is the error occurring in my code? I know null pointer error due to accessing values from where there is no value, but i cant figure it out where this is occurring and how can i resolve it. How can i solve this issue.?

Your GridView reference is null
make sure you have initialized your GridView reference
example
grid = (GridView) dialogView.findViewById(R.id.gridview);
Replace your onclickListner with this
listView_prev.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, int arg2, long arg3) {
//listview click event handling
TextView id = (TextView) arg1.findViewById(R.id.textView17);
final int id_To_Search = Integer.valueOf(id.getText().toString());
Cursor item=mydb.singlecons(id_To_Search);
Cursor att=mydb.attrs(id_To_Search);
Cursor picloc=mydb.singleconspic(id_To_Search);
att.moveToFirst();
List<String> list = new ArrayList<>();
// Log.d("temp",att.getColumnName(1));
while (!att.isAfterLast())
{
int l=att.getColumnCount();
Log.d("length", String.valueOf(l));
for(int i=2;i<l;i++){
Log.d("for","for");
if(att.getString(i)!=null){
String b= att.getColumnName(i)+" "+att.getString(i);
list.add(b);
Log.d("att",b);
}
}
Log.d("while","while");
att.moveToNext();
}
att.close();
Log.d("list", String.valueOf(list));
picloc.moveToFirst();
FilePathStrings = new String[picloc.getCount()];
int i=0;
while (!picloc.isAfterLast()){
Log.d("picloc",picloc.getString(2));
FilePathStrings[i]=picloc.getString(2);
i++;
picloc.moveToNext();
}
item.moveToFirst();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Consultation.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
TextView con=(TextView)dialogView.findViewById(R.id.textView29);
con.setText("Consultation on "+item.getString(4));
TextView des=(TextView)dialogView.findViewById(R.id.textView28);
des.setText(item.getString(2));
TextView pre=(TextView)dialogView.findViewById(R.id.textView31);
pre.setText(item.getString(3));
TextView fee=(TextView)dialogView.findViewById(R.id.textView32);
fee.setText(item.getString(5));
adapter1 = new GridViewAdapter(FilePathStrings,getApplicationContext());
grid = (GridView) dialogView.findViewById(R.id.gridview);
grid.setAdapter(adapter1);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Related

Why doesn't the onListItemClick function in the ListFragment fire when I add a button or edittext to the item?

I render each element of my ListFragment with two buttons and edittext, but in this case, onListItemClick does not work for me. And as soon as you hide the buttons and edittext in the adapter, everything immediately starts working, I think that this is some kind of conflict between the fields, but I don’t know how to fix it. I will be grateful for any help.
My adapter:
public class ProductAdapter extends ArrayAdapter<ProductsModel> {
private LayoutInflater inflater;
private int layout;
private ArrayList<ProductsModel> productsList;
private String nameFragment;
private Parsers parser;
public ProductAdapter(Context mContext, int resource, ArrayList<ProductsModel> products,
String nameFragment) {
super(mContext, resource, products);
this.productsList = products;
this.layout = resource;
this.inflater = LayoutInflater.from(mContext);
this.parser = new Parsers(mContext);
this.nameFragment = nameFragment;
}
public View getView(int position, View convertView, ViewGroup parent){
final ViewHolder viewHolder;
if(convertView==null){
convertView = inflater.inflate(this.layout, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
final ProductsModel products = productsList.get(position);
PricesModel price = parser.PriceParser((int) products.getId());
viewHolder.imageProduct.setImageResource(R.drawable.img);
viewHolder.imageProduct.setScaleType(ImageView.ScaleType.FIT_START);
viewHolder.nameProduct.setText(products.getName());
viewHolder.categoryProduct.setText("Group");
viewHolder.priceValueProduct.setText("Cost: "+price.getPriceValue());
viewHolder.countProduct.setText("0");
if(nameFragment.equals("ListProduct")){
viewHolder.priceValueProduct.setVisibility(View.GONE);
viewHolder.countProduct.setVisibility(View.GONE);
viewHolder.buttonPlus.setVisibility(View.GONE);
viewHolder.buttonMinus.setVisibility(View.GONE);
}
return convertView;
}
private class ViewHolder {
final ImageView imageProduct;
final TextView nameProduct, categoryProduct, priceValueProduct;
final EditText countProduct;
final Button buttonPlus, buttonMinus;
ViewHolder(View view){
imageProduct = view.findViewById(R.id.imageProduct);
nameProduct = view.findViewById(R.id.nameProduct);
categoryProduct = view.findViewById(R.id.categoryProduct);
priceValueProduct = view.findViewById(R.id.priceValueProduct);
countProduct = view.findViewById(R.id.countProduct);
buttonPlus = view.findViewById(R.id.buttonPlus);
buttonMinus = view.findViewById(R.id.buttonMinus);
}
}
}
My fragment:
public class ListProducts extends ListFragment {
private ProductAdapter mProductAdapter;
private Parsers parser;
private Context mContext;
private View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_products, container, false);
mContext = getContext();
parser = new Parsers(mContext);
ArrayList<ProductsModel> productsList = parser.ProductsParser();
ArrayList<ProductsModel> improveProductsList = new ArrayList<>();
for(int i = 0; i < productsList.size(); i++){
improveProductsList.add(productsList.get(i));
}
EditText searchProduct = (EditText) view.findViewById(R.id.searchEditText);
searchProduct.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String nameProduct = s.toString();
if(count != 0) {
improveProductsList.clear();
for (int i = 0; i < productsList.size(); i++) {
if (productsList.get(i).getName().toLowerCase().indexOf(nameProduct.toLowerCase()) != -1) {
improveProductsList.add(productsList.get(i));
}
}
}else{
for(int i = 0; i < productsList.size(); i++){
improveProductsList.add(productsList.get(i));
}
}
}
#Override
public void afterTextChanged(Editable s) {}
});
try {
int idCompany = getArguments().getInt("idCompany",0);
int idStore = getArguments().getInt("idStore", 0);
mProductAdapter = new ProductAdapter(mContext, R.layout.simple_list_item_product, improveProductsList, "NewOrder");
}catch (NullPointerException e){
mProductAdapter = new ProductAdapter(mContext, R.layout.simple_list_item_product, improveProductsList, "ListProduct");
}
setListAdapter(mProductAdapter);
return view;
}
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.d("TAG", ""+position);
}
}
XML simple_list_item_product:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/imageProduct"
android:layout_width="100sp"
android:layout_height="100sp"
android:scaleType="fitStart"/>
<LinearLayout
android:id="#+id/linearLayoutInfoAndButtonProduct"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="5sp">
<TextView
android:id="#+id/nameProduct"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textStyle="bold"
android:textColor="#color/black"
android:text="Name prod"/>
<TextView
android:id="#+id/categoryProduct"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:textColor="#color/black"
android:text="Category prod"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf = "#+id/nameProduct" />
<TextView
android:id="#+id/priceValueProduct"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:textColor="#color/black"
android:text="Cost prod"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf = "#+id/nameCompany" />
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/buttonMinus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"/>
<EditText
android:id="#+id/countProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/buttonPlus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
XML fragment_list_products:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_list_products"
tools:context="com.example.rbsoftsalesmobile.ui.productsscreen.ListProducts">
<TextView
android:gravity="center_horizontal"
android:id="#+id/game_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textAllCaps="false"
android:textAppearance="#style/TextAppearance.AppCompat.Headline"
android:textSize="22sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed"
android:text="List prod"/>
<EditText
android:id="#+id/searchEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search"
app:layout_constraintTop_toBottomOf="#+id/game_title"
android:layout_margin="5sp"/>
<ListView
android:id="#android:id/list"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchEditText" />
</androidx.constraintlayout.widget.ConstraintLayout>
I solved my problem with setFocusable(false), for every element that can intercept input from other components like Button, EditText, CheckBox and others.
if(nameFragment.equals("ListProduct")){
viewHolder.priceValueProduct.setVisibility(View.GONE);
viewHolder.countProduct.setVisibility(View.GONE);
viewHolder.buttonPlus.setVisibility(View.GONE);
viewHolder.buttonMinus.setVisibility(View.GONE);
}
viewHolder.countProduct.setFocusable(false);
viewHolder.buttonPlus.setFocusable(false);
viewHolder.buttonMinus.setFocusable(false);
return convertView;
}

Native Ad Admob to Custom List Adapter in Android

I'm struggling to find a way to add a native ad within my app on Android.
MainActivity Class:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
final String[] numbers = {"one","two", "", "three", "four", "five","six","seven" "eight","nine", "ten" "eleven","twelve", "thirteen"};
Integer[] images = {0,1,2,3,4,5,6,7,8,9,10,11,12,13
};
CustomListAdapter adapter=new CustomListAdapter(this.getActivity(), mobileArray, images);
NativeExpressAdView adView = (NativeExpressAdView) rootView.findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder().build();
adView.loadAd(request);
list=(ListView) rootView.findViewById(R.id.list_view);
list.setAdapter(adapter);
CustomListAdapter Class:
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] numbers;
private final Integer[] imgid;
public CustomListAdapter(Activity context, String[] numbers, Integer[] imgid) {
super(context, R.layout.listv, itemname);
// TODO Auto-generated constructor stub
this.context=context;
this.numbers=numbers;
this.imgid=imgid;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.listv, null,true);
NativeExpressAdView adView = (NativeExpressAdView) rowView.findViewById(R.id.adView);
TextView txtTitle = (TextView) rowView.findViewById(R.id.number);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgid);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(numbers[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Number: "numbers[position]);
return rowView;
};
}
I want to add the native add within a particular index in array, ideally where it shows "". I'm trying to add the adView into the adapter but unsure how to do this.
Edit:
listv layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgid"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4CBE99" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.ads.NativeExpressAdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_gravity="center"
ads:adSize="345x80"
ads:adUnitId="ca-app-pub-3940256099942544/2793859312"></com.google.android.gms.ads.NativeExpressAdView>
You can try like this,
public class CustomListAdapter extends ArrayAdapter<String> {
private NativeExpressAdView adView;
private NativeExpressAdView getAddView() {
if (adView != null) {
return adView;
}
adView = new NativeExpressAdView(context);
adView.setAdUnitId("[your unit id]");
adView.setAdSize(new AdSize(AdSize.FULL_WIDTH, 80));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
adView.setLayoutParams(layoutParams);
AdRequest request = new AdRequest.Builder().build();
adView.loadAd(request);
return adView;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.layout_add, null, true);
// NativeExpressAdView adView = (NativeExpressAdView) rowView.findViewById(R.id.adView);
LinearLayout linearLayout = (LinearLayout) rowView.findViewById(R.id.addView);
linearLayout.removeAllViews();
TextView txtTitle = (TextView) rowView.findViewById(R.id.number);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgid);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(numbers[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Number: " + numbers[position]);
if (position == 2) {
linearLayout.addView(getAddView());
linearLayout.setVisibility(View.VISIBLE);
} else {
linearLayout.removeAllViews();
linearLayout.setVisibility(View.GONE);
}
return rowView;
}
;
}
Layour xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgid"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#4CBE99"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/addView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"></LinearLayout>
</LinearLayout>

onClickListener on a button that is added through a layout inflator

Here is my code so far based on various answers to related questions on SO.
In my Activity
GridView gv = (GridView) findViewById(R.id.gridView1);
MyCustomAdapter mAdapter = new MyCustomAdapter();
mAdapter.addItem("Action1");
mAdapter.addItem("Action2");
mAdapter.addItem("Action3");
gv.setAdapter(mAdapter);
My Adapter
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NumericViewHolder holder = new NumericViewHolder();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.horizontalnumberpicker, null);
holder.textView = (TextView)convertView.findViewById(R.id.txtNPTitle);
holder.minus = (Button)convertView.findViewById(R.id.btnMinus);
holder.plus = (Button)convertView.findViewById(R.id.btnPlus);
holder.value = (TextView)convertView.findViewById(R.id.txtNPValue);
holder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString());
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
if (value > 0) {
value = value - 1;
tv.setText(Integer.toString(value));
}
}
});
holder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString()); <--Error is here
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
value = value + 1;
tv.setText(Integer.toString(value));
}
});
convertView.setTag(holder);
} else {
holder = (NumericViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
XML - Main_Activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rlAddProduct"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/btnSaveProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text="#string/Save" />
<TextView
android:id="#+id/lblSelectCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnSaveProduct"
android:layout_alignBottom="#+id/btnSaveProduct"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:text="#string/selectCategory" />
<Spinner
android:id="#+id/spCategory"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignBottom="#+id/lblSelectCategory"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp"
android:layout_toEndOf="#+id/lblSelectCategory"
android:layout_toRightOf="#+id/lblSelectCategory" />
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lblSelectCategory"
android:layout_below="#+id/btnSaveProduct"
android:layout_marginTop="14dp"
android:numColumns="auto_fit" >
</GridView>
</RelativeLayout>
XML - Horizontalnumberpicker
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtNPTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="EnterTextHere"
android:layout_marginTop="5dp" />
<Button
android:id="#+id/btnPlus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/txtNPValue"
android:layout_alignBottom="#+id/txtNPValue"
android:layout_toRightOf="#+id/txtNPValue"
android:text="+" />
<TextView
android:id="#+id/txtNPValue"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/btnMinus"
android:layout_toRightOf="#+id/btnMinus"
android:gravity="center"
android:text="0"
android:textAppearance="#style/AppBaseTheme"
android:textSize="20dp" />
<Button
android:id="#+id/btnMinus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtNPTitle"
android:layout_marginTop="2dp"
android:text="-" />
</RelativeLayout>
The requirement is that when I press the plus button, I need to increment the value in the corresponding txtNPValue. Similarly with the minus button, I need to decrement the value in the txtNPValue.
The error is
01-31 22:40:10.854: E/AndroidRuntime(32198): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
Also I do not know if this is the right way to program such a requirement and would like some pointers.
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
this will return null pointer exception, as the view that u r getting is of the button or the clicked item..
Use this :-
RelativeLayout rlLayout = (RelativeLayout) v.getParent();
TextView tv = (TextView) rlLayout.findViewById(R.id.txtNPValue);
please remove:
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
from onClick to resolve nullpointerException

setOnItemClickListener is not working for ArrayAdapter<ImageView>

When i try to click on items in the list it doesnt go through the onItemClick method.
GridViewAdapter.java
public class GridViewAdapter extends ArrayAdapter<ImageItem>{
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList<ImageItem>();
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
MainActivity.java
public class MainActivity extends Activity {
private GridView gridView;
private GridViewAdapter customGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView);
customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(customGridAdapter);
Log.d("yyoyoyoyo", "jhgvkbkhbjkhbj");
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, position + "#Selected",
Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<ImageItem>();
// retrieve String drawable array
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
row_grid.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="vertical"
android:padding="5dp"
android:clickable="true"
android:background="#drawable/grid_color_selector"
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
>
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</ImageView>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="12sp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</TextView>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:clickable="false"
android:descendantFocusability="blocksDescendants"
tools:context=".MainActivity" >
<GridView
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:drawSelectorOnTop="true"
android:stretchMode="columnWidth"
android:descendantFocusability="blocksDescendants"
>
</GridView>
</RelativeLayout>
I have tried most of the solutions regarding this topic on StackOverFlow none of them worked for me. This app lists all the images but when you click onItemClick isnt fired. Probably there is something wrong with my code.
Thank you!!
Remove android:clickable="true" in row_grid.xml. and add android:clickable="true" in activity_main.xml
Also remove the
android:focusable="false"
android:focusableInTouchMode="false"
As row_grid.xml is clickable, it blocks the grid's onclick listener from responding.

How to set an String Array to an Array Adapter in android List view with check box?

I am getting a string[] Array and storing it in an String array [variable mystrings],Now i want this array to display it in a list view with check box .
ec_checkbox_number.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="26dp"
android:text="number" />
<TextView
android:id="#+id/checkboxtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox"
android:layout_alignBottom="#+id/checkBox"
android:layout_alignParentLeft="true"
android:layout_marginLeft="107dp"
android:text="TextView" />
</RelativeLayout>
ec_number_selection.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/meetingprofilename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:text="Profile Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/meetingprofilename"
android:layout_alignBottom="#+id/meetingprofilename"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/meetingprofilename"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/cancelnumberbutton"
android:layout_width="158dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/editText2"
android:text="Cancel" />
<Button
android:id="#+id/donenumberbutton"
android:layout_width="158dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/cancelnumberbutton"
android:text="Done" />
<ListView
android:id="#+id/numberselectionlistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/cancelnumberbutton"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1" >
</ListView>
</RelativeLayout>
CheckBoxData.java
public class CheckBoxData {
private String[] number;
public String[] getNumber() {
return number;
}
public void setNumber(String[] number) {
this.number = number;
}
}
MyConferenceNumber.java
public class EcConferenceNumber extends Activity{
ListView checkBoxNumberListView;
ConferenceAdapter adapter;
Button doneBtn,cancelBtn;
EditText profileName;
MyCustomAdapter dataAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ec_number_selection);
adapter = new ConferenceAdapter(this);
checkBoxNumberListView = (ListView) findViewById(R.id.numberselectionlistView);
doneBtn=(Button) findViewById(R.id.donenumberbutton);
cancelBtn=(Button) findViewById(R.id.cancelnumberbutton);
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
List<String> strings =
new ArrayList<String>(Arrays.asList(myStrings));
System.out.println(""+strings);
dataAdapter = new MyCustomAdapter(this,
R.layout.ec_checkbox_number, strings);
checkBoxNumberListView.setAdapter(dataAdapter);
checkBoxNumberListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
CheckBoxData country = (CheckBoxData) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Clicked on Row: " + country.getNumber(),
Toast.LENGTH_LONG).show();
}
});
}
class MyCustomAdapter extends ArrayAdapter<String>{
private List<String> strings;
public MyCustomAdapter(Context context, int textViewResourceId, List<String> strings) {
super(context, textViewResourceId,strings);
this.strings=new ArrayList<String>();
this.strings.addAll(this.strings);
// TODO Auto-generated constructor stub
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.ec_checkbox_number, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.checkboxtextView);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
CheckBoxData country = (CheckBoxData) cb.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
}
The output what i am getting is..
For example:If String[] a={002,111,122} i want to display it in a listview with checkbox and i have to get the selected CheckBox text.But my output is displying like this
number
number
number
number
But i want the output like this ,
123
112
123
Since ,I am new to android i did not know how to set the array to output view.Any answers will be helpfull.
Paste your full xml code. There is no button in xml and some properties are missing.

Categories

Resources