次のコードでは、カメラから画像をキャプチャするか、SD カードから選択すると、画像のサムネイルと削除ボタンがリストボックスに表示されます。formsubmitをクリックすると。SendImages に同じ画像文字列が 2 つ見つかりました。たとえば、1枚の写真を撮ると、同じ写真の2つの文字列がSendImagesに取得されます。チェックするためにファイルを書きました...助けてください...私はひどく立ち往生しています..追跡するのが難しいことは知っていますが、スタックオーバーフローの多くの専門家が私の問題を解決しました...リストビューアイテムを削除すると、1つ削除されます2 つの重複文字列の
public class CustomerRegistrationL0 extends Activity {
int take_image=0; //must be initialized
int UploadFile=1; //must be initialized
static Bitmap thumbnail;
static String encodedImageString;
Bitmap image2;
LayoutInflater mInflater;
private ProgressBar pb;
Uri selectedImage ;
static ListView listviewattachment;
List<Bitmap> images = new ArrayList<Bitmap>();
List<String> StringImages = new ArrayList<String>();
private MyAdapter myAdapter;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
String sendImages;
ProgressDialog dialog = null;
String cnic;
String mobileNo;
String name;
String address;
String nextkin;
String value;
Context c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cr_l0);
Button formSubmit=(Button)findViewById(R.id.buttonSubmit);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
c=this;
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);
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 i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, UploadFile);
}
});
formSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText textcnic=(EditText)findViewById(R.id.EditTextCNIC);
cnic=textcnic.getText().toString();
EditText textmobile=(EditText)findViewById(R.id.editTextMob);
mobileNo=textmobile.getText().toString();
EditText textname=(EditText)findViewById(R.id.editTextName);
name=textname.getText().toString();
EditText textaddress=(EditText)findViewById(R.id.EditTextAdd);
address=textaddress.getText().toString();
EditText textkin=(EditText)findViewById(R.id.EditTextKin);
nextkin=textkin.getText().toString();
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
sendImages=StringImages.toString();
File sdcard = Environment.getExternalStorageDirectory();
try {
File myfile = new File(sdcard,"myfile4.txt");
myfile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myfile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(sendImages);
myOutWriter.close();
Toast.makeText(getBaseContext(), "File Created", Toast.LENGTH_LONG).show();
fOut.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), "COuld not create file", Toast.LENGTH_LONG).show();
}
new MyAsyncTask().execute(cnic,mobileNo,name,address,nextkin,sendImages);
pb.setVisibility(View.VISIBLE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UploadFile && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Bitmap image=(BitmapFactory.decodeFile(picturePath));
cursor.close();
addattachmentsToListView(image);
}
if(resultCode == Activity.RESULT_OK )
{
if (requestCode == take_image) {
//get image
thumbnail = (Bitmap) data.getExtras().get("data");
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
image2 = thumbnail;
addattachmentsToListView(image2);
}
}
}
private void addattachmentsToListView(Bitmap image22) {
// TODO Auto-generated method stub
listviewattachment.setItemsCanFocus(true);
myAdapter = new MyAdapter();
//ListItem listItem = new ListItem();
// myItems.add(listItem);
images.add(image22);
listviewattachment.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
public class MyAdapter extends BaseAdapter {
HashMap<String, String> imageHashMap=new HashMap<String,String>();
private LayoutInflater mInflater;
String key;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// return myItems.size();
return images.size();
}
public Bitmap getItem(int position) {
return images.get(position);
//return myItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
final Bitmap image=(Bitmap)(images.get(position));
//if (position==images.size()){
//image=(Bitmap)getItem(position);
final ViewHolder holder;
if (convertView == null) {
//}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//encode image
// final ArrayList<HashMap<String, String>> imageHashMap=new ArrayList<HashMap<String,String>>();
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
StringImages.add(encodedImageString);
// imageHashMap.put( Integer.toString(position), encodedImageString);
// for(Entry<String, String> entry : imageHashMap.entrySet()) {
// key = entry.getKey();
// value = entry.getValue();
//}
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();
}
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
int imageWidth = factoryOptions.inDensity=70;
int imageHeight = factoryOptions.inDensity=65;
Bitmap Scaled = Bitmap.createScaledBitmap(images.get(position), imageWidth, imageHeight, true);
holder.image.setImageBitmap(Scaled);
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 instance will 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);
ivPreview.setImageBitmap(images.get(position));
btnClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
imgDialog.dismiss();
}
});
imgDialog.show();
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 ((position) != (images.size() )) {
images.remove(images.get(tag));
images.remove(image);
myAdapter.notifyDataSetChanged();
// images.remove((position));
StringImages.remove(position);
}
}
});
return convertView;
}
}
class ViewHolder {
ImageView image;
Button Delete;
}
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String s=postData();
return s;
}
protected void onPostExecute(String result){
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public String postData() {
// Create a new HttpClient and Post Header
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.128.1:8080/ServletParams/AndroidServlet");
String origresponseText="";
try {
// Add your data cnic,mobileNo,name,address,nextkin
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1",cnic));
nameValuePairs.add(new BasicNameValuePair("param2", mobileNo));
nameValuePairs.add(new BasicNameValuePair("param3", name));
nameValuePairs.add(new BasicNameValuePair("param4", address));
nameValuePairs.add(new BasicNameValuePair("param5", nextkin));
nameValuePairs.add(new BasicNameValuePair("param6", sendImages));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
HttpEntity rp = response.getEntity();
origresponseText=readContent(response);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
String responseText = origresponseText.substring(7, origresponseText.length());
return responseText;
}
}
String readContent(HttpResponse response)
{
String text = "";
InputStream in =null;
try {
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
text = sb.toString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (Exception ex) {
}
}
return text;
}
}
Here is a relevant part
最終的な ViewHolder ホルダー。if (convertView == null) {
//}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//encode image
// final ArrayList<HashMap<String, String>> imageHashMap=new ArrayList<HashMap<String,String>>();
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
StringImages.add(encodedImageString);
// imageHashMap.put( Integer.toString(position), encodedImageString);
// for(Entry<String, String> entry : imageHashMap.entrySet()) {
// key = entry.getKey();
// value = entry.getValue();
//}