I'm trying to create a row in listview dynamically by giving external data.
- Each row in a listview has a string data and a switch. String data taken from an Edittext externally.
- I have a EditText field. I will input the data through this.
- I have a button . When it is pressed, the EditText content should be added to a new row of the listview along with a Switch
- While adding the new row , care should be taken to retain the previously added row.
I got the code skeleton from web. This code is manipulated by me for my requirement.
The following code adds the row dynamically but it is clearing the previously added row. Kindly help . Thanks
This is my MainActivity.java
public class MainActivity extends Activity {
Switch sw1;
private ListView listView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
}
public void getdata(View v) {
EditText et;
String dev_name;
et = (EditText)findViewById(R.id.editText1) ;
dev_name = et.getText().toString() ;
create(dev_name, null);
}
public void create (String str, Switch sw1) {
Items Items_data[] = new Items[]
{
new Items( str,sw1)
};
ItemsAdapter adapter = new ItemsAdapter (this,R.layout.items_row, Items_data);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
}
}
This is my ItemsAdapter.java
public class ItemsAdapter extends ArrayAdapter<Items>{
Context context;
int layoutResourceId;
Items data[] = null;
public ItemsAdapter(Context context, int layoutResourceId, Items[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ItemsHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ItemsHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.listtext);
holder.switch1= (Switch)row.findViewById(R.id.listswitch);
row.setTag(holder);
}
else
{
holder = (ItemsHolder)row.getTag();
}
Items item = data[position];
holder.txtTitle.setText(Items.tv);
holder.switch1.setChecked(false);
return row;
}
static class ItemsHolder
{
TextView txtTitle;
Switch switch1;
}
}
This is my Item class.
public class Items {
public static String tv;
public static Switch switc;
public Items() {
super();
}
public Items(String tv, Switch switc ) {
super();
this.tv = tv;
this.switc = switc;
}
}