Android, how to update ListView content from external activity? - java

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

Related

Object not being deleted from ListView

I am creating a simple tasklist app in Android Studios.
I have two activities as following (removed imports and package specifications):
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
EditText taskAdd;
Button add;
public ListView tasks;
public Integer pos = 0;
public ArrayList<String> taskArray;
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskAdd = findViewById(R.id.taskAdd);
add = findViewById(R.id.add);
tasks = findViewById(R.id.tasks);
taskArray = FileHelper.readData(this);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, taskArray);
tasks.setAdapter(adapter);
add.setOnClickListener(this);
tasks.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add:
String entered = taskAdd.getText().toString();
if (entered != "" || entered != null || entered != "null") {
adapter.add(entered);
taskAdd.setText("");
FileHelper.writeData(taskArray, this);
Toast.makeText(this, "Task Added!", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos = position;
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivity(intent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
processExtraData();
}
private void processExtraData(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("Value");
if (value == 1) {
taskArray.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Task Removed!", Toast.LENGTH_SHORT).show();
}
}
}
}
Pop.java (a popup)
public class Pop extends Activity implements View.OnClickListener {
Button deleteButton;
Button finishedButton;
Button timerButton;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
deleteButton = findViewById(R.id.deleteButton);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.5),(int)(height*0.5));
deleteButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, MainActivity.class);
i.putExtra("Value", 1);
startActivity(i);
}
}
After I click deleteButton in Pop.java, processExtraData in MainActivity.java is supposed to run. The Toast does appear, but the selected object in the ListView is not deleted. No errors are thrown either. In addition, using Log.d to check the size of taskArray confirmed that this is not just a graphical issue. Why is this the case, and how should I go about fixing it?
Thank you for replying in advance.
The issue is that you are using an object reference instead of a primitive data type, and so when you are calling taskArray.remove(pos), it is looking for pos the object rather than its denoted integer value.
Instead of:
taskArray.remove(pos);
try:
taskArray.remove(pos.intValue());

main activity reads the data again from the firebase database after coming back to the mainactivity

this is my MainActivity
private DatabaseReference mDatabaseReference;
private RecyclerView recyclerView;
private PlaceRecyclerAdapter placeRecyclerAdapter;
private List<Places> placesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Places");
placesList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.action_add)
{
startActivity(new Intent(MainActivity.this,AddPostActivity.class));
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
I am using this RecyclerAdapter to load cardview cards in the main activity
public PlaceRecyclerAdapter(Context context, List<Places> placesList) {
this.context = context;
this.placesList = placesList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Places places = placesList.get(position);
//String imageUrl= null;
holder.place.setText(places.getPlace());
holder.desc.setText(places.getDesc());
//imageUrl= places.getImage();
//todo: Use piccasso library to load images
//Picasso.with(context).load(imageUrl).into(holder.image);
}
#Override
public int getItemCount() {
return placesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView place;
public TextView desc;
//public ImageView image;
public ViewHolder(View view) {
super(view);
place = (TextView) view.findViewById(R.id.postTitleList);
desc = (TextView) view.findViewById(R.id.postDescList);
//image = (ImageView) view.findViewById(R.id.postImageList);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
Places clickedDataItem = placesList.get(pos);
//Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getPlace(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Details.class);
intent.putExtra("NAME", clickedDataItem.getPlace());
intent.putExtra("DESC", clickedDataItem.getDesc());
intent.putExtra("IMG", clickedDataItem.getImage());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
and here is my Details activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
dPlace = (TextView) findViewById(R.id.detail_title);
dDesc = (TextView) findViewById(R.id.detail_desc);
dImage = (ImageView) findViewById(R.id.detail_image);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String name = bundle.getString("NAME");
String desc = bundle.getString("DESC");
String img = bundle.getString("IMG");
dPlace.setText(name);
dDesc.setText(desc);
Picasso.with(this).load(img).into(dImage);
now, clicking on a item in MainActivity I am able to go to the Details activity. suppose there are 3 items in database, and at first main activity shows only 3 items. but after going to Details activity, and then coming back to main activity, there are 6 items, the earlier 3 items are repeated. and if again I go to the Details activity and come back, there will be 9 items. I used (Activity)context).finish(); in RecyclerViewAdapter to finish the main activity, but I think it finishes the context from which I am able to get the details.
please help.
Sorry for my bad english.
Your firebase loading data items needs to go inside onCreate() as it will only gets called only once if its on backstack an onStart() will get called twice. So just implement the data item loading logic in onCreate instead of onStart()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
}
Update
placesList.clear();
placesList.add(places);

How to return data from adapter to activity

I have an activity that contains a RecyclerView and I show some data that comes from server to it. The problem is that I I have set the onCLick of RecyclerView in MYAdapter class but now I need to handle the OnClick of RecyclerView in based on some data which is my Activity which contains RecyclerView.
public class ActivityAllUsers extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listitems;
private static final String URL_DATA = "http://shayea.tk/sof/get_allusers.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int id = getIntent().getIntExtra("IDUSERTYPE", 0);// -1 is default value
recyclerView = (RecyclerView) findViewById(R.id.recyvlerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listitems = new ArrayList<>();
loadRecyclerviewData();
}
private void loadRecyclerviewData()
{
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading...");
dialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
dialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("result");
for (int i =0;i<array.length();i++)
{
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("usr_id"),
o.getString("usr_name"),
o.getString("usr_phone"),
o.getString("usr_email"),
o.getString("usr_status"),
o.getString("prv_name"),
o.getString("org_name")
);
listitems.add(item);
}
adapter = new MyAdapter(listitems , getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
I want to the OnClick of RecyclerView to be available when ever this int id = getIntent().getIntExtra("IDUSERTYPE", 0); id contains 1 and if id contains anything else the OnClick shouldn't be active.
Here is MyAdapter class which contains the OnClick of RecyclerView :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ListItem listItem = listItems.get(position);
holder.txtusername.setText(listItem.getusername());
holder.txtuseremail.setText(listItem.getEmail());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserInformation.class);
intent.putExtra("Details", (Serializable) listItem);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView txtusername;
public TextView txtuseremail;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
txtusername = (TextView) itemView.findViewById(R.id.textviewusername);
txtuseremail = (TextView) itemView.findViewById(R.id.textviewuseremail);
linearLayout = (LinearLayout) itemView.findViewById(R.id.linearlayout);
}
}
}
I need the id which is in ActivityAllUsers ih here :
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserInformation.class);
intent.putExtra("Details", (Serializable) listItem);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
The problem is that I I have set the onCLick of RecyclerView in
MYAdapter class but now I need to handle the OnClick of RecyclerView
in based on some data which is my Activity which contains
RecyclerView.
I think with your requirement, you need to change title: How to return data from adapter to activity
In your adapter, you create callback like this
public interface AdapterCallback{
void onItemClicked(int position);
}
AdapterCallback callback;
public MyAdapter(List<ListItem> listItems, Context context, AdapterCallback callback) {
this.listItems = listItems;
this.context = context;
this.callback = callback;
}
...
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// You can move this block codes to Activity
Intent intent = new Intent(context, UserInformation.class);
intent.putExtra("Details", (Serializable) listItem);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//
// callback here
if(callback != null) {
callback.onItemClicked(position)
}
}
});
And in ActivityAllUsers
public class ActivityAllUsers extends AppCompatActivity implements AdapterCallback {
...
adapter = new MyAdapter(listitems , getApplicationContext(), ActivityAllUsers.this);
...
#Override
public void onItemClicked(int position){
// call back here
}
}
you may pass the value through adapter constructor something like this
adapter = new MyAdapter(listitems , getApplicationContext(), value);
and in your adapter class
int value = -1; //global variable with default value
public MyAdapter(List<ListItem> listItems, Context context, int value) {
this.listItems = listItems;
this.context = context;
this.value = value;
}
and later in onBindViewHolder
if(value == 1) {
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserInformation.class);
intent.putExtra("Details", (Serializable) listItem);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
You can pass the data to the adapter when defining the adapter. Here is an example:
adapter = new MyAdapter(listitems , getApplicationContext(), data you want to send);
To receive, you have to edit the constructor and make it like this:
public MyAdapter(List<ListItem> listItems, Context context, String DataYou WantToReceive)
{
this.listItems = listItems;
this.context = context;
this.data = DataYouWantToReceive
}
Try this,
int id = getIntent().getIntExtra("IDUSERTYPE", 0);
adapter = new MyAdapter(listitems , getApplicationContext(),id);
recyclerView.setAdapter(adapter);
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
private int id;
public MyAdapter(List<ListItem> listItems, Context context,int id) {
this.listItems = listItems;
this.context = context;
this.id=id;
}
.
.
.
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ListItem listItem = listItems.get(position);
holder.txtusername.setText(listItem.getusername());
holder.txtuseremail.setText(listItem.getEmail());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserInformation.class);
intent.putExtra("Details", (Serializable) listItem);
intent.putExtra("ID", id);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
});
}

Android - Adding item to ListView from another Activity

First of all, I've searched on many other posts and still not found a fix for it.
MainActivity contains a ListView and an ImageButton that takes to AddActivity.
This AddActivity has got a EditText (nameAddInput) and a Button(addButton).
Despite clicking this Button, the ListView in MainActivity remains empty... Don't understand why...
Here is the the code of MainActivity:
public class MainActivity extends AppCompatActivity {
static final int PICK_CONTACT_REQUEST = 0;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.itemsList);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(this, R.layout.listview_style1, android.R.id.text1, arrayList);
}
public void onClickAddButton(View view) {
Intent i = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(i, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
addNewItem();
}
}
}
public void addNewItem() {
Bundle addNameInfo = getIntent().getExtras();
if(addNameInfo == null)
return;
String nameInput = addNameInfo.getString("nameInput");
arrayList.add(nameInput);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
In xml file of MainActivity in the ImageButton: android:onClick="onClickAddButton"
The code of AddActivity:
public class AddActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
}
public void backToMain(View view) {
Intent i = new Intent();
EditText nameAddInput = (EditText) findViewById(R.id.nameAddInput);
String userNameText = nameAddInput.getText().toString();
i.putExtra("nameInput", userNameText);
setResult(RESULT_OK, i);
finish();
}
}
In xml file of AddActivity in the Button: android:onClick="backToMain"
Hope someone can help!!
Thank you in advance!!
getIntent() returns you the intent that launched MainActivity, not the one you set in backInMain
Try the "data" variable passed to you in onActivityResult?
Also change to
startActivityForResult(i, PICK_CONTACT_REQUEST);
I'd also suggest you rename that variable 😉
set adapter just in onCreate and just call notifyDataSetChanged in addNewItem method.
the resulting value is returned in the Intent data-Parameter of the onActivityResult function, not in the intent-member of the mainActivity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
addNewItem(data.getExtras().getString("nameInput");
}
}
}
...
public void addNewItem(String newItem)
...

Go back to previous Activity with some `put extra` onClick of a recyclerView Item

I want to pass an data previous activity on click of Item in Recycler view and show it on a Edit Text.
This is the code i have used to pass data from listview to the previous activity
I want to do the same thing with Recyclerview
//Calling Second Activity
public static final int REQUEST_CODE = 100;
Intent dateintent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(dateintent, REQUEST_CODE);
//onClick of listview pass the data back to previous activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.textView);
String str = txt.getText().toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK,intent);
finish();
}
});
//After getting data show the data in the first activity edit box
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String data= data.getStringExtra("data");
if (data!= null) {
edittext.setText(data);
}
}
}
}
First create this Interface
public interface RunnableValue {
public void run(Object obj);
}
2.This MainActivity add
RunnableValue run=new RunnableValue() {
#Override
public Bundle run(Object obj) {
String str = obj.toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK,intent);
finish();
}
};
mAdapter = new SearchAdapter(dataSet,run);
This RecyclerView Adapter
public SearchAdapter(List<String> dataSet,RunnableValue runnableValue) {
mDataSet = dataSet;
this.runnableValue=runnableValue;
}
public static class SearchHolder extends RecyclerView.ViewHolder {
private final TextView textView;
public SearchHolder(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runnableValue.run(getTextView().toString());
}
});
textView = (TextView) v.findViewById(R.id.txtSearchItem);
}
public TextView getTextView() {
return textView;
}
}
Follow the Jacob's solution here. This adds listener for RecyclerView. Then, do the same as you have done in ListView.
There is no setOnItemClickListener available in RecyclerView, so you need make your own click listener in your RecyclerView adaper, just check out the post, then you should be able to make it.
Hope this help!
RecyclerView doesn't have a setOnItemClickListener like its predecessor ListView did. However, that shouldn't prevent us from doing what we want to do. So, we reinvent the wheel and make our very own OnItemClickListener for your RecyclerView. Here's a step by step guide.
Create an interface called OnItemClickListener by creating a new file called OnItemClickListener.java with an empty method called onItemClick.
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
Create a static variable in your adapter called
static OnItemClickListener mItemClickListener;
Setup onClickListener in your custom ViewHolder with a call to our onItemClick method like so
#Override
public void onClick(View view) {
mItemClickListener.onItemClick(view, getPosition());
}
Create a public method called SetOnItemClickListener in your adapter class
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener)
{
this.mItemClickListener = mItemClickListener;
}
SetOnItemClickListener on your custom RecyclerView Adapter
((NameOfYourAdapter) mAdapter).SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(view != null)
{
TextView txt = (TextView) view.findViewById(R.id.textView);
String str = txt.getText().toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK, intent);
//close this Activity...
finish();
}
}
});
That should do it. If you have any questions, feel free to ask!

Categories