2013-10-07 112 views
0

在我的代碼中,當我從相機拍攝圖像時,它在imageview中正確顯示。但是,當我第二個圖像,兩個listview項目顯示相同的圖片..舊圖片取代新的..當我第三張圖片,然後所有三項顯示相同的結果。等等..請任何人都可以解決我的問題。ListView顯示從相機拍攝的最近圖像

public class CustomerRegistrationL0 extends Activity { 
int take_image; 
int UploadFile; 
static SimpleAdapter Adapter; 
static Bitmap thumbnail; 
static String encodedImageString; 
Bitmap image2; 
LayoutInflater mInflater; 

Uri selectedImage ; 
static ListView listviewattachment; 
    public ArrayList<ListItem> myItems = new ArrayList<ListItem>(); 
private MyAdapter myAdapter; 

@Override 
protected void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_cr_l0);   

    //declare fields 
    final EditText textcnic=(EditText)findViewById(R.id.EditTextCNIC); 
    final String cnic=textcnic.getText().toString(); 
    final EditText textmobile=(EditText)findViewById(R.id.editTextMob); 
    final String mobileNo=textmobile.getText().toString(); 
    final EditText textname=(EditText)findViewById(R.id.editTextName); 
    final String name=textname.getText().toString(); 
    final EditText textaddress=(EditText)findViewById(R.id.EditTextAdd); 
    final String address=textaddress.getText().toString(); 
    final EditText textkin=(EditText)findViewById(R.id.EditTextKin); 
    final String nextkin=textkin.getText().toString(); 


     listviewattachment=(ListView)findViewById(R.id.listView1); 
    ////////////////////////////////////////////////////////// 
     //make listview scrollable manuallly(shit) 
     listviewattachment.setOnTouchListener(new ListView.OnTouchListener() { 

      @Override 
      public boolean onTouch(View v, MotionEvent arg1) { 
       // TODO Auto-generated method stub 
       int action = arg1.getAction(); 
        switch (action) { 
        case MotionEvent.ACTION_DOWN: 
         // Disallow ScrollView to intercept touch events. 
         v.getParent().requestDisallowInterceptTouchEvent(true); 
         break; 

        case MotionEvent.ACTION_UP: 
         // Allow ScrollView to intercept touch events. 
         v.getParent().requestDisallowInterceptTouchEvent(false); 
         break; 
        } 

        // Handle ListView touch events. 
        v.onTouchEvent(arg1); 
        return true; 
      } 
     }); 

    //////////////// // ////////////////////////////////////////////////////////////// 
    Button buttonCamera=(Button)findViewById(R.id.buttonCamera); 
    Button buttonFromGallery=(Button)findViewById(R.id.buttonAttach); 
    Button formSubmit=(Button)findViewById(R.id.buttonSubmit); 

    buttonCamera.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View view) { 
      Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 


      startActivityForResult(i, take_image); 

     } 
}); 


    buttonFromGallery.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 

      Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
       intent.setType("*/*"); 
       intent.addCategory(Intent.CATEGORY_OPENABLE); 


        startActivityForResult(
          Intent.createChooser(intent, "Select a File to Upload"), 
          UploadFile); 
      } 

     });   

    formSubmit.setOnClickListener(new View.OnClickListener() {   


    public void onClick(View v) { 


     validate(textcnic,textmobile,textname,textaddress,textkin); 

    //decoding bytes 


     String attachedImage=encodedImageString; 

      JSONObject jsonObj = new JSONObject(); 
     try { 
      jsonObj.put("CNIC Number", cnic); 
      jsonObj.put("Mobile Number", mobileNo); 
      jsonObj.put("Name", name); 
      jsonObj.put("Address", address); 
      jsonObj.put("Next Kin", nextkin); 
      jsonObj.put("Image",attachedImage); 
      String jsonString=jsonObj.toString(); 
      File sdcard = Environment.getExternalStorageDirectory(); 
      try { 

       File myfile = new File(sdcard,"JSONCache.json"); 
       myfile.createNewFile(); 

       Writer myOutWriter = new BufferedWriter(new FileWriter(myfile)); 
       myOutWriter.write(jsonString); 
       myOutWriter.close(); 

       Toast.makeText(v.getContext(), "File Created", Toast.LENGTH_LONG).show(); 

       } catch (Exception e) { 
        e.getStackTrace(); 
         Toast.makeText(v.getContext(), "COuld not create file", Toast.LENGTH_LONG).show(); 
       } 
      //end of write json object 

     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     //write json object 

} 
    }); 


} 

private void validate(EditText cnic, EditText mobile, 
     EditText name, EditText address, EditText kin) { 
    // TODO Auto-generated method stub 

    if(name.getText().toString().trim().equals("")){ 
     name.setError("Please Enter Name"); 

    } 
} 


protected void onActivityResult(int requestCode, int resultCode, Intent data) { 



     super.onActivityResult(requestCode, resultCode, data); 


     if(resultCode == Activity.RESULT_OK) 
     { 
      if (requestCode==UploadFile){ 

       // Uri selectedImage = data.getData(); 

       // if ("content".equalsIgnoreCase(selectedImage.getScheme())) { 
       // String[] filePathColumn = { "_data" }; 

       //Cursor cursor = getContentResolver().query(selectedImage, 
       //  filePathColumn, null, null, null); 
       //cursor.moveToFirst(); 

       //int columnIndex = cursor.getColumnIndex("_data");} 
       // String picturePath = cursor.getString(columnIndex); 
       // cursor.close(); 
       // } 
       // else if ("file".equalsIgnoreCase(selectedImage.getScheme())) { 
    // String path= selectedImage.getPath();} 


      /* Uri selectedImage = data.getData(); 
       String[] filePathColumn = { "data"}; 

       Cursor cursor = getContentResolver().query(selectedImage, 
         filePathColumn, null, null, null); 
       cursor.moveToFirst(); 

       int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
       String picturePath = cursor.getString(columnIndex); 
       cursor.close();*/ 
     } 


     if (requestCode == take_image) { 


      //get image 
       thumbnail = (Bitmap) data.getExtras().get("data"); 



       BitmapFactory.Options factoryOptions = new BitmapFactory.Options(); 

       factoryOptions.inJustDecodeBounds = true; 




       int imageWidth = factoryOptions.inDensity=50; 
       int imageHeight = factoryOptions.inDensity=50; 

      image2 = Bitmap.createScaledBitmap(thumbnail, imageWidth , imageHeight, true); 

       //////listview work 


      listviewattachment.setItemsCanFocus(true); 
       myAdapter = new MyAdapter(); 
       ListItem listItem = new ListItem(); 
       myItems.add(listItem); 

       listviewattachment.setAdapter(myAdapter); 
       myAdapter.notifyDataSetChanged(); 

      ////////////////////end of listview work 

      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 


      thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
      //encode image 
      byte[] b = bytes.toByteArray(); 
       encodedImageString = Base64.encodeToString(b, Base64.DEFAULT); 

     } 

     } 
} 

    public class MyAdapter extends BaseAdapter { 
     private LayoutInflater mInflater; 

     public MyAdapter() { 
      mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     } 

     public int getCount() { 
      return myItems.size(); 
     } 

     public ListItem getItem(int position) { 
      return myItems.get(position); 
     } 

     public long getItemId(int position) { 
      return position; 
     } 

     public View getView(final int position, View convertView, 
       ViewGroup parent) { 
      final ViewHolder holder; 
      if (convertView == null) { 
       holder = new ViewHolder(); 
       convertView = mInflater.inflate(R.layout.imageview2, null); 


       holder.image = (ImageView) convertView 
         .findViewById(R.id.imageView2); 
       holder.Delete=(Button)convertView.findViewById(R.id.buttonClose); 

       convertView.setTag(holder); 
      } else { 
       holder = (ViewHolder) convertView.getTag(); 

      } 


      holder.image.setImageBitmap(image2); 

      holder.image.setTag(position); 
      holder.Delete.setTag(position); 

      holder.image.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View view) { 
        // TODO Auto-generated method stub 


        final Dialog imgDialog = new Dialog(view.getContext(),android.R.style.Theme_Translucent_NoTitleBar_Fullscreen); 

        imgDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
        imgDialog.setCancelable(false); 
        // layout imageview2 is used because when i use simple imageview layout dialogue with imageview and closebutton, 
        // every taken image at instancewill not be shown in dialogue. 
        imgDialog.setContentView(R.layout.imageview); 
        Button btnClose = (Button)imgDialog.findViewById(R.id.btnIvClose); 
        ImageView ivPreview = (ImageView)imgDialog.findViewById(R.id.image1); 


        BitmapFactory.Options factoryOptions = new BitmapFactory.Options(); 


       int imageWidth = factoryOptions.inDensity=400; 
        int imageHeight = factoryOptions.inDensity=500; 
        //thumbnail is selected coz if we select bm to enlarge it will give poor quality(bm is small sized image) 
      Bitmap Scaled = Bitmap.createScaledBitmap(CustomerRegistrationL0.thumbnail, imageWidth, imageHeight, true); 

        ivPreview.setImageBitmap(Scaled); 

        btnClose.setOnClickListener(new OnClickListener() { 
         @Override 
         public void onClick(View arg0) { 

          imgDialog.dismiss(); 
         } 
        }); 
        imgDialog.show(); 
         // ListItem listItem = new ListItem(); 

         //myItems.add(listItem); 

         myAdapter.notifyDataSetChanged(); 
         //listviewattachment.setSelection(myAdapter.getCount()+1); 

       } 
      }); 


      holder.Delete.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View view) { 
        // TODO Auto-generated method stub 
        int tag = (Integer) view.getTag(); 
        if (tag != (myItems.size())) { 
         myItems.remove(tag); 
         Log.d("GCM", "Item removed from " + tag); 
         myAdapter.notifyDataSetChanged(); 

       } 
       } 
      }); 

      return convertView; 
     } 

    } 

    class ViewHolder { 

ImageView image; 
     Button Delete; 
    } 

} 

回答

0

這是因爲在您的getView()中,您不考慮位置。您始終將位圖設置爲image2這是最近的位圖:holder.image.setImageBitmap(image2);

我想你誤解了如何使視圖有效。當notifyDataSetChanged()時,將爲列表中的每個項目調用getView()方法。

的解決辦法是保持在一個列表參考不同的位圖(或其他地方..我只是給一個可能的解決方案),

List<Bitmap> images = new ArrayList<>(); 

當您從結果得到的圖像,將其添加到列表images

image2 = Bitmap.createScaledBitmap(thumbnail, imageWidth , imageHeight, true); 
images.add(image2) 

最後,根據該項目的位置setImageBitmap期間getView()

holder.image.setImageBitmap(images.get(position)); 
+0

感謝阿馬爾亞Khare..you是對我的幫助,這些小問題great..thanks .... :)。 ... – user2768215

相關問題