ListView Items get reset onActivityResult from 2 different activities - android

I have a list view which contains a TextView for each list item. I need to take a picture onItemClick of the listView. onActivityResult of the ACTION_IMAGE_CAPTURE intent and updating the listview , I start another activity for result.
The problem I am facing is that all the textviews in my list view are getting reset when I come back to the activity onActivityResult from the second activity. Can you please help me with this.
This is my onItemClick
public void onItemClick(AdapterView<?> arg0, View v, int index, long arg3) {
selectedIndex = index; //selectedIndex is a class level variable
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = createImageFile();
if (f != null) {
imageFileName = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
}
startActivityForResult(takePictureIntent, 1);
}
}
This is my onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
View v = listView.getChildAt(selectedIndex
- listView.getFirstVisiblePosition());
TextView textView = (TextView) v.findViewById(R.id.textView1);
int quantity = Integer
.parseInt(textView.getText().toString().trim().length() > 0 ? quantityTV
.getText().toString() : getString(R.string._0));
quantity++;
textView.setText(String.valueOf(quantity));
listViewAdapter.notifyDataSetChanged();
Intent intent = new Intent();
intent.setClass(getApplicationContext(), NotificationActivity.class);
intent.putExtra("Value1", "0");
startActivityForResult(intent, 100);
}
else if (requestCode == 100) {
// do nothing
}
}

While you're updating the content of the text view here, you're not updating the data that backs the adapter for your list view. This means when your activity comes back into view (after the second startActivityForResult) it's redrawing itself with the old data.
Instead of updating the view directly, you should update the data that backs the adapter. Something like this; you'll have to modify it to suit your code.
if (requestCode == 1 && resultCode == RESULT_OK) {
List<Integer> adapterData = listViewAdapter.getQuantities();
int quantity = adapterData.get(selectedIndex) + 1;
adapterData.set(selectedIndex, quantity);
listViewAdapter.setQuantities(adapterData);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), NotificationActivity.class);
intent.putExtra("Value1", "0");
startActivityForResult(intent, 100);
}
And in your adapter, you'd have something like this:
public List<Integer> getQuantities() {
return mQuantities;
}
public void setQuantities(List<Integer> quantities) {
mQuantities = quantities;
notifyDataSetChanged();
}

Related

problem i'm getting (random order) after select images from gallery

after select multi images from gallery on order selection the images goes to the recycle view on random order not as I select on specific order or sort. for example if I select B then A then C but the code always bring them with random sort or order like A C B and sometimes C A B. . the order seems undefined at first I thought android sort them based on date and time added to the gallery or what their name i mean alphabet letter but then I realize the order seems undefined. i'm not sure if I need to add listener with array track the user selections. any suggestion
ArrayList imagesUriArrayList;
public static final int slect_photo = 100;
Bitmap bitmap1 = null;
RecyclerView rec;
LinearLayoutManager lnm;
Adopter_Browse list;
ArrayList<MyCard> mylist;
public void Onclick_View(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, slect_photo);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data.getData() != null) {//data.getData() != null) {
imagesUriArrayList = null;
imagesUriArrayList = new ArrayList();
try{
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
imagesUriArrayList.add(data.getClipData().getItemAt(i).getUri());
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
try {
for (int i = 0; i < imagesUriArrayList.size(); i++) {
bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), (Uri) imagesUriArrayList.get(i));
mylist.add(new MyCard(count_s, bitmap1));
}
} catch (IOException e) {
e.printStackTrace();
}
lnm = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
list = new Adopter_Browse(mylist);
rec.setLayoutManager(lnm);
list.notifyDataSetChanged();
rec.setAdapter(list);
}
I found out that using onActivityResult that provided by google will always return the order of your selection on miss , so maybe a bug or need improve .
I got two option :
1- using ItemTouchHelper library ... helped me to solve my problem !
2- gradle source form githup !
I share this maybe some one can get relief !

Identify a specific dynamically generated TextView in order to setText

I have a function that generates a specific number of TextViews dynamically.
TextView tv;
EditText et;
public TextView textViewGenerate(final Activity activity, String tag, Integer id) {
tv = new TextView(activity);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFFFFFF);
gd.setCornerRadius(4);
gd.setStroke(1, 0xFF757575);
tv.setBackground(gd);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
1.0f
);
tv.setPadding(7, 9, 0, 0);
tv.setGravity(Gravity.START);
tv.setTextSize(22);
tv.setTag(tag);
tv.setId(id);
tv.setHint("Enter Module Serial Number");
//Click to launch camera
tv.setClickable(true);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(ct, MctCameraActivity.class);
Intent intent = new Intent(activity, MctCameraActivity.class);
activity.startActivityForResult(intent, 1);
//ct.startActivity(intent);
//ToDo: finish receiving the data from the activityForResult
}
});
lp.setMargins(10, 0, 10, 0);
lp.setMarginStart(10);
lp.setMarginEnd(10);
tv.setLayoutParams(lp);
return tv;
}
}
The onClick launches another activity that loads the camera in order to capture barcode data. In the main activity I create the TextViews with
final LayoutElements le = new LayoutElements();
mainLayout = (LinearLayout)findViewById(R.id.mctScanPageMain);
for(int i = 0; i < 3; i++) {
mainLayout.addView(le.textViewGenerate(this, "NewID" + i, i));
}
The onActivityResult returns the value from the camera activity but the issue is that it sets every generated TextView to have the same barcode number (the barcode number is returned as a string). How can I modify this so that only the text of the selected TextView gets changed in the onActivityResult?
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null) {
String returnResult = data.getStringExtra("result");
for (int i=0; i < mainLayout.getChildCount(); i++){
TextView tv = (TextView) mainLayout.findViewWithTag("NewID"+i);
if(tv == null) {
break;
} else {
tv.setText(returnResult);
}
}
}
}
In your click listener of TextView you can change:
Intent intent = new Intent(activity, MctCameraActivity.class);
activity.startActivityForResult(intent, 1);
to
Intent intent = new Intent(activity, MctCameraActivity.class);
intent.putExtra("text_view_tag", tag);
activity.startActivityForResult(intent, 1);
And then sent it back in result of MctCameraActivity, so you can use it in onActivityResult with getStringExtra. This way you will know tag of TextView which started activity.
Alternatively you can use requestCode that you pass to startActivityForResult to differentiate between text views. For example pass request code 1 for text view 1, request code 2 for text view 2 etc and use this requestCode in onActivityResult.

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);

Call onActivityResult for contact in OnCreate() Android

I got this code from another question but I don't know how to call this onActivityResult() class in my onCreate() activity to display the first contact from my phone. Also, what does "if (requestCode == RQS_PICKCONTACT){" and "RQS_PICKCONTACT" stand for? Could someone please clarify?
public class MainActivity extends Activity {
Button buttonReadContact;
TextView textPhone;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
buttonReadContact.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//Start activity to get contact
/*final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
*/
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK) {
if(requestCode == RQS_PICKCONTACT) {
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if (cursor.moveToNext()) {
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
textPhone.setText("0"+stringNumber);
}
} else {
textPhone.setText("NO Phone Number");
}
} else {
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}
When you call startActivityForResult(intent,requestCode)
onActivityResult is called when user comes back to calling activity with
requestCode
//You can start multiple activities by calling startActivityForResult so this value is to differentiate between them
resultCode
//This value is set by the called activity to indicate whether the intended operation was a success or not.
data
//this is an object of type Intent which contains data returned by called activity.
in your code when this part is executed:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, RQS_PICKCONTACT);
New activity is started and when user comes back from that activity by selecting a contact onActivityResult is called
onActivityResult is called after u startIntent or u select an contact.
RQS_PICK_CONTACT u can change as u want. like 2 , 3,4 or another number.
it just identity for requestCode in onActivityResult so u can do as u need.

Android - Passing database and id through activities

I have 2 android activity's
One where I have a room list, i.e. list of rooms.
The other the room contents. Where all the content of a selected room is displayed.
All I want is for the room id(r_id) to be passed through the room list class into the room overview class where I can retreive all its contents from the database.
I've been trying to figure out where i'm going wrong, I think its around line 94 - 101:
selectedRoom = (String) ((TextView) view).getText();
Cursor c2 = sampleDB.rawQuery("SELECT * FROM tbl_roomDesc WHERE roomName =?", new String[] {selectedRoom});
if (c2 != null ) {
if (c2.moveToFirst()) {
do {
r_id = c2.getString(c2.getColumnIndex("r_id"));
}while (c2.moveToNext());
}
}
c2.close();
Can anyone help me figure out what i'm doing wrong here?
Here is the source for the room list
Here is the source for the room overview
Thanks in advance!
To pass data between to Intents, use the putExtras() method.
Example:
Intent i = new Intent(...);
i.putExtras("roomid", "10");
startActivity(i);
final int roomId = r_id;
next = (ImageButton) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
CreateBuilding.val = "Retrieve";
sampleDB.close();
Intent intent2 = new Intent(RoomList.this, TabLayoutActivity.class);
intent2.putExtra("roomId", roomId);
setResult(RESULT_OK, intent2);
finish();
startActivityForResult(intent2, 0);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
int roomId = data. getIntExtra("roomId", 0);
}
}
}
If I have not misunderstood you put the roomId inside the Intent and retrieve it inside the onActivityResult

Categories

Resources