How to add items from Edittext to listview? - java

I have been striving for a couple of hours but I still can't figure out why my latest edittext value overwrites my old listview item.
The problem is that, suppose I type a string s1 in my edittext and press the add to listview button, then the string s1 gets entered successfully. Now if I type a string s2 in my edittext and press the add to listview button, the string s2 now replaces s1 in the listview, and thus now it is just showing s2 in my listview. How do I fix this?
Here is my code:
String str=edittext.getText().toString();
List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(My_activity.this, android.R.layout.simple_list_item_multiple_choice, list);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(str.length()!=0) {
list.add(str);
}
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
});
Edit: I am trying to take the input string from one activity and trying to add it to the listview of another activity. This is where the problem arises. Please help me.
1st Activity:
public static String str;
add.setOnClickListener(new (new View.OnClickListener() {
#Override
public void onClick(View view) {
str=edittext.gettext().toString();
}
});
2nd Activity:
List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(My_activity.this, android.R.layout.simple_list_item_multiple_choice, list);
if (Main_activity.i == R.id.event_1 || Main_activity.i == R.id.rem_1) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
if(str.length()!=0) {
list.add(str);
adapter.notifyDataSetChanged();
}
else{
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "No
text found", Snackbar.LENGTH_LONG);
snackbar.show();
}
}

public class ListViewExample extends AppCompatActivity {
List<String> list = new ArrayList<String>();
ListView listView;
EditText editText;
ArrayAdapter<String> adapter;
FloatingActionButton fab
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_view_example);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.listView);
editText = (EditText) findViewById(R.id.et);
fab = findViewById(R.id.fab);
adapter = new ArrayAdapter<String>(ListViewExample.this, android.R.layout.simple_list_item_multiple_choice, list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText.getText().toString().trim();
if(!name.isEmpty()) {
list.add(name);
adapter.notifyDataSetChanged();
editText.setText("");
}
}
});
}
This is my Activity, and this is work for me.

Although the above code is correct, please try to modularize your code. It will make your life easier when comes to debugging it and sequentially follow it. See below
private final List<String> list = new ArrayList<>();
private ArrayAdapter<String> mAdapter;
private EditText editText;
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
public void initViews() {
editText = findViewById(R.id.et);
Button addOptionsBtn = findViewById(R.id.button);
addOptionsBtn.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
addOptionToList();
}
});
mAdapter =
new ArrayAdapter<>(getBaseContext(),
android.R.layout.simple_list_item_multiple_choice,
list);
ListView listView = findViewById(R.id.options_list_view);
listView.setAdapter(mAdapter);
}
private void addOptionToList() {
String option = editText.getText().toString();
if (option.isEmpty()) {
return;
}
list.add(option);
mAdapter.clear();
mAdapter.addAll(list);
mAdapter.notifyDataSetChanged();
}

I've finally found the solution. I guess the adapter wasn't updating after getting a new item. So what I did was:
1st Activity:
public static String str;
add.setOnClickListener(new (new View.OnClickListener() {
#Override
public void onClick(View view) {
str=edittext.gettext().toString();
list.add(s3);
}
});
2nd Activity:
public static List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(My_activity.this, android.R.layout.simple_list_item_multiple_choice, list);
adapter.notifyDataSetChanged();
if (Main_activity.i == R.id.event_1 || Main_activity.i == R.id.rem_1) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
if(str.length()!=0) {
list.add(str);
}
else{
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "No
text found", Snackbar.LENGTH_LONG);
snackbar.show();
}
}

Related

How do i copy an item in an list into a list in another activity?

Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.

Delete a listview item with a button in it self in android studio

As I am very new to java pls help me on this. I have a custom list view in my main activity and a Custom adapter with it. In my every list item there is a delete button that should delete that item when it clicked. I can not remove data from my arraylist when i am inside my custom adapter. Pls helm me in coding this delete button.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText getItem;
Button AddButton;
Button DellButton;
public static ArrayList<String> myData = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView)
findViewById(R.id.listView);
getItem = (EditText) findViewById(R.id.newItem);
AddButton = (Button) findViewById(R.id.AddButton);
MyAdapter adapter = new MyAdapter(this, myData);
list.setAdapter(adapter);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = getItem.getText().toString();
myData.add(result);
adapter.notifyDataSetChanged();
}
});
}
MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, ArrayList<String> records) {
super(context, 0, records);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_custom, parent, false);
}
final TextView lst_txt = (TextView) convertView.findViewById(R.id.list_Txt2);
Button plusbut = (Button) convertView.findViewById(R.id.plusbut);
Button minusbut = (Button) convertView.findViewById(R.id.minusbut);
final TextView sum = (TextView) convertView.findViewById(R.id.sum);
Button cal = (Button) convertView.findViewById(R.id.calButton);
Button delete = (Button) convertView.findViewById(R.id.btnDel);
lst_txt.setText(item);
minusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll - 1;
sum.setText(String.valueOf(sum1));
}
});
plusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll + 1;
sum.setText(String.valueOf(sum1));
}
});
cal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = sum.getText().toString();
Intent intent = new Intent(getContext(), calll.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("sumFL", s);
getContext().startActivity(intent);
}
});
return convertView;
}
}
Please first try to remove object from list by using the position of item with check the validation with list size and then call notifyItemadapter to update the list view.
Use ViewHolder class for all view like textview, button etc. And initialize them inside the condition
if(convert view==null){
Initialize holder object here and
Inflate your layout and
Initialize button like
holder.deletebutton = convert view.findviewbyid from xml
settag(holder)
}
Again get the holdet using the gettag in
else{
//Here
}
Put All click event and text update etc. Outside of above condition
holder.deletbutton.setonclicklistener{
int pos = view.getag
list.remove(pos)
Notifyadapter here
}
holder.deletebutton.settag(position)

When adding Values to Arraylist from one class to another, Listview does not display updated values

I am having one Array list in Class-A and two textfields one from Class-A and other from Class-B,
While adding values to Array List through Class-A textfield it works fine for me,
and when trying to add from Class-B textfield, it gets added to Array list but does not display the updated list in the listview(Blank)
Below is the code i have tried till now
Class-A :-
public static ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
ListView listView;
EditText quickTask;
Button addButton;
Button moreButton;
public static ArrayList<String> addToList( String i ) {
arrayList.add(i);
return arrayList;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
quickTask = (EditText) findViewById(R.id.quicktaskeditText);
listView = (ListView) findViewById(R.id.TasksListView);
arrayAdapter = new ArrayAdapter<String>(ClassA.this, android.R.layout.simple_list_item_1,arrayList);
addButton = (Button) findViewById(R.id.Addbutton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = quickTask.getText().toString();
arrayList.add(task);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
});
moreButton = (Button) findViewById(R.id.moreButton);
moreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent secondActIntent = new Intent(getApplicationContext(),ClassB.class);
startActivity(secondActIntent);
}
});
}
Class-B :-
EditText Title;
Button AddButton;
ArrayList<String> alist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Title = (EditText) findViewById(R.id.Title);
AddButton = (Button) findViewById(R.id.secondAddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = Title.getText().toString();
//Adding text to Class-A arraylist
alist = ClassA.addToList(task);
Intent startIntent = new Intent(getApplicationContext(),ClassA.class);
startActivity(startIntent);
}
});
}
Because you don't notify ListView that contents of ArrayList changed.
You have notifyDataSetChanged only in button listener. You need to add it in Class-A#onResume or in addTolist.

How to update TextView using listView every second [duplicate]

This question already has an answer here:
Display Strings from a listView every second [closed]
(1 answer)
Closed 5 years ago.
I have a simple android application. Inside that app, there is an editText which inputs an item to a listView on button click. Then when a button with onClick ''start'' is clicked, it displays a textView which shows the listview items as a whole.
public class Math extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
TextView displayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_math);
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
displayText = (TextView)findViewById(R.id.displayText);
//displayText is textView that displays list values.
}
public void AddItem(View v) {
//Where items are added to the list
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
items.add(itemText);
etNewItem.setText("");
}
public void start(View v) {
//Where it displays text
RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
lc.setVisibility(View.GONE);
RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
tc.setVisibility(View.VISIBLE);
for (int i = 0; i < items.size(); i++) {
displayText.setText(displayText.getText().toString() + "\n" + items.get(i));
}
}
}
Is there any way that I can display the listView items in displayText one by one every second.
Here is updated code, as per your requirement::
public class Math extends AppCompatActivity {
int listSize=0;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
TextView displayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_math);
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
displayText = (TextView)findViewById(R.id.displayText);
//displayText is textView that displays list values.
}
public void AddItem(View v) {
//Where items are added to the list
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
items.add(itemText);
etNewItem.setText("");
}
public void start(View v) {
//Where it displays text
RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
lc.setVisibility(View.GONE);
RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
tc.setVisibility(View.VISIBLE);
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(count>items.size())
timer.cancel();
else {
displayText.setText(displayText.getText().toString() + "\n" + items.get(count));
}
}
});
}
}, 0, 1000);
}
}
}
I think it will work as per your expectation, if something to change please tell me I will do.
thanks and happy coding.

How to display data entered in one activity in another activity in list one by one in android?

FirstActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Name = etName.getText().toString();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
// Create a bundle object
intent.putExtra("NAME", Name);
startActivity(intent);
}
});
My Second Activity.java is as follows:
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
String UName;
String iName;
ListView lvName;
Button btnBack;
Bundle savedInstanceState;
#Override
protected void onCreate(Bundle b) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
b = getIntent().getExtras();
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
UName=b.getString("NAME");
list.add(UName);
adapter.notifyDataSetChanged();
lvName.setAdapter(adapter);
lvName.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),
ThirdActivity.class);
// Create a bundle object
intent.putExtra("ITEMNAME", item);
startActivity(intent);
}
});
btnBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
}
});
}
My problem is whenever I click on back button, activity is restarted. So that first item in list is overwritten by second item. I want to get the output as list(items one by one) in second activity, whatever the data I enter in first activity. How can I do this?
For example when I enter ABC in edittext its displaying the same data ABC in list.Its good.
But when I click on back button and again enter any data in edittext its not displaying the data as second item in list but it is over writing the first item.This is the thing I wanna get to be solved...
You can put all items into intent in the first activity:
intent.putStringArrayListExtra(ITEMS, list);
And then you can extract them from intent in the second activity:
List<String> items = getIntent().getStringArrayListExtra(ITEMS);
use the extends Application class
public class MyGlobal extends Application {
public ArrayList<String> selectedAppsPackageNames = new ArrayList<String>();
}
for getting this in your activity
private MyGlobal mMyGlobal = (MyGlobal) getApplicationContext();
declare in manifest inside the Application Tag(give the path)
<application
android:name="com.afbb.lockaddicted.core.MyControlList"
..............
.........
</application>
You Just have to create the global list somewhere in your app like you can create Singletone or Application Class where you have to store your username List.
In below code you have to update your arrayList in first activity and you have to get your nameList in SecondActivity
public class MySingleton
{
private static MySingleton _instance;
private ArrayList<String> nameList;
private MySingleton()
{
}
public static MySingleton getInstance()
{
if (_instance == null)
{
_instance = new MySingleton();
}
return _instance;
}
public ArrayList<String> getNameList(){
return nameList;
}
public void setNameList(ArrayList<String> nameList(){
nameList = nameList;
}
}
You can save the names in the FirstActivity to shared preferences, with an id. Then retrieve those values in the SecondActivity. Also do not forget to clear the shared preferences when you destroy your FirstActivity.
FirstActivity
public class FirstActivity extends Activity {
private EditText etName;
private Button btnOk;
private String name;
private int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOK);
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id++;
SharedPreferences.Editor editor = getSharedPreferences("shared_pref", MODE_PRIVATE).edit();
editor.putString(Integer.toString(id), etName.getText().toString());
editor.commit();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences("shared_pref", MODE_PRIVATE).edit().clear().commit();
}
}
SecondActivity
public class SecondActivity extends Activity {
private ArrayList<String> list = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private String UName;
private String iName;
private ListView lvName;
private Button btnBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lvName.setAdapter(adapter);
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", MODE_PRIVATE);
Map<String,String> names = (Map<String, String>) sharedPreferences.getAll();
if(names != null){
for(String value: names.values()){
list.add(value);
}
adapter.notifyDataSetChanged();
}
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}

Categories

Resources