0

I am displaying hotels in listview with checkbox,image and text. when user click on checkbox then put that checked hotel_id into bundle. And pass to it's super class.

When i am selected hotels and click on button on main activity my logcat shows NullPointerException. I will check my code with debugger. I can find getting Bundle=null. So please help to find the hotel_id when click's on checkbox and send that all selected hotel_id to its main Activity.

Here is my ListViewAdapter class.

public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<Product> AllMenu = new ArrayList<>();
ImageLoader imageLoader;
int checkCounter = 0;
public ListViewAdapter(Context context, ArrayList<Product> itemlist) {
    this.context = context;
    AllMenu = itemlist;
    imageLoader = new ImageLoader(context);
    checkCounter = 0;
}
public int getCount() {
    return AllMenu.size();
}
public Object getItem(int position) {
    return position;
}
public long getItemId(int position) {
    return 0;
}

public View getView(final int position, final View convertView, final ViewGroup parent) {
    // Declare Variables
    final Product tempMenu = AllMenu.get(position);
    final CheckBox c;
    final ImageView image_path;
    final TextView name, location, desc;
    final Bundle b = new Bundle();
    final Intent intent = new Intent(context.getApplicationContext(),Hotels.class);

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View view = inflater.inflate(R.layout.viewpage, parent, false);

    // Get the position
    c = (CheckBox) view.findViewById(R.id.mycheckbox);
    name = (TextView) view.findViewById(R.id.fh_name);
    location = (TextView) view.findViewById(R.id.fh_loc);
    desc = (TextView) view.findViewById(R.id.fh_desc);
    image_path = (ImageView) view.findViewById(R.id.image_all_main);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            if (c.isChecked() && checkCounter >= 3) {
                AllMenu.get(position).setSelected(false);
                c.setChecked(false);
                Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
            } else {
                Product p = (AllMenu).get(position);
                p.setSelected(c.isChecked());
                if (c.isChecked()) {
                    checkCounter++;

                } else {
                    checkCounter--;
                }

            }
            StringBuffer responseText = new StringBuffer();
            responseText.append("The following were selected...");

            ArrayList<Product> p = AllMenu;
            for (int i = 0; i < p.size(); i++) {
                Product pp = p.get(i);
                if (pp.isSelected()) {
    //here is i want hotel id when i am cliked on hotel.
    //and save it into bundle and i am get bundle into it's super class

                    String[] h = new String[0];
                    b.putStringArray(String.valueOf(pp.getId()),hid);
                    intent.putExtras(b);

    //Here is how i can pass custom object to string

                    responseText.append("\n" + pp.getName() + "\t");
                    responseText.append("\t" + pp.getLocation());
                }
            }
            Toast.makeText(context, responseText, Toast.LENGTH_SHORT).show();

        }
    });

    c.setTag(tempMenu);
    c.setChecked(tempMenu.isSelected());
    name.setText(tempMenu.getName());
    location.setText(tempMenu.getLocation());
    desc.setText(tempMenu.getDescription().trim());
    imageLoader.DisplayImage(tempMenu.getImage_path(), image_path);
   return view;
}
}

And i will get that bundle into this Hotels.class

Here is my Hotels.class

public class  Hotels extends Activity
{
// Declare Variables
JSONArray jsonarray = null;
private static final String TAG_ID= "id";
public static final String TAG_NAME = "name";
public static final String TAG_LOCATION = "location";
public static final String TAG_DESC = "description";
String f_date,l_date;
int[] hotel_id = new int[0];


ProgressDialog loading;
ListView list;
Button booknow;
ListViewAdapter adapter;
private ArrayList<Product> itemlist;
Product product;
static String Array = "MyHotels";
View view;
CheckBox click;
String hotel = "http://app.goholidays.info/getHotelData.php";
String booking = "http://app.goholidays.info/insertIntoBooking.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_item_layout);
    product = new Product();

    itemlist = new ArrayList<Product>();
    new ReadJSON().execute();
    click = (CheckBox) findViewById(R.id.mycheckbox);
    booknow = (Button) findViewById(R.id.bookhotel);
    product = new Product();
    list = (ListView) findViewById(R.id.myimagelist);

    Calendar c = Calendar.getInstance();
    System.out.println("Current time => "+c.getTime());
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Hotels.this);
    SharedPreferences.Editor editor = sp.edit();

    final String user_id = sp.getString("id", TAG_ID);
    final String start_date = sp.getString("start_date", f_date);
    final String end_date = sp.getString("end_date", l_date );
    final String chk_status = df.format(c.getTime());

    booknow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

    //here i want get all selected hotel_id into bundle. 
    //And i want pass that hotel_id to my database.
            Bundle bundle = getIntent().getExtras();
            String[] hotel_id = bundle.getStringArray(String.valueOf(product.getId()));
            Submit(start_date,end_date,hotel_id,chk_status,user_id);
        }
    });
}

class ReadJSON extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loading = ProgressDialog.show(Hotels.this,"Fetching Data","Please wait...",false,false);
    }
    @Override
    protected String doInBackground(String... args) {
        Product tempMenu;
        try {
            JSONObject jsonobject = JSONfunctions.getJSONfromURL(hotel);
            jsonarray = jsonobject.optJSONArray(Array);
            //parse date for dateList
            for (int i = 0; i < jsonarray.length(); i++) {
                tempMenu = new Product();
                jsonobject = jsonarray.getJSONObject(i);
                tempMenu.setId(jsonobject.getInt("hotel_id"));
                tempMenu.setName(jsonobject.getString("name"));
                tempMenu.setLocation(jsonobject.getString("location"));
                tempMenu.setImage_path(jsonobject.getString("image_name"));
                tempMenu.setDescription(jsonobject.getString("description"));
                tempMenu.setFacility1(jsonobject.getString("facility1"));
                tempMenu.setFacility2(jsonobject.getString("facility2"));
                tempMenu.setFacility3(jsonobject.getString("facility3"));
                tempMenu.setFacility4(jsonobject.getString("facility4"));
                tempMenu.setStar(jsonobject.getString("star"));
                itemlist.add(tempMenu);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        adapter = new ListViewAdapter(Hotels.this, itemlist);
        list.setAdapter(adapter);
        loading.dismiss();
    }
}
private void Submit(final String start_date, final String end_date, final String[] hotel_id, final String chk_status, final String user_id) {
    class BackTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String... params) {
            String start_dtae = params[0];
            String end_date = params[1];
            String hotel_id = params[2];
            String user_id = params[3];
            String chk_status = params[4];

            try {
                URL url = new URL(booking);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream os = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                String data = URLEncoder.encode("start_date", "UTF-8") +"="+URLEncoder.encode(start_dtae, "UTF-8") + "&" +
                        URLEncoder.encode("end_date", "UTF-8") +"="+URLEncoder.encode(end_date, "UTF-8") + "&" +
                        URLEncoder.encode("hotel_id", "UTF-8") +"="+URLEncoder.encode(hotel_id, "UTF-8") + "&" +
                        URLEncoder.encode("user_id", "UTF-8") +"="+URLEncoder.encode(user_id, "UTF-8") + "&" +
                        URLEncoder.encode("chk_status", "UTF-8") +"="+URLEncoder.encode(chk_status, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                os.close();

                InputStream is = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                String responce = "";
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    responce += line;
                }
                bufferedReader.close();
                is.close();
                httpURLConnection.disconnect();
                return responce;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast.makeText(getApplicationContext(),"Book Success"+result,Toast.LENGTH_SHORT).show();
        }
    }
    BackTask lg=new BackTask();
    lg.execute(start_date, end_date, chk_status, String.valueOf(hotel_id), user_id);
}
}

My custom object class is here.

public class Product extends HashMap<String, String> {

private String name;
private int hotel_id;
private String description;
private String location;
private String image_path;
boolean selected;

public boolean isSelected(){
    return selected;
}
public void setSelected(boolean selected){
    this.selected = selected;
}

public void setId (int hotel_id) { this.hotel_id = hotel_id;}

public int getId() {
    return hotel_id;
}

public void setName (String name) { this.name = name;}

public String getName() {
    return name;
}

public void setLocation(String location) {
    this.location = location;
}

public String getLocation() {
    return location;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDescription() {
    return description;
}

public void setImage_path(String image_path) {
    this.image_path = image_path;
}

public String getImage_path() {
    return image_path;
}
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

0

The problem is you are only putting data to intent. It is just worth if You put bundle or data inside intent object with using startActivity.

If you want to get selected Hotel id's just make a public array like:-

public class  Hotels extends Activity
{
 public ArrayList<Integer> hotel_ids=new ArrayList<>();
}

and inside adapter while selecting check box put id in arrayList with the use of context as below and if unchecked remove hotel_id from that array list :-

 c.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                if (c.isChecked() && checkCounter >= 3) {
                    AllMenu.get(position).setSelected(false);         
                    c.setChecked(false);
                    Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
                } else {
                    Product p = (AllMenu).get(position);
                    p.setSelected(c.isChecked());
                    if (c.isChecked()) {
                       if(context instanceof Hotels){
           ((Hotels)context).hotel_ids.add(p.getId());
                        }  
                        checkCounter++;

                    } else {
                       if(context instanceof Hotels){
               ((Hotels)context).hotel_ids.remove(p.getId());
                       }  
                        checkCounter--;
                    }

                }
    }
}

It may help you out. With the above one you will always find selected Hotel_ids.

Aditi
  • 455
  • 4
  • 13
  • what is that mean it showing red line. if(context instance of Hotels) – yogi puranik Jul 22 '16 at 10:30
  • if i am use context.startActivity(intent) within setOnClickListener. Then it will restart my Hotels activity on every click on checkbox. and remove status of checkbox and display a existing list as it is. That's way i can not use it in my code. can u tell me where i can use context.startActivity(intent) in my code. – yogi puranik Jul 22 '16 at 10:36
  • sorry it is by mistake it is instanceof not instance Of , and you can' t do it with intent because activity is already running and by startActivity(intent), it again starts that activity which is worth so its better to pass value to main activity by using public variable. – Aditi Jul 22 '16 at 11:13
  • i am getting the position of row from this line ((Hotels)context).hotel_ids.remove(p.getId()); not an actual hotel_id. I will check this with debugger. Please help for find id u r very close to it. I am also doing the changes. thank You for response. – yogi puranik Jul 22 '16 at 11:51
  • when i deselecting a checkbox it will gives an error on this line ((Hotels)context).hotel_ids.remove(p.getId()); here is logcat java.lang.IndexOutOfBoundsException: Invalid index 6, size is 1 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) at java.util.ArrayList.remove(ArrayList.java:399) at com.hotel.yasmeenshaikh.GoHolidays.ListViewAdapter$1.onClick(ListViewAdapter.java:141) at android.view.View.performClick(View.java:4084) at android.widget.CompoundButton.performClick(CompoundButton.java:100) – yogi puranik Jul 22 '16 at 11:58
  • And i will check my database that "6" is my hotel_id. But when i getting it from arraylist i will gives me hotel_ids=1. and my second id is "37" and arraylist is giving me hotel_ids=2 means arraylist is also not adding hotel_id it was jst replace with existence value.and i actually want 6 and 37. I am so confusing. :-( – yogi puranik Jul 22 '16 at 12:14
  • @yogipuranik you can take one boolean in model class. so in adapter you can update that value on checkbox change listener. .now in main activity you just have to make loop and cheked in model class.checked boolean true. that you can add in other arraylist . – Vishal Thakkar Jul 25 '16 at 04:09
  • yes i am taking boolean in model class. But how u can update my checkbox values when it's change. If their any example you have plz share it. – yogi puranik Jul 25 '16 at 05:42
0

you can do something like this.

1> in getview method you can do checked listener like below

  viewHolder.chkbox.setOnCheckedChangeListener(new CheckUpdateListener(itemList.get(position));

2> make new class for CheckUpdatelistener with argument constructor of model class

    private final class CheckUpdateListener implements CompoundButton.OnCheckedChangeListener {
    private final Product product;

    private CheckUpdateListener(Product product) {
        this.product = product;


    }


    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.i("onCheckedChanged", "isChecked: " + isChecked);
        product.setChecked(isChecked);


        notifyDataSetChanged();




    }
}

3> in main activity on button click listener you can do code like this

     Arraylist<Product> selectedProduct = new ArrayList<>();




            if (itemList.size() > 0) {
                for (int i = 0; i < itemList.size(); i++) {
                    if (itemList.get(i).isChecked()) {
                        try {

                            selectedProduct.add(itemList.get(i));
                        } catch (NullPointerException e) {
                            e.printStackTrace();
                        }
                    }
                }
Vishal Thakkar
  • 2,117
  • 2
  • 16
  • 33
  • error on this line viewHolder.chkbox.setOnCheckedChangeListener(new CheckUpdateListener(parent)); 'CheckUpdateListener(com.hotel.yasmeenshaikh.GoHolidays.Product)' has private access in 'com.hotel.yasmeenshaikh.GoHolidays.CheckUpdateListener' – yogi puranik Jul 25 '16 at 05:59
  • @yogipuranik sorry i cant. you just have to pass model class there – Vishal Thakkar Jul 25 '16 at 06:07
  • I will already passed it and make it private but they says Modifier 'private' not allowed here. on this class private final class CheckUpdateListener implements CompoundButton.OnCheckedChangeListener { – yogi puranik Jul 25 '16 at 06:09
  • @yogipuranik you create that class inside getview so you get that error. create it out side getview. you just have to call it from get view – Vishal Thakkar Jul 25 '16 at 06:22
  • No sir i will create class in my package directory. not in inside getview. and sir where u can get hotel_id i need a hotel_id when checkbox is checked. U r jst getting a boolean value and it's position. :-( i feature i will use that hotel_id and send it to my server. – yogi puranik Jul 25 '16 at 06:27
  • @yogipuranik you have not set its id in model class – Vishal Thakkar Jul 25 '16 at 06:35
  • Here sir look my post in model class i am setting id's like this public void setId (int hotel_id) { this.hotel_id = hotel_id;} public int getId() { return hotel_id; } – yogi puranik Jul 25 '16 at 06:47
  • I am used setId for getting my hotel_id from json array in Hotels class. – yogi puranik Jul 25 '16 at 06:48