jeudi 13 août 2015

how to use checkbox in customlistview

How to use checkbox in customlistview, if i check the checkbox means, am not getting any response.if i select any checkbox means, toast should come.

Visting_PlacesJSONParser.java

    public class Visting_PlacesJSONParser
    {


      public Map<String,VisitingPlaces_Getter> parse(JSONObject jObject){       

        JSONArray jClubs = null;
        try {       

            jClubs = jObject.getJSONArray("PLACES");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return getCountries(jClubs);
    }

    private Map<String, VisitingPlaces_Getter> getCountries(JSONArray jClubs){
        int clubCount = jClubs.length();

        Map<String, VisitingPlaces_Getter> club = new LinkedHashMap<String, VisitingPlaces_Getter>();
        List<Map<String, VisitingPlaces_Getter>> placeList = new ArrayList<Map<String,VisitingPlaces_Getter>>();

        String place_id = "";
        String place_name = "";
        String place_image1="";
        String profile_flag = "";
        String place_rating = "";
        String place_description = "";


        VisitingPlaces_Getter obj =null;

            try {
                for(int i=0; i<clubCount;i++){

                JSONObject jClub =(JSONObject)jClubs.get(i);
                place_id = jClub.getString("place_id").trim();
                place_name = jClub.getString("place_name").trim();
                place_image1 = jClub.getString("place_image");

                place_rating = jClub.getString("place_rating");
                place_description = jClub.getString("place_description");


            //profile_flag = "http://ift.tt/1IK1HaS".concat(place_image1);

                profile_flag = "http://ift.tt/1WlCoDe".concat(place_image1);


                if(club.get(place_name) !=null){
                    obj =club.get(place_name);
                    club.put(place_name, obj);
                }else{
                    obj=new VisitingPlaces_Getter();
                    obj.setPlace_id(place_id);
                    obj.setPlace_name(place_name);
                    obj.setPlace_image(profile_flag);
                    obj.setRating(place_rating);
                    obj.setDescription(place_description);

                    club.put(place_name, obj);


                }

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }


        return club;
    }



}

VisitingPlaces_Getter.java

    public class VisitingPlaces_Getter

    {

    String name = null;
    boolean selected = false;


    private String place_id;

    private String place_name;

    private String place_rating = "";

    public String getRating() {
        return place_rating;
    }
    public void setRating(String rating) {
        this.place_rating = rating;
    }
    public String getDescription() {
        return place_description;
    }
    public void setDescription(String description) {
        this.place_description = description;
    }
    private String place_description = "";
    String place_image = "";





    public String getPlace_id() {
        return place_id;
    }
    public void setPlace_id(String place_id) {
        this.place_id = place_id;
    }
    public String getPlace_name() {
        return place_name;
    }
    public void setPlace_name(String place_name) {
        this.place_name = place_name;
    }
    public String getPlace_image() {
        return place_image;
    }
    public void setPlace_image(String place_image) {
        this.place_image = place_image;
    }



    public String getName()  
    {
      return name;
    }

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

    public boolean isSelected()  
    {
       return selected;
    }

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

}

VisitingPlaces_FliterList.java

public class VisitingPlaces_FliterList extends Activity 

{

  String strUrl;
  private static LayoutInflater inflater = null;
  JSONArray places = null;
private View vi;
private ListView listview;  
private ViewHolder viewHolder;

private static String url = "http://ift.tt/1IK1EM9";
private static String url1 = "http://ift.tt/1WlCqe8";
private ListView mainListView;

private int count;  
private boolean[] thumbnailsselection;  

boolean[] checkBoxState;

TourGuideController dbcon;
String data;
private static final String TAG_PLACES = "PLACES";
private static final String TAG_NAME = "place_name";
TextView msg;
ListView mListView;
private ProgressDialog pDialog;
HashMap<String, Object> hm = null;
HashMap<String, Object> hm2 = null;
HashMap<String, Object> hm3 = null;
VisitingPlaces_Getter obj;
ArrayList<HashMap<String, String>> placeList;
AutoCompleteTextView desigination,source11 ;
AutoCompleteTextView source;
final Context context = this;
List<String> responseList = new ArrayList<String>();
ArrayList<String> items = new ArrayList<String>(); 
SimpleAdapter adapter;
Button click,delete;
String location;
String src1 ;
String desc1 ;
long count1;
CheckBox placeselect;

Map<String, VisitingPlaces_Getter> visitings = null;

ArrayList<Map<String, Object>> newList = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    setContentView(R.layout.visitingplace_fliterlist); 

    click = (Button) findViewById(R.id.start_plan);
    delete = (Button) findViewById(R.id.delete);

    dbcon = new TourGuideController(this);
    dbcon.open();

    Cursor cursor = dbcon.readAll();
    Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor));





    new GetSpinner().execute();

    click.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            dbcon.deleteData();


            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                    VisitingPlaces_FliterList.this,
                    android.R.layout.simple_dropdown_item_1line, responseList);

            LayoutInflater li = LayoutInflater.from(context);
            View promptsView = li.inflate(R.layout.prompts, null);
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
            alertDialogBuilder.setView(promptsView);
            source = (AutoCompleteTextView) promptsView.findViewById(R.id.source);
            desigination = (AutoCompleteTextView) promptsView.findViewById(R.id.desigination);

            source.setAdapter(arrayAdapter);
            desigination.setAdapter(arrayAdapter);

            alertDialogBuilder
                    .setCancelable(false)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {


                                    String src = source.getText().toString();
                                    String desc = desigination.getText().toString();

                                    System.out.println("TESTING SRC>>>>>"+src);
                                    System.out.println("TESTING DESC>>>>>"+desc);

                                    SendHttpRequestTask t = new SendHttpRequestTask();

                                    String[] params = new String[]{url1, src,desc};
                                    t.execute(params);

                                }
                            })

                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                }
                            });

            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();

        }

    });


    msg = (TextView)findViewById(R.id.msg);

    strUrl = "http://ift.tt/1WlCqe8";


}  





private class SendHttpRequestTask extends AsyncTask<String, Void, String> 

  {

    @Override
    protected String doInBackground(String... params) {
         String url1 = params[0];
        final String src1 = params[1];
        final String desc1 = params[2];


        try {

            HttpClient client = new HttpClient(url1);
            client.connectForMultipart();


            client.addFormPart("parseSource", src1);
            client.addFormPart("parseDestination", desc1);

             client.finishMultipart();
             data = client.getResponse();

             if(data!=null){
                 Handler h = new Handler(Looper.getMainLooper());
                    h.post(new Runnable() {
                      public void run() {

                          DownloadTask downloadTask = new DownloadTask();
                          downloadTask.execute(strUrl);
                          mListView = (ListView) findViewById(R.id.list_visit);

                      }
                    });
                }
                else{

    Toast.makeText(getBaseContext(), "no data",Toast.LENGTH_SHORT).show();

  }


            System.out.println("SORTED RESPONSE"+data);
        }
        catch(Throwable t) {
            t.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String data) {         

    }

}


private class GetSpinner extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(VisitingPlaces_FliterList.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        ServiceHandler sh = new ServiceHandler();


        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Spinner Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {

                JSONObject jsonObj = new JSONObject(jsonStr);

                places = jsonObj.getJSONArray(TAG_PLACES);

                for (int i = 0; i < places.length(); i++) {
                    final JSONObject e = places.getJSONObject(i);
                     String name = e.getString(TAG_NAME);
                    // String place_longitude = e.getString(TAG_LONG);
                   //  String place_latitude = e.getString(TAG_LAT);


                     responseList.add(name);
                     //longList.add(place_longitude);
                     //latList.add(place_latitude);
                  }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();





    }

}


/*


private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    try{



            URL url = new URL(strUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            StringBuffer sb  = new StringBuffer();
            String line = "";

            while( ( line = br.readLine())  != null){
                sb.append(line);
            }
            data = sb.toString();

            br.close();

            System.out.println("RESPONSE_FEATURED"+data);

    }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
    }finally{
            iStream.close();
    }


    return data;
}

*/


private class DownloadTask extends AsyncTask<String, Integer, String>{
    //String data = null;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(VisitingPlaces_FliterList.this);
        //pDialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.progress));
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }
            @Override
            protected String doInBackground(String... url) {
                    try{
                        //data = downloadUrl(url[0]);


                        Log.e("LISTVIEW RESPONSE", data);


                    }catch(Exception e){
                        Log.d("Background Task",e.toString());
                    }
                    return data;
            }

            @Override
            protected void onPostExecute(String result) {
                if (pDialog.isShowing())
                    pDialog.dismiss();

                    ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
                    listViewLoaderTask.execute(result);     

            }
}


private Bitmap decodeFile(File f) {
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE=70;

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        while(o.outWidth / scale / 2 >= REQUIRED_SIZE && 
              o.outHeight / scale / 2 >= REQUIRED_SIZE) {
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}



private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

    JSONObject jObject;

    @Override
    protected SimpleAdapter doInBackground(String... strJson) {
        try{
            jObject = new JSONObject(strJson[0]);
            Visting_PlacesJSONParser visitingJsonParser = new Visting_PlacesJSONParser(); 
            visitingJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("JSON Exception1",e.toString());
        }


        Visting_PlacesJSONParser visitingJsonParser = new Visting_PlacesJSONParser();




        List<String> imgList = null;

        //count = newList.size();  
        //thumbnailsselection = new boolean[count];  

        try{

            visitings = visitingJsonParser.parse(jObject);

            Log.e("jObject", jObject.toString());
            Map<String, Object> test=null;

            if(visitings.size() >0){
                newList = new ArrayList<Map<String,Object>>();



                    for (Map.Entry<String, VisitingPlaces_Getter> entry : visitings.entrySet())
                    {
                        test =new HashMap<String, Object>();
                        obj=(VisitingPlaces_Getter)entry.getValue();


                        test.put("place_id", obj.getPlace_id());
                        test.put("place_name", obj.getPlace_name());
                        test.put("place_image", obj.getPlace_image());
                        test.put("place_description", obj.getDescription());
                        test.put("flag", R.drawable.defailt_profile_img);
                        test.put("place_rating", obj.getRating());

                        String p_id = obj.getPlace_id();
                        String p_name = obj.getPlace_name();
                        String p_rating = obj.getRating();
                        String p_description = obj.getDescription();
                        //String p_id = obj.getPlace_id();


                        System.out.println("p_id"+p_id);
                        System.out.println("p_name"+p_name);
                        System.out.println("p_rating"+p_rating);
                        System.out.println("p_description"+p_description);

                        newList.add(test);

                        items.add(p_name);

                        count = items.size(); 

                        System.out.println("COUNT"+count);
                        thumbnailsselection = new boolean[count];


                       // mListView.setAdapter(new ImageAdapter(VisitingPlaces_FliterList.this)); 
                        dbcon.insertData(p_id, p_name, p_rating, p_description);

                    }

            }
            else{

                msg.setVisibility(View.VISIBLE);
            }

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }

        String[] from = { "place_name","flag","place_rating","place_description"};

        int[] to = { R.id.tv_title, R.id.iv_flag,R.id.ratingBar2,R.id.tv_desc};



      adapter = new SimpleAdapter(getBaseContext(), newList, R.layout.visitingplace_backfliter, from, to); 


      adapter.setViewBinder(new MyBinder());



                  return adapter;

    }

    @Override
    protected void onPostExecute(final SimpleAdapter adapter) {

        if (pDialog.isShowing())
            pDialog.dismiss();

            mListView.setAdapter(adapter);

           // mListView.setAdapter(new ImageAdapter(VisitingPlaces_FliterList.this));

            for(int i=0;i<adapter.getCount();i++){

            hm = (HashMap<String, Object>) adapter.getItem(i);

            String imgUrl = (String) hm.get("place_image");

            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();

                hm.put("place_image",imgUrl);
                hm.put("position", i);


            // Starting ImageLoaderTask to download and populate image in the listview 
            imageLoaderTask.execute(hm);





        mListView.setOnItemClickListener(new OnItemClickListener() {


            public void onItemClick(AdapterView<?> parent, View view,

                    int position, long id) {





                //Toast.makeText(VisitingPlaces_FliterList.this, "test", Toast.LENGTH_SHORT).show();

                hm2 = (HashMap<String, Object>) adapter.getItem(position);


                ArrayList<String> arr = new ArrayList<String>();

                System.out.println("postion"+hm2);


                String name = (String) hm2.get("place_name");
                String description = (String) hm2.get("place_description");  
                String image_path = (String) hm2.get("place_image");  

                System.out.println("description_testing"+description);


                Intent in = new Intent(VisitingPlaces_FliterList.this,VisitingPlaces_Detailedview.class);
                in.putExtra("place_name", name);
                in.putExtra("place_description", description);  
                in.putExtra("imagePath", image_path); 
                //in.putExtra("title", visiting_title);
                //in.putExtra("desc",description);

                //Toast.makeText(VisitingPlaces_FliterList.this, "test", Toast.LENGTH_SHORT).show();
                startActivity(in);

            }
        });


         }


    }   
}


class MyBinder implements ViewBinder{
    /*
    CheckBox checkbox = (CheckBox) findViewById(R.id.select_place);

    if (checkbox.setChecked(false)) {  

       Log.e("", "Noooooooo");

    } else { 
       Log.e("", "yeppppp");

      checkbox.setChecked(true);  

    }  */



    public boolean setViewValue(View view, Object data, String rate) {
        if(view.getId() == R.id.ratingBar2){

            String stringval = rate;

            float ratingValue = Float.parseFloat(stringval);

            RatingBar ratingBar = (RatingBar) view;
            ratingBar.setRating(ratingValue);
            return true;
        }

        return false;
    }
}



private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;
        String imgUrl = (String) hm[0].get("place_image");
        int position = (Integer) hm[0].get("position");

        URL url;
        try {
            url = new URL(imgUrl);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            File cacheDirectory = getBaseContext().getCacheDir();
            File tmpFile = new File(cacheDirectory.getPath() + "/visiting_"+position+".png");
            System.out.println("TEMPFILE"+tmpFile);
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            Bitmap preview_bitmap = BitmapFactory.decodeStream(iStream, null, options);



            //Bitmap b = BitmapFactory.decodeStream(iStream);    

            preview_bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream); 


            fOutStream.flush();
            fOutStream.close();
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
            hmBitmap.put("flag",tmpFile.getPath());
            hmBitmap.put("position",position);
            return hmBitmap;                


        }catch (Exception e) {              
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {

        String path = (String) result.get("flag");  

        int position = (Integer) result.get("position");
        SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);   
        hm.put("flag",path);
        adapter.notifyDataSetChanged(); 

        if (pDialog.isShowing())
            pDialog.dismiss();
    } 
}




public class ImageAdapter extends BaseAdapter {  
    private LayoutInflater mInflater;  
    private Context mContext;  
    public ImageAdapter(Context context) {  
         mContext = context;  
    }  
    public int getCount() {  
         return count;  
    }  
    public Object getItem(int position) {  
         return position;  
    }  
    public long getItemId(int position) {  
         return position;  
    }  


    public View getView(int position, View convertView, ViewGroup parent) {  
         ViewHolder holder;  
         if (convertView == null) {  
              holder = new ViewHolder();  
              convertView = LayoutInflater.from(mContext).inflate(  
                        R.layout.visitingplace_fliterlist, null);  
              holder.textview = (TextView) convertView  
                        .findViewById(R.id.tv_title);  

              holder.checkbox = (CheckBox) convertView  
                        .findViewById(R.id.select_place);  
              convertView.setTag(holder);  

         } 
            else {  
              holder = (ViewHolder) convertView.getTag();  
         }  
         holder.checkbox.setId(position);  
         holder.textview.setId(position);  

         holder.checkbox.setOnClickListener(new OnClickListener() {  
              public void onClick(View v) {  
                   // TODO Auto-generated method stub  
                   CheckBox cb = (CheckBox) v;  
                   int id = cb.getId();  
                   if (thumbnailsselection[id]) {  

                       Log.e("", "Noooooooo");
                        cb.setChecked(false);  
                        thumbnailsselection[id] = false;  
                   } else { 
                       Log.e("", "yeppppp");

                        cb.setChecked(true);  
                        thumbnailsselection[id] = true;  
                   }  
              }  
         });  


         holder.textview.setOnClickListener(new OnClickListener() {  
              public void onClick(View v) {  
                   // TODO Auto-generated method stub  
                   int id = v.getId();  
              }  
         });  

         holder.textview.setText(items.get(position));  
         holder.checkbox.setChecked(thumbnailsselection[position]);  
         holder.id = position;  
         return convertView;  
    }  
   }  
    class ViewHolder {  
    TextView textview;  
    CheckBox checkbox;  
    int id;  
  }  


  public void click(View v) { 

   Log.e("", "Click");
   if (v.getId() == R.id.delete) {  
        final ArrayList<Integer> posSel = new ArrayList<Integer>();  
        posSel.clear();  
        boolean noSelect = false;  
        for (int i = 0; i < thumbnailsselection.length; i++) {  
             if (thumbnailsselection[i] == true) {  
                  noSelect = true;  
                  Log.e("sel pos thu-->", "" + i);  

                  posSel.add(i);  

                  // break;  
             }  
        }  
        if (!noSelect) {  
             Toast.makeText(VisitingPlaces_FliterList.this, "Please Select Item!",  
                       Toast.LENGTH_SHORT).show();  
        } else {  
            for(int j=0;j<posSel.size();j++)
            {

             Toast.makeText(VisitingPlaces_FliterList.this,  
                       "Selected Items:" + items.get(posSel.get(j)),  
                       Toast.LENGTH_LONG).show();  
        }
            }  
   }  
 }  




 }




Aucun commentaire:

Enregistrer un commentaire