why the captured image keep on changing? - android

I'm trying to pass captured image and valuefrom C to B, finally to listView A. When the list in Activity A is clicked, it will display the passed image on imageView and values on editText B . But the problem now is the image displayed on Activity B is not from row I have clicked on listview A.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,int position, long id)
{
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM", "");
name = temp[1].trim();
Log.e("TAG", result + "");
if (name.equals("Project"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // image receive from C
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); //display image
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
Activity C
ImageView b;
ok.setOnClickListener(new View.OnClickListener()
{ // return image to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Add image into database
When ok button in Activity A is clicked, I want save all the image todatabase.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
byte[] data=getBitmapAsByteArray(getActivity(),Global.img);// this is a function
SB.insertStaffBenefit(data);
}
}
}
public static byte[] getBitmapAsByteArray(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
Toast.makeText(context, outputStream.size()/1024+"KB", Toast.LENGTH_LONG).show();
return outputStream.toByteArray();
}
1: ListView in A. Values were get fom C and B.
2: Activity B. Assume the list is clicked and intent to B. Noted that the value and image are from Activity C and B.
3: New value and images added and return to A
4: Two list in Activity A now
5: When first list clicked, image changed

You may add bitmap array list (in your Activity A):
ArrayList<Bitmap> m_listBitmapItems = new ArrayList<Bitmap>();
in onItemClick of your listV:
Global.img = m_listBitmapItems.get(position);
in onActivityResult():
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
}
else
{
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}

Related

Pass ListView value to EditText

I have a listView in Activity A as shown below.
When the first list is clicked, it should display 3 on editText. But it displays 5 which was actually getting from the last list.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new
AdapterView.OnItemClickListener() { // when list is pressed, intent to B
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
mClickedPosition = position;
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) { // receive from B
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
// m_listItems.clear();
if (mClickedPosition == -1) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // receive from C
}
Use you ArrayList to extract String at position of ListView like..
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
mClickedPosition = position;
String result = m_listItems.get(position); //add this
result = result.substring(2);
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("result", result); // your intent stuff
}
}
});

How to use different button to access same class?

I have three activity.
A>>B>>C
C>>return image and value to B>>return to A>>If textView not null can intent to B
C has a camera function which will return the image from B to A.
In A, it has one editText and a button. If editText not null, it can be clicked and intent to B by passing the value and image for edit. But the problem now is, when I click the button, I will see the image display on the image view even it is not get the image from c!
I know I can use view.setImageDrawable(null) to clear the image but it cannot work in my case since I access the B two times with different widget!
Activity C
ok.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) //return to B
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive value and image from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img);
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
b.setOnClickListener(new View.OnClickListener() { // back to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
returnIntent.putExtra("c",c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //receive data from B
int button = data.getIntExtra("k1", 0);
if (button == 1) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description=data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as=Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
c.setOnClickListener(new View.OnClickListener() { // if c is not null, it can intent to B.Otherwise it is not clickable
#Override
public void onClick(View view) {
if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
if (name.equals("Project")) {
Intent intent = new Intent(getActivity(), Project1.class);
Global.img = null;
v.setDrawingCacheEnabled(true);
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
intent.putExtra("name", name);
intent.putExtra("result", result);
intent.putExtra("description", description);
if (v.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
startActivity(intent);
}
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity().getApplicationContext(), fk + "", Toast.LENGTH_LONG).show();
AlertDialogRadio(a1);
}
});
public void AlertDialogRadio(final int k) {
final CharSequence[] ClaimsModel = {"B", "Petrol", "Car Maintenance"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), B.class);
intent.putExtra("k",k);
startActivityForResult(intent, 0);
}else{...}
}
In A I have textView and button. If textView is clicked, it should display an image on B imageView. If button is clicked, nothing should display on B imageView. Please help,I have no idea...
So just simply add intent.putExtra("bitmap",true); in the c.setOnClickListener, then add
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getBooleanExtra("bitmap",false))
{
viewImage.setImageBitmap(Global.img);
}
else
{
viewImage.setImageBitmap(null);
}
in onCreate Activity B

Control back button functionality

From the given ListView in picture, I select the contact to send sms and move to another activity (second picture). And from this sms Activity picture. When I press back hardware button available on phone, I should move where I want. I don't want a default Activity to be displayed. How can I do this?
public class SendSms extends Activity{
ListView listView;
List<RowItems> rowItems;
CustomListViewAdapter adapter;
String toNumbers = "";
String separator;
int i=0,j,count=0,count1; String a[]=new String[5];
String number,val2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new4);
listView = (ListView) findViewById(R.id.list);
rowItems = new ArrayList<RowItems>();
val2=getIntent().getStringExtra("name");
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor c = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
// ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
}, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[] { rawContactId }, null);
if (c != null) {
if (c.moveToFirst()) {
String number = c.getString(0);
//int type = c.getInt(1);
String name = c.getString(1);
int photoId = c.getInt(2);
Bitmap bitmap = queryContactImage(photoId);
RowItems p=new RowItems(bitmap, number, name);
rowItems.add(p);
}
adapter = new CustomListViewAdapter(this,
R.layout.new5, rowItems);
listView.setAdapter(adapter);
c.close();
}
}
}
}
private Bitmap queryContactImage(int imageDataRow) {
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {
ContactsContract.CommonDataKinds.Photo.PHOTO
}, ContactsContract.Data._ID + "=?", new String[] {
Integer.toString(imageDataRow)
}, null);
byte[] imageBytes = null;
if (c != null) {
if (c.moveToFirst()) {
imageBytes = c.getBlob(0);
}
c.close();
}
if (imageBytes != null) {
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
} else {
return null;
}
}
public void showResult(View v) {
// String result = "";
String result1="";
for (RowItems p : adapter.getBox()) {
if (p.chck){
// result += "\n" + p.getTitle();
result1 +="\n" +p.getDesc();
a[i]=p.getTitle();
i++;
count++;
}
count1=count;
}
Toast.makeText(this, result1+"\n", Toast.LENGTH_LONG).show();
}
public void send(View v) throws IOException {
int value=a.length-count1;
for(j=0;j<a.length-value;j++){
if(android.os.Build.MANUFACTURER.equalsIgnoreCase("Samsung")){
separator = ",";
} else
separator = ";";
number = a[j];
toNumbers= toNumbers +number +separator;
}
toNumbers = toNumbers.substring(0, toNumbers.length());
Uri sendSmsTo = Uri.parse("smsto:" + toNumbers);
String smsValue = "help iam in danger..i am presently at \n"+val2;
if(val2==null){
Toast.makeText(SendSms.this, "wait.....", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", smsValue);
intent.setData(sendSmsTo);
startActivity(intent);
}
Use startAtctivityForResult, and in onActivityResult check the resultCode. If it is Activity.RESULT_CANCELLED, the user 'backed out' of the SMS activity. Due to the implementation of the SMS activity being outside of your control, this might not be the only case when the result code says it has been cancelled.
I think you should, when the Activity picture is displayed, try to call the onBackPressed method.
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// new intent to call an activity that you choose
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// finish the activity picture
this.finish();
}
If you don't want to call an external Activity, you can hide the layout calling by the Intent as below:
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// your layout with the picture is displayed, hide it
if(MySecondView.getVisibility() == View.VISIBLE)
MySecondView.setVisibility(View.Gone);
// display the layout that you want
MyDefaultView.setVisibility(View.VISIBLE);
}
As I said below, try with a boolean that you initialize to false at the beginning of your Class. When you start the Intent.ACTION_VIEW, make this boolean to true:
public class Foo extends Activity {
private boolean isSms = false;
// some stuff
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
// ...
startActivity(intent);
// make your boolean to true
isSms = true;
// create the onBackPressed method
#Override
public void onBackPressed() {
// check if the user is on the sms layout
if(isSms)
// do something
else
// do something else like finish(); your activity
}
}
Or you can try to use the onKeyDown method (see here: onKeyDown (int keyCode, KeyEvent event)) as below:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0) {
// dome some stuff
return true;
}
return super.onKeyDown(keyCode, event);
}
You can see the diffence between these two methods here: onBackPressed() not working and on the website that I talk in the comments below.
Hope this will be useful.
UPDATE:
A better way should make an startActivityForResult to start the Intent.ACTION_VIEW:
startActivityForResult(intent, 1);
And then, you return the cancel code like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != 1 && resultCode == RESULT_CANCELED) {
// do something
}
}
This is #FunkTheMonk, just above, who tells the good choice!
Add this method to the class to handle device back button.
#Override
public void onBackPressed() {
// do something
}
Please note that it requires API Level 5 or higher.
You have to overide go back behaviour of hardware back button by calling a method name onbackpressed();
#Override
public void onBackPressed() {
super.onBackPressed();
// set intent to activity where you want to move on after back press
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// also clean the current activity from stack.
youractivityname.this.finish();
}

how to replace clicked item in listView with using position or index

I am working on todolist app and I cant handle editing item in listview. Edit button is working like add button.The old item is not deleted. when ı use (ListView.getSelectedItemPosition(),myobject) program gives arrayindexoutofboundsexception.
here EditItem.java
editButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// ArrayList<String> b = new ArrayList<String>();
task = editText1.getText().toString();
priorityLevel = spinner.getSelectedItem().toString();
status = toggleButton.getText().toString();
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear();
date = day + "/" + month + "/" + year;
itemList.setName(task);
itemList.setPriorityLevel(priorityLevel);
itemList.setStatus(status);
itemList.setDueDate(date);
Intent okIntent = new Intent();
okIntent.putExtra("editItem", new DataWrapper(itemList));
setResult(Activity.RESULT_OK, okIntent);
finish();
}
});
and MainActivity.java
todoListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent editIntent = new Intent(MainActivity.this,
EditItem.class);
startActivityForResult(editIntent, EDIT_NOTE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case EDIT_NOTE:
DataWrapper dw2 = (DataWrapper) data
.getSerializableExtra("editItem");
entry = dw2.getEntry();
todoItems.set(todoListView.getSelectedItemPosition(), entry);
todoArrayAdapter.notifyDataSetChanged();
break;
default:
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
You can try give the position from onItemClick in
todoListView.setOnItemClickListener(new OnItemClickListener()
to a global int.
and then do:
todoItems.set(globalInt, entry);

ListView Shows Recent Image taken from camera

In my code when i take image from camera it shows correctly in imageview. But when i take second image, both listview items shows same picture..Old picture replaces with new one..when i take third picture then all of three items show same result.and so on..Please can anyone solve my problem.
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;
}
}
This is because in your getView() you do not consider the position. You always set the bitmap to image2 which is the most recent bitmap: holder.image.setImageBitmap(image2);
I think you misunderstood how get view works. The getView() method is called for each item in the list when you notifyDataSetChanged().
The solution is to keep reference to the different bitmaps in a list (or elsewhere.. i am just giving a possible solution),
List<Bitmap> images = new ArrayList<>();
When you get the image from the result, add it to the images list.
image2 = Bitmap.createScaledBitmap(thumbnail, imageWidth , imageHeight, true);
images.add(image2)
Finally, setImageBitmap based on the position of the item during getView()
holder.image.setImageBitmap(images.get(position));

Categories

Resources