Excuse me, but i somehow cant post comments for the answers, so i have to write my own here
I need to get String data from custom ListView (consist of EditText and ImageView).
Here is my code:
First, i declare my own copy of ArrayList
private ArrayList<EditText> m_edit = null;
Second, i initialize it inside onCreate method of my Activity
public void onCreate(Bundle savedInstanceState) {
...
m_edit = new ArrayList<EditText>();
...
Third, i fill my ArrayList with EditText copies and then add them to ListView using ArrayAdapter
fieldAddButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view){
EditText et = new EditText(AddCategory.this);
m_edit.add(et);
m_adapter.notifyDataSetChanged();
}
});
Fourth, i want to get EditText value for any item in my custom ListView. So i do something like this:
for (int i = 0;i<m_edit.size();i++){
_string = m_edit.get(i).getText().toString();
}
And there is problem: result is always ""
What am i doing wrong?
My class source code
import android.app.Activity;
import android.widget.Toast;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
import android.view.*;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class AddCategory extends Activity {
private ArrayList<EditText> m_edit = null;
private EditAdapter m_adapter;
private EditText categoryName;
private MyDbAdapter dbAdapter;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcategory);
final Button categoryAddButton = (Button)findViewById(R.id.CategoryAddButton);
final Button fieldAddButton = (Button)findViewById(R.id.FieldAddButton);
final ListView fieldList = (ListView)findViewById(R.id.CategoryFieldList);
categoryName = (EditText)findViewById(R.id.CategoryNameEdit);
m_edit = new ArrayList<EditText>();
this.m_adapter = new EditAdapter (this, R.layout.categoryfieldlayout, m_edit);
fieldList.setAdapter(m_adapter);
dbAdapter = new MyDbAdapter(this);
context = getApplicationContext();
dbAdapter.open();
fieldAddButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view){
EditText et = new EditText(AddCategory.this);
m_edit.add(et);
m_adapter.notifyDataSetChanged();
}
});
categoryAddButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view){
int duration;
String error;
long categoryID;
;
int errCount = 0;
if (!categoryName.getText().toString().equals("")){
for (int i = 0;i<m_edit.size();i++){
if (m_edit.get(i).getText().toString().equals("")){
errCount++;
}
}
if (errCount != 0){
GroupItem group = new GroupItem(categoryName.getText().toString());
categoryID = dbAdapter.insertGroup(group);
for (int i = 0;i<m_edit.size();i++){
FieldItem field = new FieldItem(m_edit.get(i).getText().toString());
duration = Toast.LENGTH_SHORT;
error = m_edit.get(i).getText().toString();
Toast.makeText(context, error, duration).show();
}
}
else{
duration = Toast.LENGTH_SHORT;
error = "Field cannot be empty";
Toast.makeText(context, error, duration).show();
}
}
else{
duration = Toast.LENGTH_SHORT;
error = "Name cannot be empty";
Toast.makeText(context, error, duration).show();
}
}
});
}
private class EditAdapter extends ArrayAdapter<EditText>{
private ArrayList <EditText> items;
public EditAdapter(Context context, int textViewResourceId, ArrayList<EditText> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.categoryfieldlayout, null);
}
EditText et = (EditText)v.findViewById(R.id.fieldEdit);
return v;
}
}
}
When i update (write some text) EditText field of my custom listView item, i think, m_edit dont update its content automaticaly. So the problem is, how to force that update
ps. sorry for my poor english
From the code below, I guess you are going wrong by getting text from an ArrayList and not your EditText field.
m_edit = new ArrayList<EditText>();
for (int i = 0;i<m_edit.size();i++) {
_string = m_edit.get(i).getText().toString();
}
Simply set a ListView onClickListener and you will get the Edittext value for each listview item you click. In your case...
final ListView fieldList = (ListView)findViewById(R.id.CategoryFieldList);
fieldList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
EditText et = (EditText)v.findViewById(R.id.fieldEdit);
String myText = et.getText().toString();
Toast.makeText(getApplicationContext(), myText , Toast.LENGTH_SHORT).show();
}
});
can you provide you code snippets so get more idea what you are doing with edittext Arraylist.
From this i can see that you are adding edittext in arraylist and refreshing your listview. but did your listview refreshed with added edittext or not? Then that is the main problem with your code.
thanks for your source,
I think you are using listview and on button click you are trying to get edittext value. but how can you know that which position view is got selected from the listview.
I think there is some problem in what you are asking and what you doing. i think what you are doing is on single button click you try to get all edittext value.
You are getting blank value because in your listview you have not edited it..you can do it something like this.
Inside your adapter getview method put this code
public View getView(final int position, View convertView, ViewGroup parent) {
ed.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) {
}
#Override
public void afterTextChanged(Editable s) {
list.get(position).edittext.setText(ed.getText().toString())
}
});
}
Hope this may help you.
Related
In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView.
There are a number of problems with his code.
1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews.
2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done.
I want the list to be automatically updated when new data is entered rather than over writing it.
3) The data vanishes away when i restart the app. I want the data to be saved permanently.
Code for Custom Adapter is:
package com.example.sakshi.dialogsandmenus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Data> list;
private LayoutInflater mLayoutInflator;
public CustomAdapter(Context context, ArrayList list){
this.context=context;
this.list=list;
mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
dob.setText(list.get(position).getDate());
return convertView;
}
}
Code for Main Activity is:
package com.example.sakshi.dialogsandmenus;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.R.id.list;
import static com.example.sakshi.dialogsandmenus.R.id.date;
public class MainActivity extends AppCompatActivity{
ListView listview;
ArrayList<Data> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.list_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==R.id.add){
filldialog();
}
return super.onOptionsItemSelected(item);
}
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
arrayList = new ArrayList<>();
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
//customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
}
}
1) you have to convert the value of age to String before setText
//age.setText(list.get(position).getAge());
age.setText(Integer.toString(list.get(position).getAge()));
2) Every time new Arraylist initilaization
intarrayList = new ArrayList<>();
ArrayList arrayList = new ArrayList<>();
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
enter code here
3) Use Sqlite or anyStorage Option for data saving
You are setting int value directly to setText of ageTextView. You need to convert int to String before you setting a text to TextView.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
age.setText(String.valueOf(list.get(position).getAge())); // use this it will work
dob.setText(list.get(position).getDate());
return convertView;
}
}
Move these lines outside the onClickListener
arrayList = new ArrayList<>();
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
Because whenever you are clicking the button arraylist is initializing again.
This is my first app and i'm having some problem whit ListView
How can I get the ID in the database after clicking on a Item?
I can't use position because the Id may not be continuous and even if it is in order sometimes does not return the correct Id any.
this is my code, Thank you for your help:
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", position);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
There are a lot of solution approaches.
For example, you can store of Id's if ArrayList before ListView initialization.
That is, execute "SELECT id FROM mytable"
Then store in arraylist and use while click method.
Example:
//in class declaration
private ArrayList<Long> ar_ids = new ArrayList<Long>;
//
String sql = "SELECT id FROM table";
Cursor cur = db.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
}
}
cur.close();
for click event:
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", ar_id.get(position));
//this is awsome!
startActivity(i);
}
and initialize this something like:
private void myfunc() {
String sql = "SELECT id FROM table";
Cursor cur = myDb.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
throw new NullPointerException();
}
}
cur.close();
}
private void populateListView(){
myfunc();
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
well instead of using the ArrayAdapter you can extend a BaseAdapter or ListAdapter or even the ArrayAdapter to make your custom adapter. First of all make a plain java class to map your database data including id to an object. Then make a custom BaseAdapter instead of using the ArrayAdapter. In your BaseAdapter class you have to override various methods including getItem and getItemId methods. Now you can return the whole mapped object from the getItem method and simply obtain the object of selected item of the ListView by using listView.getSelectedItem() method in the Activity or Fragment class. Once you get the object you can access the id easily.
You can find a good example and explanation of a custom adapter here
About mapping the database result to an object, you can get some concept here
Here, you can replace you code class with this one, I have added a cursorAdapter and attached it with your ListView, in adapter I have added a method for getting Id that I call from click listener to retrieve id from cursor, you will have to set column number for _ID in public void getId(int position) from MyCursorAdapter class below.
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
private MyCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
//retrieve id from cursor
int _id = adapter.getId(position)
i.putExtra("id", _id);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
adapter = new MyCursorAdapter(this, res, 0);
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setAdapter(adapter);
}
//adapter for list view
class MyCursorAdapter extends CursorAdapter {
Cursor cursor;
// Default constructor
public MyCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
this.cursor = cursor;
}
public void bindView(View view, Context context, Cursor cursor) {
String text = cursor.getString(1);
//make sure the TextView id is "#+id/text1" in da_item.xml
TextView tvText = (TextView) view.findViewById(R.id.text1);
tvText.setText(text);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflator inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
return Inflater.inflate(R.layout.da_item, parent, false);
}
public int getId(int position){
cursor.moveToPosition(position);
int colId = //set id column number here
int id = cursor.getLong(colId);
return id;
}
}
Since the code is untested, you might face a build issue in start, but it should give an idea of what's going on in code. feel free to ask any question if you face any problem in compilation
This is the first question I am posting. Here is my question and below given is the debugged code from android studio.
Here, I have tried to extract the data by taking the data from the adapter into the mainActvity, but I failed as the app is crashing on Clicking the save button. Here the data is nothing but and object.
MainActivity :
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ListItem_Elements> testsList;
int n=5;//No. of tests
Button btn_save;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
btn_save= (Button)findViewById(R.id.btn_save);
//CustomAdapter adapter;
Resources res=getResources();//Takes the resource permission required to show ListView
testsList= new ArrayList<ListItem_Elements>();
testsList = SetList();
adapter= new CustomAdapter(this, testsList, res);
listView.setAdapter(adapter);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(testsList!=null)
saveValues();
}
});
}
public ArrayList<ListItem_Elements> SetList() {
/*Enter the Test names*/
ArrayList<ListItem_Elements>tests_Array= new ArrayList<ListItem_Elements>();
for(int i=0;i<5;i++) {
ListItem_Elements e = new ListItem_Elements();
e.setTest("XYZ");
e.setResult(null);
tests_Array.add(e);
}
return tests_Array;
}
ArrayList<ListItem_Elements>ar= new ArrayList<>();
public void saveValues() {
if(adapter.extractedArray!=null) {
ar = adapter.extractedArray;
Toast.makeText(MainActivity.this, ar.size(), Toast.LENGTH_SHORT).show();
}
}
}
--------------------------------------------------------------------------------
CustomAdapter :
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList<ListItem_Elements> extractedArray= new ArrayList<ListItem_Elements>();
private ArrayList<ListItem_Elements> array;
//Declaration of ArrayList which will be used to recieve the ArrayList that has to be putup into the ListView
private LayoutInflater inflater; //To Instantiates a layout XML file into its corresponding View
Resources res;
//protected String bridgeValue;
CustomAdapter(Activity a, ArrayList<ListItem_Elements> b, Resources resLocal) {
activity = a;
array= b;
res = resLocal;
//Initialization of inflater to link the layout of list items
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CustomAdapter() {
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
// keeping references for views we use view holder
public static class ViewHolder {
/*Declaration of elements of layout of list items in the class for future use of putting up
data onto the List View*/
TextView textView;
EditText editText;
}
#Override
//Here views were bound to a position
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
// if a view is null(which is for the first item) then create view
if (convertView == null) {
vi = inflater.inflate(R.layout.layout_items, null);
// Taking XML files that define the layout of items, and converting them into View objects.
holder = new ViewHolder();//Stores the elements of the layout of list items
/*Initializing the elements of the layout of list item*/
holder.textView = (TextView) vi.findViewById(R.id.textView);
holder.editText = (EditText) vi.findViewById(R.id.editText);
vi.setTag(holder);
//Stores the view(layout of list item) into vi
}
//else if it already exists, reuse it(for all the next items). Inflate is costly process.
else {
holder = (ViewHolder) vi.getTag();
//Restores the already exisiting view in the 'vi'
}
/*Setting the arrayList data onto the different elements of the layout of list item*/
try {
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
}
catch (Exception e) {
e.getMessage();
}
return vi;//Returns the view stored in vi i.e contents of layout of list items
}
}
--------------------------------------------------------------------------------
public class ListItem_Elements {
String test;
String result;
ListItem_Elements() {
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
You are missing some necessary code. EditText has a method called addTextChangedListener() which accepts a TextWatcher implementation. This implementation would be responsible for updating the data in the adapter.
final ListItem_Elements item = array.get(position);
holder.textView.setText(item.getTest());
holder.editText.setText(item.getResult());
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
item.setResult(s.toString());
}
// omitted empty impls for beforeTextChanged() and afterTextChanged(), you need to add them
});
Now, everytime the user updates the EditText, your adapter value will be updated. Then you just get the array values:
public void saveValues() {
// testLists in the activity and array in the adapter are references
// to the same list. So testLists already has the updated results
}
And take out this whole block of code:
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
It doesn't do the right thing.
you are filling the listView with value from an ArrayList. Why you don't just get values from the your ArrayList ??
public void saveValues() {
if(tests_Array!=null) {
//and here you get values from your list
//by a simple for instruction
Toast.makeText(MainActivity.this, tests_Array.size(), Toast.LENGTH_SHORT).show();
}
}
I am a new android developer and I need your help.
I created a simple listview. I add items in this listview through the keyboard.
Moreover I add action on item. When user click "OK" the app will be strike out text and set background green.
But when I add the next item,I see that it applies that strike out and background option from previously item.
Can you advise me what I need to do in this situation? How to improve it?
My Code:
package com.example.boytsov.foodbasketapp;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Boytsov on 23.07.2015.
*/
public class ProductList extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
EditText myText;
ListView lvMain;
ArrayList<String> catnames;
ArrayAdapter<String> adapter;
Button button;
final String LOG_TAG = "myLogs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
lvMain = (ListView) findViewById(R.id.lvMain);
myText = (EditText) findViewById(R.id.editText);
button=(Button)findViewById(R.id.button);
catnames= new ArrayList<String>();
// создаем адаптер
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, catnames);
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(this);
lvMain.setOnItemLongClickListener(this);
// Прослушиваем нажатия клавиш
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button :
catnames.add(0, myText.getText().toString());
adapter.notifyDataSetChanged();
myText.setText("");
myText.setBackgroundColor(Color.TRANSPARENT);
myText.setPaintFlags(0);
break;
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d(LOG_TAG, "itemClick: position = " + i + ", id = "
+ l);
TextView textview= (TextView) view;
if (textview.getPaintFlags() != 16){
textview.setPaintFlags(16);
textview.setBackgroundColor(Color.parseColor("#77dd77"));
Toast.makeText(this, "Куплено", Toast.LENGTH_SHORT).show();
} else {
textview.setPaintFlags(0);
textview.setBackgroundColor(Color.TRANSPARENT);
}
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
catnames.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Удалено", Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "onItemClick: position = " + position + ", id = "
+ id);
return true;
}
}
every listview item has its own R.id.editText so having one global myText = (EditText) findViewById(R.id.editText); does not work.
Instead you have to find the edit in the onClick handler
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button : {
// EditText myText = (EditText) view.findViewById(R.id.editText);
TextView myText = (TextView) view;
catnames.add(0, myText.getText().toString());
adapter.notifyDataSetChanged();
myText.setText("");
myText.setBackgroundColor(Color.TRANSPARENT);
myText.setPaintFlags(0);
}
break;
}
}
[Update 28.7.2015]
Your adapter is using android.R.layout.simple_list_item_1 :
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, catnames);
wich does not have an EditText with id R.id.editText. therefore you get an exception.
simple_list_item_1 is a textview. using
TextView myText = (TextView) view;
might work
So this is a bit complicated situation, so I will try to explain what is going on as best I can. I have a sqlite db which populates a listview. Each item in the listview contains the name of the item, along with two buttons. I want these two buttons to be able to use the sqlite db row id of the item they're contained in order to execute their purpose. So I need to get the id of the item, but I don't think using onListItemClick(ListView l, View v, int position, long id) will work for me, becuase I'm not clicking the entire item, rather, buttons within it. If I'm misunderstanding this point, please let me know. In order for the buttons to be clicked, I've created a class which extends SimpleCursorAdapter, which correctly handles clicks. Here are the two classes in question. First, the listactivity, and second, the custom listadapter.
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
public class FriendRequestList extends ListActivity implements OnClickListener {
private Button m_closeButton;
private TagDBAdapter mDbAdapter;
private Cursor mCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbAdapter = new TagDBAdapter(this);
mDbAdapter.open();
this.initLayout();
fillData();
}
private void initLayout() {
setContentView(R.layout.request_list);
m_closeButton = (Button)findViewById(R.id.request_window_close_button);
m_closeButton.setOnClickListener(this);
}
private void fillData() {
SharedPreferences prefs = this.getSharedPreferences("Prefs", MODE_WORLD_READABLE);
String username = prefs.getString("keyUsername", "");
RestClient.getRequests(username, this);
mCursor = mDbAdapter.fetchAllRequests();
startManagingCursor(mCursor);
String[] from = new String[] {TagDBAdapter.KEY_NAME};
int[] to = new int[] {R.id.requester};
SimpleCursorAdapter requests = new FriendRequestListAdapter(this, R.layout.request_view, mCursor, from, to);
this.setListAdapter(requests);
}
public String getRequester() {
return null;
}
#Override
public void onClick(View v) {
SharedPreferences prefs = this.getSharedPreferences("Prefs", MODE_WORLD_READABLE);
String username = prefs.getString("keyUsername", "");
RestClient.getUpdates(username, this);
Intent intent = new Intent(this, MainMenu.class);
this.startActivity(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
mDbAdapter.close();
}
}
And the adapter class:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
public class FriendRequestListAdapter extends SimpleCursorAdapter implements OnClickListener {
private Context mContext;
public FriendRequestListAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Button confirm = (Button)view.findViewById(R.id.confirm_request);
confirm.setOnClickListener(this);
Button deny = (Button)view.findViewById(R.id.deny_request);
deny.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
SharedPreferences prefs = mContext.getSharedPreferences("Prefs", Activity.MODE_WORLD_READABLE);
String username = prefs.getString("keyUsername", "");
//want to get the id here so i can do stuff with the buttons
switch(v.getId()) {
case R.id.confirm_request :
String confirmState = "2";
//these buttons both work
break;
case R.id.deny_request :
String denyState = "3";
//these buttons both work
Log.e("TESTING", "deny");
break;
}
}
}
I hope I've made my question clear enough. To summarize, I don't know how I would get the rowId of the item a pair of buttons is nested in, because I'm not ever using the onListItemClick method, which is, as far as I'm aware, the way one would normally get the id of the item. Thank you for reading and thank you for your answers. Please let me know if there is any clarifications I can make.
Create your a class by implements OnClickListener
class myCustomClass implements OnClickListener {
int rowid;
public myCustomClass(int rowid){
this.rowid=rowid;
}
#Override
public void onClick(View v) {
//do you code in 'rowid' will have the current row position
}
}
So in your
getView
function you can set listener like this
//your other codes
confirm.setOnClickListener(new myCustomClass(position));
//your other codes
deny.setOnClickListener(new myCustomClass(position));
//your other codes
Hope this give you an idea.
you maybe can do like this,in your custom adapter the getView method
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
//you can set view's tag here
//and you should do the reflect on your position to your rowid
view.setTag(customMethodForGetId(position));
//end
Button confirm = (Button)view.findViewById(R.id.confirm_request);
confirm.setOnClickListener(this);
Button deny = (Button)view.findViewById(R.id.deny_request);
deny.setOnClickListener(this);
return view;
}
and in your click event you can get the id by view.getTag();
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Button confirm = (Button)view.findViewById(R.id.confirm_request);
confirm.setOnClickListener(this);
view.setTag(position);
Button deny = (Button)view.findViewById(R.id.deny_request);
deny.setOnClickListener(this);
view.setTag(position);
return view;
}
#Override
public void onClick(View v) {
// get the position here
Integer position = (Integer)v.getTag();
switch(v.getId()) {
case R.id.confirm_request :
break;
case R.id.deny_request :
String denyState = "3";
break;
}
}