I want getting a result from an activity, I try to follow the example code,
but startActivityForResult() has been deprecated,
I tried this , but I don't know how to change requestCode
ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
aMemo[requestCode] = it.getStringExtra("memo");
aa.notifyDataSetChanged();
}
}
});
this is my all old code (inculding deprecated method)
public class MainActivity extends AppCompatActivity
implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
String[] aMemo = {
"1. Touch to Edit MEMO",
"2.","3.","4.","5.","6." };
ListView lv;
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.listView);
aa = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, aMemo);
lv.setAdapter(aa);
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(this);
}
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Intent it = new Intent(this, Edit.class);
it.putExtra("number", pos+1);
it.putExtra("memo", aMemo[pos]);
startActivityForResult(it, pos);
}
public boolean onItemLongClick(AdapterView<?> a, View v, int pos, long id) {
aMemo[pos] = (pos+1) + ".";
aa.notifyDataSetChanged();
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent it) {
if(resultCode == RESULT_OK) {
aMemo[requestCode] = it.getStringExtra("memo");
aa.notifyDataSetChanged();
}
}
}
Java
public void openSomeActivityForResult() {
Intent intent = new Intent(this, SomeActivity.class);
someActivityResultLauncher.launch(intent);
}
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
doSomeOperations();
}
}
});
Kotlin
fun openSomeActivityForResult() {
val intent = Intent(this, SomeActivity::class.java)
resultLauncher.launch(intent)
}
var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes
val data: Intent? = result.data
doSomeOperations()
}
}
Related
I want to pick multiple or single images from phone gallery. But my code returning null pointer also one major problem I have notice the createChooser runs twice.
After tries two pick image two time it sends me to the parent activity
OnCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item_business);
ItemName = findViewById(R.id.item_name);
ItemDes = findViewById(R.id.item_des);
pickImage = findViewById(R.id.pickImage);
ChooseImageList = new ArrayList<>();
UrlsList = new ArrayList<>();
pickImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPermission();
PickImageFromGallery();
}
});
}
Checking Permission
private void CheckPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(addItemBusiness.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(addItemBusiness.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
} else {
PickImageFromGallery();
}
}
}
Move to gallery
private void PickImageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select images"), 100);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("result", "inside activity result");
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Log.i("result", "result is ok");
if (data.getClipData() != null) {
Log.i("result", "fine");
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
ImageUri = data.getClipData().getItemAt(i).getUri();
ChooseImageList.add(ImageUri);
SetAdapter();
}
} else if (data.getData() != null) {
Log.i("result", "clip data is null");
ImageUri = data.getData();
ChooseImageList.add(ImageUri);
SetAdapter();
}
}
}
Adapter
private void SetAdapter(){
ViewPagerAdapter adapter = new ViewPagerAdapter(this, ChooseImageList);
viewPager.setAdapter(adapter);
}
Adapter Class
private Context context;
ArrayList<Uri> ImageUrls;
LayoutInflater layoutInflater;
public ViewPagerAdapter(Context context, ArrayList<Uri> imageUrls) {
this.context = context;
ImageUrls = imageUrls;
layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return ImageUrls.size();
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view=layoutInflater.inflate(R.layout.show_imgaes_layout,container,false);
ImageView imageView=view.findViewById(R.id.UploadImage);
imageView.setImageURI(ImageUrls.get(position));
container.addView(view);
return view ;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view== object;
}
#Override
public void destroyItem(#NonNull View container, int position, #NonNull Object object) {
((RelativeLayout)object).removeView(container);
}
Hope that you can find the issue. Thank you
I want to return the data from second activity to first activity using intent when click the OnAddClicked button in second activity, but what I done was not working. The data that I return to first activity is null and I have no idea about this. Can anyone help me to solve this problem?
First Activity:
public class CartView extends AppCompatActivity {
ActivityCartViewBinding binding;
public CartView.MyClickHandler handler;
GridView view_listView;
String Default_curr;
String itemgroup;
String itemtype;
String uprice;
String quantity;
ACDatabase db;
List<AC_Class.Item> s_item = new ArrayList<>();
AC_Class.InvoiceDetails invoiceDetails;
AC_Class.Item item;
String substring = "";
EditText searchEditText;
Button All;
Button Type;
Button Group;
ArrayAdapter<String> adapter;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_cart_view);
// Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Catalog");
actionBar.setDisplayHomeAsUpEnabled(true);
searchEditText = (EditText) findViewById(R.id.searchField);
UIUtil.hideKeyboard(this);
UIUtil.showKeyboard(this, searchEditText);
db = new ACDatabase(this);
invoiceDetails = new AC_Class.InvoiceDetails();
item = new AC_Class.Item();
handler = new MyClickHandler(this);
binding.setHandler(handler);
All = (Button) findViewById(R.id.button1);
Type = (Button) findViewById(R.id.button2);
Group = (Button) findViewById(R.id.button3);
view_listView = (GridView) findViewById(R.id.GridView);
All.setVisibility(View.GONE);
Type.setVisibility(View.GONE);
Group.setVisibility(View.GONE);
getData("");
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
#Override
public void afterTextChanged(Editable s) {
getData(s.toString().trim());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ctlg_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
/*if (id == android.R.id.home)
{
onBackPressed();
return true;
}*/
if (id == R.id.cart)
{
Intent new_intent = new Intent(CartView.this, CartList.class);
new_intent.putExtra("invoiceDetail", invoiceDetails);
startActivityForResult(new_intent,3);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
getData("");
}
public void getData(String substring) {
Cursor data = db.getItemLike(substring, 0);
if (data.getCount() > 0){
s_item.clear();
while (data.moveToNext()) {
try {
AC_Class.Item item = new AC_Class.Item(data.getString(0), data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5), data.getString(6), data.getString(7), data.getString(8), data.getFloat(9), data.getFloat(10), data.getFloat(11), data.getFloat(12), data.getFloat(13), data.getFloat(14), data.getString(15), data.getString(16), data.getFloat(17), data.getString(18),data.getFloat(19),data.getFloat(20));
s_item.add(item);
} catch (Exception e) { Log.i("custDebug", "error reading image: "+e.getMessage()); }
}
CartViewListAdapter arrayAdapter = new CartViewListAdapter(this, s_item);
view_listView.setAdapter(arrayAdapter);
Cursor dcurren = db.getReg("6");
if(dcurren.moveToFirst()){
Default_curr = dcurren.getString(0);
}
view_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemcode = ((AC_Class.Item)parent.getItemAtPosition(position)).getItemCode();
String uom = ((AC_Class.Item)parent.getItemAtPosition(position)).getUOM();
AC_Class.Item sa =((AC_Class.Item) parent.getItemAtPosition(position));
//Intent item_intent = new Intent();
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//setResult(4, item_intent);
startActivity(item_intent);
//finish();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == 1) {
itemtype = data.getStringExtra("TypeKey");
if (itemtype != null) {
getTypedata();
}
}
break;
case 2:
if (resultCode == 1) {
itemgroup = data.getStringExtra("GroupKey");
if(itemgroup != null){
getGroupdata();
}
}
break;
case 3:
if (resultCode == 1) {
AC_Class.Item i = data.getParcelableExtra("Item");
uprice = data.getStringExtra("Price");
quantity = data.getStringExtra("Quantity");
if (i != null) {
invoiceDetails.setItemCode(i.getItemCode());
invoiceDetails.setItemDescription(i.getDescription());
invoiceDetails.setUPrice(Double.valueOf(i.getPrice()));
invoiceDetails.setUOM(i.getUOM());
//invoiceDetails.setUPrice(Double.valueOf(uprice));
invoiceDetails.setQuantity(Double.valueOf(quantity));
}
}
break;
}
}
}
SecondActivity:
public class ItemDetail extends AppCompatActivity {
ActivityItemDetailBinding binding;
AC_Class.Item items;
AC_Class.ItemUOM itemuom;
AC_Class.Cart cart;
AC_Class.InvoiceDetails invoiceDetails;
ACDatabase db;
String Item;
String ItemUOM;
String Default_curr;
Intent pintent;
EditText etQty;
String default_loc;
List<AC_Class.Item> c_item = new ArrayList<>();
MyClickHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_item_detail);
itemuom = new AC_Class.ItemUOM();
items = new AC_Class.Item();
invoiceDetails = new AC_Class.InvoiceDetails();
cart = new AC_Class.Cart();
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
db = new ACDatabase(this);
pintent = getIntent();
//substring = pintent.getStringExtra("substring");
Item = pintent.getStringExtra("ItemKey");
ItemUOM = pintent.getStringExtra("ItemUOMKey");
handler = new MyClickHandler(this);
binding.setHandler(handler);
Cursor loc = db.getReg("7");
if(loc.moveToFirst()){
default_loc = loc.getString(0);
}
items = pintent.getParcelableExtra("Items");
binding.setItem(items);
binding.setInvoicedetail(invoiceDetails);
binding.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
etQty = (EditText)findViewById(R.id.quantity);
String qty = etQty.getText().toString();
if(qty.length() > 0)
{
invoiceDetails.setQuantity(Double.valueOf(qty));
//Calculation();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
onBackPressed();
return true;
}
}
return super.onOptionsItemSelected(item);
}
public class MyClickHandler {
Context context;
public MyClickHandler(Context context) {
this.context = context;
}
public void OnAddClicked(View view) {
//Intent new_intent = new Intent(context, CartList.class);
Intent new_intent = new Intent(context,CartView.class);
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(1, new_intent);
finish();
}
}
}
OnAddClicked your are finishing the activity when it goes to next activity previous activity goes to end....so remove the finish();
First thing first, to get result from other activity, you need to Use startActivityForResult method instead of startActivity.
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//startActivity(item_intent);
startActivityForResult(item_intent,REQUST_CODE);
and for setting result
Intent new_intent = new Intent();
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(Activity.RESULT_OK, new_intent);
finish();
and to receive result use below code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(REQUST_CODE==requestCode && resultCode==Activity.RESULT_OK){
// do logical stuff.
}
}
I have two activities and the second activity should send back a string of text to the appropriate textview on activity 1 depending on if I select button 1 or button 2. I believe my intent in launchFoodActivity() in activity 1 is incorrectly asking for 2 requests at the same time. How can I correct my code to have each string of text be sent to the appropriate textview in activity 1?
Activity 1
public class MainActivity extends AppCompatActivity {
private TextView mReplyTextView1;
private TextView mReplyTextView2;
public static final int TEXT_REQUEST = 1;
public static final int TEXT_REQUEST2 = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mReplyTextView1 = findViewById(R.id.food_text_1);
mReplyTextView2 = findViewById(R.id.food_text_2);
}
public void launchFoodActivity(View view) {
Intent intent = new Intent(this, FoodListActivity.class);
startActivityForResult(intent, TEXT_REQUEST);
Intent intent2 = new Intent(this, FoodListActivity.class);
startActivityForResult(intent2, TEXT_REQUEST2);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String textFoodReply1 = data.getStringExtra(FoodListActivity.EXTRA_REPLY);
mReplyTextView1.setText(textFoodReply1);
break;
}
}
case 2:
if (requestCode == 2) {
if (resultCode == RESULT_OK) {
String textFoodReply2 = data.getStringExtra(FoodListActivity.EXTRA_REPLY);
mReplyTextView2.setText(textFoodReply2);
break;
}
}
}
}
}
Activity 2
public class FoodListActivity extends AppCompatActivity {
public static final String EXTRA_REPLY = "com.dev20.shoppinglist.extra.REPLY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list);
}
public void returnFoodItem1(View view) {
String replyItem1 = getResources().getString(R.string.cheese_text);
Intent replyIntent = new Intent();
replyIntent.putExtra(EXTRA_REPLY, replyItem1);
setResult(RESULT_OK, replyIntent);
finish();
}
public void returnFoodItem2(View view) {
String replyItem2 = getResources().getString(R.string.apples_text);
Intent replyIntent2 = new Intent();
replyIntent2.putExtra(EXTRA_REPLY, replyItem2);
setResult(RESULT_OK, replyIntent2);
finish();
}
}
I Have code which is defined for image (drawable )
Means Image is are already defined but I want user to select Image from Gallery .
SO first I want to get all Images from gallery and then it is show in view and from their user can select Image .
So it means all Images must be saved in array like below .
Any Help for this.
public class StickerSelectActivity extends AppCompatActivity {
public static final String EXTRA_STICKER_ID = "extra_sticker_id";
private final int[] stickerIds = {
R.drawable.abra,
R.drawable.bellsprout,
R.drawable.bracelet,
R.drawable.bullbasaur,
R.drawable.camera,
R.drawable.candy,
R.drawable.caterpie,
R.drawable.charmander,
R.drawable.mankey,
R.drawable.map,
R.drawable.mega_ball,
R.drawable.meowth,
R.drawable.pawprints,
R.drawable.pidgey,
R.drawable.pikachu,
R.drawable.pikachu_1,
R.drawable.pikachu_2,
R.drawable.player,
R.drawable.pointer,
R.drawable.pokebag,
R.drawable.pokeball,
R.drawable.pokeballs,
R.drawable.pokecoin,
R.drawable.pokedex,
R.drawable.potion,
R.drawable.psyduck,
R.drawable.rattata,
R.drawable.revive,
R.drawable.squirtle,
R.drawable.star,
R.drawable.star_1,
R.drawable.superball,
R.drawable.tornado,
R.drawable.venonat,
R.drawable.weedle,
R.drawable.zubat
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_sticker_activity);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.stickers_recycler_view);
GridLayoutManager glm = new GridLayoutManager(this, 3);
recyclerView.setLayoutManager(glm);
List<Integer> stickers = new ArrayList<>(stickerIds.length);
for (Integer id : stickerIds) {
stickers.add(id);
}
recyclerView.setAdapter(new StickersAdapter(stickers, this));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onStickerSelected(int stickerId) {
Intent intent = new Intent();
intent.putExtra(EXTRA_STICKER_ID, stickerId);
setResult(RESULT_OK, intent);
finish();
}
class StickersAdapter extends RecyclerView.Adapter<StickersAdapter.StickerViewHolder> {
private final List<Integer> stickerIds;
private final Context context;
private final LayoutInflater layoutInflater;
StickersAdapter(#NonNull List<Integer> stickerIds, #NonNull Context context) {
this.stickerIds = stickerIds;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public StickerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new StickerViewHolder(layoutInflater.inflate(R.layout.sticker_item, parent, false));
}
#Override
public void onBindViewHolder(StickerViewHolder holder, int position) {
holder.image.setImageDrawable(ContextCompat.getDrawable(context, getItem(position)));
}
#Override
public int getItemCount() {
return stickerIds.size();
}
private int getItem(int position) {
return stickerIds.get(position);
}
class StickerViewHolder extends RecyclerView.ViewHolder {
ImageView image;
StickerViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.sticker_image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
if (pos >= 0) { // might be NO_POSITION
onStickerSelected(getItem(pos));
}
}
});
}
}
}
}
Its not required If you want to show all available images in gallery in your application. You can use
private Cursor cc = null;
cc = this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
null)
This will give you a connection with files available in gallery. More detailed answer is here
How to implement Image Gallery in Gridview in android?
If In case in your application you have an image view and you want your user to click on the image and then Android should ask if they want to select an image from gallery/camera you can follow this, You can call selectImage method on setOnClickListener on ImageView.
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Update Profile Photograph");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(getActivity());
if (items[item].equals("Take Photo")) {
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
if(result)
galleryIntent();
}
}
});
builder.show();
}
private void cameraIntent() {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, familyMemberId + ".png");
Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePicture, 0);
}
private void galleryIntent() {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == Activity.RESULT_OK){
File out = Environment.getExternalStorageDirectory();
out = new File(out, familyMemberId + ".png");
Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
Toast.makeText(getContext(), photoURI.toString(), Toast.LENGTH_LONG).show();
imageUri = photoURI.toString();
Glide.with(this).load(imageUri).into(familyMemberProfilePick);
}
break;
case 1:
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageUri = selectedImage.toString();
Glide.with(this).load(imageUri).into(familyMemberProfilePick);
}
break;
}
}
Please don't forget add these in
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application ...
<provider
android:name=".utility.GenericFileProvider"
android:authorities="${applicationId}.app.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
....
</application>
I have a project with 4 classes: 2 activities, 1 adapter and 1 class for simple object. Names of the classes are: MainActivity, AddingItemsActivity, ItemAdapter, SimpleItem. In a layout corresponding to the MainActivity, there is a list view named SimpleListView. SimpleListView should contain SimpleItem objects. ItemAdapter is made to handle SimpleListView. Updating, adding items to SimpleListView from MainActivity is very easy. What I would like to reach is updating, adding items, which appear on the SimpleListView, from AddingItemsActivity (appear when user come back to the MainActivity). Could you tell me what should I do to reach that?
PS: I would like to ask: "how to update SimpleListView from AddingItemsActivity?" but I have read that it is not proper question, beacuse SimpleListView does not exist in AddingItemsActivity.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button toAddingActivity = findViewById(R.id.toAddingActivitybutton);
final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivity(intent);
}
});
}
}
AddingItemsActivity
public class AddingItemsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
Button addItem = findViewById(R.id.AddItembutton);
// final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
// final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// first reflex try, which does not work:
// SimpleItem item = new SimpleItem("String number 1", "String number 2");
// mAdapter.add(item);
// simpleItemsListView.setAdapter(mAdapter);
}
});
}
}
ItemAdapter
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
public ItemAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ItemAdapter(Context context, int resource, List<SimpleItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.simple_item_adapter, null);
}
SimpleItem item = getItem(position);
if (item != null) {
TextView tv1 = v.findViewById(R.id.adapterTextView1);
TextView tv2 = v.findViewById(R.id.adapterTextView2);
tv1.setText(item.getStr1());
tv2.setText(item.getStr2());
}
return v;
}
}
SimpleItem
public class SimpleItem {
private String str1;
private String str2;
public SimpleItem(String s1, String s2)
{
str1 = s1;
str2 = s2;
}
public String getStr1()
{
return str1;
}
public String getStr2()
{
return str2;
}
}
Use startActivityForResult to get the result as SimpleItem from AddingItemsActivity.
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivityForResult(intent,1);
Create a SimpleItem in AddingItemsActivity, add values to it and use setResult to give simple item instance back to MainActivity
// inside on click
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("result", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();`
In MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
SimpleItem result = (SimpleItem)data.getSerializableExtra("result");
// add result to the list, used by adapter
// notify adapter using notifyDataSetChanged
}
}
}//onActivityResult
Note : add public class SimpleItem implements Serializable and seems like you forgot to create and pass list to adapter instances, so simply create it
your adaper is not complete you must override getCount method and set your list.size() to it . then from your MainActivity you mast create a list of simle item and pass it to your adapter .
ArrayList<SimpleItem> items=new ArrayList<>();
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter,items);
then you can put your list to intent and pass it to AddingItemsActivity .
Intent intent=new Intent (this,AddingItemsActivity.class);
intent.putExtra("Key",items);
startActivityForResult(intent,your request code (exam : 14));
and in AddingItemsActivity :
Bundle bundel=getIntent().getExtras();
ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)bundle.get("Key");
change or add items to list and return it to MainActivity :
Intent returnIntent = new Intent();
returnIntent.putExtra("returnedList", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
and in onActivityResult of MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14) {
if(resultCode == Activity.RESULT_OK){
// ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
mAdapter .notifyDataSetChanged();
}
}
}
And dont forgot implemens your simpleItem class of Serializable
try this :
MainActivity :
public class MainActivity extends AppCompatActivity {
private ArrayList<SimpleItem> items = new ArrayList<>();
private Button toAddingActivity;
private ListView simpleItemsListView;
private ItemAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toAddingActivity = (Button) findViewById(R.id.toAddingActivitybutton);
simpleItemsListView = (ListView) findViewById(R.id.SimpleListView);
mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter, items);
simpleItemsListView.setAdapter(mAdapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddingItemsActivity.class);
startActivityForResult(intent, 14);
}
});
mAdapter.notifyDataSetChanged();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14 && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
SimpleItem item=(SimpleItem) bundle.get("reKey");
items.add(item);
mAdapter.notifyDataSetChanged();
}
}
}
ItemAdapter :
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
private ArrayList<SimpleItem> items =new ArrayList<>();
private Activity activity;
private int layoutResource;
public ItemAdapter(#NonNull Activity act, int resource, #NonNull ArrayList<SimpleItem> data) {
super(act, resource, data);
items =data;
activity=act;
layoutResource=resource;
}
#Override
public int getCount() {
return items.size();
}
#Override
public SimpleItem getItem(int position) {
return items.get(position);
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
View row=convertView;
if(row==null || (row.getTag()==null)){
LayoutInflater inflater=LayoutInflater.from(activity);
row=inflater.inflate(layoutResource,null);
holder=new ViewHolder();
holder.tv1=row.findViewById(R.id.adapterTextView1);
holder.tv2=row.findViewById(R.id.adapterTextView2);
row.setTag(holder);
}else {
holder=(ViewHolder)row.getTag();
}
holder.simpleItem=items.get(position);
holder.tv1.setText(holder.simpleItem.getStr1());
holder.tv2.setText(holder.simpleItem.getStr2());
return row;
}
class ViewHolder{
TextView tv1;
TextView tv2;
SimpleItem simpleItem;
}
}
AddingItemsActivity :
public class AddingItemsActivity extends AppCompatActivity{
private Button addItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
addItem=(Button)findViewById(R.id.AddItembutton);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("reKey",item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
}
you can change AddingItemsActivity onclick method