Android list view shows blank elements - android

In my App i download a list of strings from the web
then i'm using AsyncTask to update the listview on my activity.
at prePostExecute im creating the array adapter(private member)
at doInBackground i download the list and return it
at onPostExecute i set the returned list to the adapter and then connects the listview and the adapter
in my activity i see just 1 blank element(instead of 2 elements) , when i click it i can see the Text but when im not its blank.
also , when my adapter is not android.R.layout.simple_list_1 but android.R.layout.acitiviy_list_item (and 2 other templates) i can see 2 elements with visible text but the text is small and gray
code:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical" >
<TableRow
android:id="#+id/tableRow0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dip" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#4CB8FB"
android:gravity="center"
android:text="Search"
android:textColor="#FAFAFA"
android:textSize="40sp" />
</TableRow>
<EditText
android:id="#+id/searchInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_btn_search" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"
android:scrollingCache="true" >
</ListView>
</LinearLayout>
code Behind
public class ProductPickerActivity extends Activity {
private ListView listView;
private EditText inputSearch;
private ArrayAdapter<String> adapter;
private final Integer PRODUCT_REQUEST_ID = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_listview);
inputSearch = (EditText) findViewById(R.id.searchInput);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ProductPickerActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
new InitializeUi().execute(this);
setupUI(findViewById(R.id.parent));
}
private class InitializeUi extends AsyncTask<Object, Void, List<IProduct>> {
#Override
protected void onPreExecute() {
// Get ListView object from xml
listView = (ListView) findViewById(R.id.list);
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.activity_list_item, new ArrayList<String>());
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), ProductViewActivity.class);
intent.putExtra("ProductName", itemValue);
startActivityForResult(intent, PRODUCT_REQUEST_ID);
}
});
}
#Override
protected List<IProduct> doInBackground(Object... params) {
// Defined Array values to show in ListView
IProductManager manager = new ProductManager(getApplicationContext());
// download from web
List<IProduct> lst = manager.GetProductList();
return lst;
}
#Override
protected void onPostExecute(List<IProduct> lst) {
String[] values = new String[lst.size()];
Integer i = 0;
for (IProduct p : lst) {
values[i] = p.getName();
i = i + 1;
Log.d("ProductPickerActivity", "Got Values : " + p.getName());
adapter.add(p.getName());
adapter.notifyDataSetChanged();
}
// Assign adapter to ListView
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
listView.refreshDrawableState();
}
}
}

apply the edit code below to onPostExecute hope its work
// Assign adapter to ListView
listView.setAdapter(adapter);
//then add values to adatper
String [] values = new String[lst.size()];
int i =0; //<<-- change to int
for(IProduct p : lst)
{
values[i] = p.getName();
i++;//<-- add +1
Log.d("ProductPickerActivity","Got Values : "+p.getName());
adapter.add(p.getName());
}
//finaly notify adapter data changed
adapter.notifyDataSetChanged();

Related

Spinner doesn't display data after being clicked

So I have been trying to display a list of data from my local mysql server using API calls like getAll,getByID,etc. on the spinner in a drop down style. However when I click on the spinner nothing happens. Here's my code for the passing the data to the spinner:-
public class markAbsentee extends AppCompatActivity implements OnItemSelectedListener{
Button fromDate, toDate, save;
TextView displayFDate, displayTDate;
Spinner genieS;
List genieList;
private Spinner getGenieS;
private List<Genie> getGenieList;
private Button getFromDate;
private Button getToDate;
private Button getSave;
private TextView getDisplayFDate;
private TextView getDisplayTDate;
private DatePickerDialog.OnDateSetListener mDateSetListener, mDateSetListener1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mark_absentee);
getGenieS = (Spinner) findViewById(R.id.geniespinner);
getFromDate = (Button) findViewById(R.id.button2);
getToDate = (Button) findViewById(R.id.button3);
getDisplayFDate = (TextView) findViewById(R.id.fromDate);
getDisplayTDate = (TextView) findViewById(R.id.toDate);
new SpinTask().execute();
//I have called the AsyncTask here which contains the get() API
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Genie selected = (Genie)parent.getSelectedItem();
Toast.makeText(markAbsentee.this, selected.id + " " + selected.name, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class SpinTask extends AsyncTask<Void, Void, List<Genie>>{
private Exception exception;
protected void onPreExecute(){}
#Override
protected List<Genie> doInBackground(Void... voids) {
GenieService genieService = new GenieService();
return genieService.getAll();
}
protected void onPostexecute(List<Genie> genies){
if(genies == null){
new ArrayList<Genie>();
}else {
List<String> rows = genies.stream().map(genie -> getRow(genie)).collect(Collectors.toList());
ArrayAdapter<Genie> adapter = new ArrayAdapter<Genie>(markAbsentee.this, android.R.layout.simple_spinner_item, genies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Toast.makeText(markAbsentee.this, "Clicked", Toast.LENGTH_LONG).show();
genieS.setAdapter(adapter);
}
}
private String getRow(Genie g){
return String.format("%s %s", g.name, g.salary);
}
}
}
Here's the layout of the spinner:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bcak"
android:orientation="vertical"
tools:context="com.codionics.geniem.markAbsentee">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="76dp"
android:layout_marginTop="59dp"
android:text="Enter Absentee"
android:textSize="30dp"
android:textColor="#ffff" />
<Spinner
android:id="#+id/geniespinner"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView4"
android:layout_marginStart="20dp"
android:layout_marginTop="27dp"
android:popupBackground="#color/colorPrimary"
android:spinnerMode="dropdown"
android:autofillHints="Select genie" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
P.S:- GenieService is the service class for calling the API's. I want to display the name and salary of the person in the spinner drop down list.Thanks in advance for the help.
when you set spinner value it containg only single value like string,integer etc show. when you getting data then it add data into list like below ...
listArray.addAll("Your Value");
then after define array adapter like below and set spinner ..
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,strings);
spinner.setAdapter(arrayAdapter);
then after you called any function on spinner item selection used like below code ...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Hello",0).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

Remove a few values from ListView built with BaseAdapter

I am writing the basic task management application. I am using base adapter to work with ListView. I wonder how I can remove (a few) checked values from the list? And how I can remove only one value with long click?
if this posible with my adapter? I tried a few options but nothing worked.
Here is my code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/btn1"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:text="\u2713"
android:background="#drawable/add_btn"
android:onClick="knopka2"/>
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/btn1"
android:hint="put your task here"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:divider="#drawable/deriver"
android:layout_below="#+id/input"
android:layout_centerHorizontal="true"
android:choiceMode="multipleChoice" />
<TextView
android:id="#+id/ttl"
android:layout_below="#id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/tryClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/ttl"
android:onClick="tryClear"
/>
</RelativeLayout>
This is my Activity:
public class Trird extends AppCompatActivity {
Button btn;
EditText input4;
TextView ttl;
ListView list;
public static ArrayList<String> taskList = new ArrayList<String>();
SparseBooleanArray sparseBooleanArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
input4 = (EditText) findViewById(R.id.input);
btn = (Button) findViewById(R.id.btn1);
list = (ListView) findViewById(R.id.listView);
ttl = (TextView)findViewById(R.id.ttl);
}
public String[] putToArray() {
String ag = input4.getText().toString().trim();
if (ag.length() != 0) {
taskList.add(ag);
input4.setText("");
}
String[] abc = taskList.toArray(new String[taskList.size()]);
return abc;
}
public void knopka2(View v) {
final String[] ListViewItems = putToArray(); //
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new MyAdapter(ListViewItems, this));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View tv, int i, long id) {
///tv.setBackgroundColor(Color.YELLOW);
///ttl.setText("selected: " + list.getAdapter().getItem(i));
sparseBooleanArray = list.getCheckedItemPositions();
String ValueHolder = "";
int a = 0;
while (a < sparseBooleanArray.size()) {
if (sparseBooleanArray.valueAt(a)) {
ValueHolder += ListViewItems[sparseBooleanArray.keyAt(a)] + ",";
}
a++;
}
ValueHolder = ValueHolder.replaceAll("(,)*$", "");
Toast.makeText(Trird.this, "ListView Selected Values = " + ValueHolder, Toast.LENGTH_LONG).show();
if(ValueHolder!=null){
taskList.remove(ValueHolder);
}
}
});
}
}
This is my adapter:
public class MyAdapter extends BaseAdapter {
private final Context context;//Context for view creation
private final String[] data;//raw data
public MyAdapter(String[] data, Context context){
this.data=data;
this.context=context;
}
//how many views to create
public int getCount() {
return data.length;
}
//item by index (position)
public Object getItem(int i) {
return data[i];
}
//ID => index of given item
public long getItemId(int i) {
return i;
}
//called .getCount() times - for each View of item in data
public View getView(int i, View recycleView, ViewGroup parent) {
if(recycleView==null)recycleView = LayoutInflater.from(context).inflate(R.layout.item,null);
((TextView)recycleView).setText(data[i]);//show relevant text in reused view
return recycleView;
}
}
And this is how looks like item in ListView.
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
/>
The problem is that you are trying removing item using the ListView remove methode.
Just remove the selected item from the list using the remove() method of your Adapter.
A possible way to do that would be:
CheckedTextView checkedText= baseAdapter.getItem([POSITION OF THE SELECTED ITEM]);
baseAdapter.remove(checkedText);
baseAdapter.notifyDataSetChanged();
put this code inside the wanted button click and there you go.

how to show list view record into second listview on setOnItemClickListener

I have created list view, what I want to do is that when user clicks on first list view the selected record should show in second list, in my code it show on text view, but I want to show that record in second list view so please give me the code/idea how to do this as I am new in android..
public class MainActivity extends Activity {
String item[]=new String[]{"rk","kk","kk","ll","mm","uu"};
TextView tv,tv2,tv3,tv4,tv5;
List<TextView> arrayTV = new ArrayList<TextView>();
ListView li,li2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
li=(ListView)findViewById(R.id.listView1);
li2=(ListView)findViewById(R.id.listView2);
tv=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
tv3=(TextView)findViewById(R.id.textView3);
tv4=(TextView)findViewById(R.id.textView4);
tv5=(TextView)findViewById(R.id.textView5);
arrayTV.add(tv);
arrayTV.add(tv2);
arrayTV.add(tv3);
arrayTV.add(tv4);
arrayTV.add(tv5);
ArrayAdapter<String> adapter=new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,android.R.id.text1, item);
li.setAdapter(adapter);
li.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
// TODO Auto-generated method stub
int itm=position;
Toast.makeText(getApplicationContext(),""+itm+""+li.getItemAtPosition(position),40).show();
arrayTV.get(position).setText(""+li.getItemAtPosition(position));
}
});
}
Here is my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_weight=".5" >
</ListView>
set the adapter for second listview in onitemclick of first listview
List<String> a = new ArrayList<String>();
li.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
String clickedItem =item[postion];
if(!a.contains(clickedItem))
a.add(clickedItem);
String[] newitem = new String[a.size()];
a.toArray(newitem);
ArrayAdapter<String> adapter=new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1, newitem);
li2.setAdapter(adapter);
}
});

click not working on searchitem from listview android

Click on search item inside edittext redirect on wrong activity, it doesn't open the activity associated with it. It opening other activities that are associated with other listitems but not that i am clicking one.
Here is my complete code:
public class Tabtwo extends Activity implements OnItemClickListener {
ListView listView;
TextView txt;
ArrayAdapter<String> adapter;
// Search EditText
EditText edtSearch;
// Array of strings storing country names
String[] countries = new String[] { "Admin Cost", "Affinity Diagram",
"Analyse", "Apprasal Costs", "Assessment of Stakeholders",
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[] { R.drawable.admin, R.drawable.affinity,
R.drawable.analysis, R.drawable.appraisal, R.drawable.assessment,
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabtwo);
// Each row in the list stores country name, currency and flag
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 4; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("txt", countries[i]);
hm.put("flag", Integer.toString(flags[i]));
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag", "txt" };
// Ids of views in listview_layout
int[] to = { R.id.flag, R.id.txt };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = (ListView) findViewById(R.id.listview);
edtSearch = (EditText) findViewById(R.id.Search_box);
txt = (TextView) findViewById(R.id.txt);
listView.setOnItemClickListener(this);
// Setting the adapter to the listView
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
edtSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
if (position == 0) {
Intent int0 = new Intent(getApplicationContext(), Admincost.class);
startActivity(int0);
}
if (position == 1) {
Intent int1 = new Intent(getApplicationContext(), Affinity.class);
startActivity(int1);
}
if (position == 2) {
Intent int2 = new Intent(getApplicationContext(), Analyse.class);
startActivity(int2);
}
if (position == 3) {
Intent int3 = new Intent(getApplicationContext(),
ApprasalCosts.class);
startActivity(int3);
}
if (position == 4) {
Intent int1 = new Intent(getApplicationContext(), Assessment.class);
startActivity(int1);
} }
}
}
Here is my tabtwo xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/Search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Search a Item from ListView"
android:inputType="textVisiblePassword" />
/>
<TextView
android:id="#+id/List_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="12dip"
android:textSize="17sp"
android:textStyle="bold" />
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-50dp" />
</LinearLayout>
Here is listview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="21dp" />
</LinearLayout>
Replace your onItemClick method with below and try.. Hope it works..
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
TextView tv = (TextView) arg1.findViewById(R.id.txt);
String str = tv.getText().toString().trim();
if (str.equals(countries[0])) {
Intent int0 = new Intent(Tabtwo.this, Admincost.class);
startActivity(int0);
}else if(str.equals(countries[1])) {
Intent int1 = new Intent(Tabtwo.this, Affinity.class);
startActivity(int1);
}else if(str.equals(countries[2])) {
Intent int2 = new Intent(Tabtwo.this, Analyse.class);
startActivity(int2);
}else if(str.equals(countries[3])) {
Intent int3 = new Intent(Tabtwo.this, ApprasalCosts.class);
startActivity(int3);
}else if(str.equals(countries[4])) {
Intent int1 = new Intent(Tabtwo.this, Assessment.class);
startActivity(int1);
}
}
Add this code to your TextView as well as to ImageView
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
and for ItemClick you can use the answer of Tamilan
I meet the same question with you. Try the following one:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
//(String) getListAdapter().getItem(position);
String city_id=map.get( (String) adapter.getItem(position) );
Toast.makeText(getApplicationContext(),city_id, Toast.LENGTH_SHORT).show();
Intent i=new Intent(MainActivity.this,DetailActivity.class);
i.putExtra("city_id",city_id);
startActivity(i);
}
});

ListActivity Android

Does somebody know why ListActivity won't work and when I change it to Activity base class, with slight changes it works, but onClick() method still doesn't. I'm trying only to put some strings into the list... Here's the code:
public class TestDataBaseActivity extends Activity implements OnClickListener {
private CommentsDataSource datasource;
ListView m_list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
m_list = (ListView) findViewById(R.id.listView1);
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
m_list.setAdapter(adapter);
Button add = (Button)findViewById(R.id.button_add);
Button delete = (Button)findViewById(R.id.button_delete);
add.setOnClickListener(this);
delete.setOnClickListener(this);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
#Override
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) m_list.getAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.button_add:
String[] comments = new String[] {
"Cool", "Very nice", "Hate it"
};
int nextInt = new Random().nextInt(3);
// Save the new comment to the database
comment = datasource.createComment(comments[nextInt]);
adapter.add(comment);
break;
case R.id.button_delete:
if (m_list.getAdapter().getCount() > 0) {
comment = (Comment) m_list.getAdapter().getItem(0);
datasource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Here is XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestDataBaseActivity" >
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_new" />
<Button
android:id="#+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/button_add"
android:text="#string/delete_first" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/button_add"
android:padding="15dp" >
</ListView>
</RelativeLayout>
I edited now to extend Activity, now "only" onClick() dont work...
Thanks in advance!
For a ListActivity, you should override onListItemClick() instead:
#Override
protected void onListItemClick(ListView lv, View v, int position, long id){
}
Since you are extending ListActivity you need to have an Listview with android:id="#android:id/list".
if you want to use #+id/lst_id then dont extend ListActivity, just extended Activity.
And whenever you are using Listview you need to implement OnItemClickListener not OnClickListener.
and override the default OnItemClick method
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
you should implement OnClickListener
public class TestDatabaseActivity extends ListActivity implements
OnClickListener{
try following code a simple list activity
public class MainActivity extends ListActivity implements OnItemClickListener {
ListView listView;
static final String[] SPORTS = {"Shuttle Badminton", "Tennis", "FootBall",
"Basket Ball","Table Tennis", "Chess","Hockey"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = getListView();
//setting adapter
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,SPORTS));
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view.findViewById(R.id.text1);
Toast.makeText(getApplicationContext(),"Position is: "+position,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Text is: "+tv.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
here list_item is an xml having following code
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#android:color/black"
android:padding="10dp" />
Use this code for list activity and modify row xml according to your needs.
hope this helps..
This is what's troubling you:
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) m_list.getAdapter();
Build a global object for your adapter instead. ( Declare it before onCreate() )

Categories

Resources