NullPointerException on trying to save SparceBooleanArray - java

Here's the code of my baseadapter which shows contacts' name, phone number and checkboxes alongside them.
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
int mPos;
MyAdapter()
{
if (mCheckStates==null){
mCheckStates = new SparseBooleanArray(name1.size());
}else {
mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");
}
mInflater = (LayoutInflater) ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
public void setPosition(int p){
mPos = p;
}
public int getPosition(){
return mPos;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
setPosition(position);
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
Activity code:
#Override
public void onDestroy(){
bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
//adapter is the MyAdapter object created in parent class
super.onDestroy();
}
Note that I'm using bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates)); and mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");, to store and retrieve the SparseBooleanArray on activity being destroyed and recreated. The onDestroy() method is of the parent class, which is an activity. I haven't pasted that, because I thought it was irrelevant. Please ask if it's needed.
I'm also using a SparseBooleanArrayParcelable class that helps me mCheckStates on destruction, and retrieve on creation.
According to the logs, the NullPointerException occurs within onDestroy() when trying to execute bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
Help will be appreciated. Thank you!
EDIT: I had initialized bundle wrong. Now I do not get any sort of errors, but the checkbox state isn't saved. I could use some help with that. Thank you!

Related

getView not called on baseAdapter class using Android Studio

I have use this class extends base adapter display values. Below code working eclipse correctly. but me newly created project using Androi Studio there this code getview function not call or working.
i also check getcount . getcount values available.
public class CustomAdapterChatActivity extends BaseAdapter {
ArrayList<ChatUsersDetailsBean> mBeans = new ArrayList<ChatUsersDetailsBean>();
Context mcontext;
LayoutInflater inflater;
CommonUtil commonUtil;
public CustomAdapterChatActivity(Context context,
ArrayList<ChatUsersDetailsBean> mBeans) {
// TODO Auto-generated constructor stub
mcontext = context;
this.mBeans = mBeans;
commonUtil = new CommonUtil(context);
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mBeans.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name;
TextView content;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("getView",""+"getView");
if (convertView == null) {
convertView = inflater.inflate(
R.layout.chat_listview_layout_screen, null);
}
setAttributes(position, convertView);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
click(position);
}
});
return convertView;
}
public void click(int position) {
Intent mintent = new Intent(mcontext, ChatViewBackgroundActivity.class);
mintent.putExtra("name", mBeans.get(position).getOpponent_name());
((ChatActivity) mcontext).startActivityForResult(mintent, 1);
}
public void setAttributes(final int position, View convertView) {
Holder holder = new Holder();
holder.imgdispatcher = (ImageView) convertView
.findViewById(R.id.chat_list_iv_profilepic);
}
Please help me. i struggle this part.
No error will be displayed.
i check getview run or not that time getview not working anytime.
this code any changes needed
Change your getView() method in your adapter class like below code:
public View getView (final int position, View convertView, ViewGroup parent){
if( convertView == null ){
//We must create a View:
convertView = inflater.inflate(R.layout.my_list_item, parent, false);
}
//Here we can do changes to the convertView
return convertView;
}
While adding newly inflated view, try to avoid passing null as view root. Lint will now warn you not to pass in null for root. Your app won’t crash in this scenario, but it can misbehave. When your child View doesn’t know the correct LayoutParams for its root ViewGroup, it will try to determine them on its own using generateDefaultLayoutParams.
#AbiK If you already done like I mentioned on above comment means, use below code of modified getView() method and setAttributes() method. I hope It works for you.
public class CustomAdapterChatActivity extends BaseAdapter {
ArrayList<ChatUsersDetailsBean> mBeans;
Context mcontext;
LayoutInflater inflater;
CommonUtil commonUtil;
public CustomAdapterChatActivity(Context context,
ArrayList<ChatUsersDetailsBean> mBeans) {
mcontext = context;
this.mBeans = mBeans;
commonUtil = new CommonUtil(context);
}
#Override
public int getCount() {
return mBeans.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name;
TextView content;
ImageView imgdispatcher;
}
public Holder setAttributes(final int position, View convertView) {
Holder holder = new Holder();
holder.imgdispatcher = (ImageView) convertView.findViewById(R.id.chat_list_iv_profilepic);
// holder.name=(TextView)convertView.findViewById(R.id.); // declare Id
// holder.content=(TextView)convertView.findViewById(R.id.); // declare Id
return holder;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = null;
LayoutInflater inflater = (LayoutInflater)
mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.chat_listview_layout_screen, parent, false);
holder = setAttributes(position, convertView);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
click(position);
}
});
return convertView;
}
public void click(int position) {
Intent mintent = new Intent(mcontext, ChatViewBackgroundActivity.class);
mintent.putExtra("name", mBeans.get(position).getOpponent_name());
((ChatActivity) mcontext).startActivityForResult(mintent, 1);
}
}

Need help in Multiplying the edit text value with a text view value from a custom list view in android

I have created a custom list view with a image view, 2 text view,one edit text one is for displaying brand names a string value another for displaying loyalty points, edit text for entering the quantity by the user which will be multiplied with loyalty point from text view.I have tried to multiplying the user entered value in each list item (from edit text)with the text view loyalty points value,I have implemented my own logic for multiplying it but it is not working, I have posted my code here for your reference correct me if any thing wrong in the code
MainActivity.java
public class MainActivity extends Activity {
ListView lv;
Context context;
static TextView ttv;
ArrayList prgmName;
public static int [] prgmImages={R.drawable.images,R.drawable.images1,R.drawable.images2,R.drawable.images3,R.drawable.images4,R.drawable.images5,R.drawable.images6,R.drawable.images7,R.drawable.images8};
public static String [] prgmNameList={"Britania","Rin","Goodrej","ITC","Nestle","Wheel","Ariel","Tide"};
public static String [] loyal_pts={"10","5","15","25","20","18","30","32"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
ttv= (TextView) findViewById(R.id.tot_point);
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages,loyal_pts));
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter{
String [] result;
String [] Pts;
Context context;
int [] imageId;
int total_points;
String con_pts;
int lyl_pts;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages, String[] loyal_pts) {
// TODO Auto-generated constructor stub
result=prgmNameList;
Pts=loyal_pts;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
TextView tv1;
ImageView img;
EditText etxt;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder=new Holder();
View rowView;
// final int total_points,con_pts,lyl_pts;
rowView = inflater.inflate(R.layout.item_list, null);
try{
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.etxt= (EditText) rowView.findViewById(R.id.edit_txt);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.tv1= (TextView) rowView.findViewById(R.id.textView2);
holder.tv.setText(result[position]);
holder.tv1.setText(" " + Pts[position] + "pts");
holder.img.setImageResource(imageId[position]);
System.out.println("total points"+total_points);
holder.etxt.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) {
try {
lyl_pts = Integer.parseInt(String.valueOf(Pts[position]));
con_pts = holder.etxt.getText().toString().trim();
total_points = lyl_pts * Integer.parseInt(con_pts);
Toast.makeText(context,total_points,LENGTH_LONG).show();
System.out.println("heyy"+total_points);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
catch(Exception e){
e.printStackTrace();
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Toast.makeText(context, "You Clicked " + result[position], LENGTH_LONG).show();
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
});
return rowView;
}
}
getView() is called whenever a new item is displayed on screen. at the initial phase nothing will be in your EditText so that you are not getting expected result from this line in getView() method.
con_pts=holder.etxt.getText().toString().trim();
I suggest either putting some initial value at etxt Or moving the logic in afterTextChanged like here
#Override
public void afterTextChanged(Editable s) {
lyl_pts=Integer.parseInt(String.valueOf(Pts[position]));
con_pts=holder.etxt.getText().toString().trim();
total_points = lyl_pts * Integer.parseInt(con_pts);
System.out.println("total points"+total_points);
}

click to start new activity in grid view

I have grid view in my application. on click of each image in gridview new activity should start.
now when I click on them, a toast appears.
how I manage setOnClicklistener in my adaptor I can't have startactivity.
enter code here:
public class CustomAdapter extends BaseAdapter {
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MyActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
and here is myactivity:
public class MyActivity extends Activity {
GridView gv;
Context context;
ArrayList prgmName;
public static String [] prgmNameList={"Let Us C","c++","JAVA","Jsp","Microsoft .Net","Android","PHP","Jquery","JavaScript"};
public static int [] prgmImages={R.drawable.images,R.drawable.images1,R.drawable.images2,R.drawable.images3,R.drawable.images4,R.drawable.images5,R.drawable.images6,R.drawable.images7,R.drawable.images8};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gv=(GridView) findViewById(R.id.gridView1);
gv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Add onItemClickListener on GridView
gv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
if(position==0){
Intent iinent= new Intent(MyActivity.this,secondactivity.class);
startActivity(iinent);
}
}
});

why android mycustom adapter not working

mycustom adapter which extends from baseadapter but when i run my main java file it shows main activity no
list view item
public class MyCustomadapter extends BaseAdapter{
private Context mycontext;
String[] mystringlist;
public MyCustomadapter(Context context,String[] strText) {
this.mycontext=context;
this.mystringlist = strText;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mystringlist.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.each_row, parent,false);
TextView tv = (TextView) rowView.findViewById(R.id.rowtxt);
tv.setText(mystringlist[position]);
return rowView;
}
}
mycustom adapter which extends from baseadapter but when i run my main java file it shows main activity no
list view item
problem:
return 0;
You are return 0 means there would be no list items to be displayed in your ListView thus giving you 0 result.
You need to return the number of item in your array or the length of it.
sample:
#Override
public int getCount() {
// TODO Auto-generated method stub
return mystringlist.length;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return mystringlist.length();
}
My idea is extending ArrayAdapter, Have a look at the following codes
public class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, String[] items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// your codes for generating rows
String thisItem = getItem(position);
}
}
You're done, also you're no longer need to override other methods!
Just as an addendum your getItem() method is incorrect. It should read as follows:
#Override
public Object getItem(int arg0) {
return mystringlist[position];
}

how to store value of checkboxes when creating a custom listView android

public class AppleSupportList extends BaseAdapter {
private LayoutInflater mInflater;
private final String[] values;
public AppleSupportList(Context context, String[] values) {
mInflater = LayoutInflater.from(context);
this.values = values;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return values.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customlist1, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.labelContact1);
holder.img = (ImageView) convertView.findViewById(R.id.imageContact1);
holder.check = (CheckBox) convertView.findViewById(R.id.checkBoxContact1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(values[position]);
holder.check.setId(position);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.check.isChecked()) {
holder.check.setChecked(false);
//store id
} else {
holder.check.setChecked(true);
//remove id
}
}
});
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
//store id
} else {
//remove id
}
}
});
return convertView;
}
static class ViewHolder {
TextView text1;
ImageView img;
CheckBox check;
}
}
i am creating a custom list view with check boxes.all works fine except when i scroll the list the check boxes get checked/unchecked automatically.
How can i store the state of check boxes.
I have gone through all related questions but nothing worked for me.
Please take a look at my code and help me out.
Your Custom Adapter must implement CompoundButton.OnCheckedChangeListener. Use a SparseBooleanArray.
Drawing from Romain guy's solution #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
Then
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
Then use the checked state to set text to check box
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
Use the below example as reference and modify according your requirements. I have not used a viewholder in the sample. Use a view holder as you used in your code.
Example
public class MainActivity extends Activity implements
AdapterView.OnItemClickListener {
int count;
private CheckBoxAdapter mCheckBoxAdapter;
String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for(int i=0;i<GENRES.length;i++)
{
if(mCheckBoxAdapter.mCheckStates.get(i)==true)
{
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int
position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
String[] gen;
CheckBoxAdapter(MainActivity context, String[] genres)
{
super(context,0,genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen= genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.checkbox, null);
tv= (TextView) vi.findViewById(R.id.textView1);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ gen [position]);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
checkbox.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>

Categories

Resources