Trying to get this working... it loads up fine, even tells the application that it completed getting all the data. It does not populate the listview though.
The data response inside mArrayList.toString(): [A, B, C, D]
public class MainActivity extends ActionBarActivity {
private static final String DEBUG_TAG = "MainActivity";
private boolean mAlternateTitle = false;
ListView lv;
private ArrayList<Show> mArrayList;
ShowsAdapter adapter;
AlertDialog mAlertDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mArrayList = new ArrayList<Show>();
lv = (ListView) findViewById(R.id.list);
adapter = new ShowsAdapter(MainActivity.this, android.R.layout.simple_list_item_1, mArrayList);
ShowsList show_list = new ShowsList();
show_list.execute();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new ListClickListener());
}
private class ShowsList extends AsyncTask<Void, Void, List<Show>> {
#Override
protected void onPreExecute() {
mAlertDialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_action_refresh).setTitle(R.string.fetching_new).show();
}
#Override
protected List<Show> doInBackground(Void... voids) {
final String DEBUG_TAG = "MainActivity$ShowList$doInBackground";
try {
for (Show show : Show.getShows()) {
Log.d(DEBUG_TAG, show.toString());
mArrayList.add(show);
};
return mArrayList;
} catch (Exception e) {
new AlertDialog.Builder(MainActivity.this.getApplicationContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.server_down_title).setMessage(R.string.server_down_message).setPositiveButton(R.string.app_quit, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
}).show();
return null;
}
}
#Override
protected void onPostExecute(final List<Show> show_list) {
if (mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
adapter.notifyDataSetChanged();
}
}
private class ListClickListener implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Show show = mArrayList.get(i);
Toast.makeText(MainActivity.this, "Clicked on a list item: " + show.title, Toast.LENGTH_LONG).show();
}
}
private class ShowsAdapter extends ArrayAdapter<Show> {
final String DEBUG_TAG = "MainActivity$ShowsAdapter";
public ShowsAdapter(Context context, int textViewResourceId, List<Show> shows) {
super(context, textViewResourceId, shows);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Show show = this.getItem(position);
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row_show, parent, false);
}
((TextView) convertView.findViewById(R.id.show_title)).setText(show.title);
//Log.d(DEBUG_TAG, (String)((TextView) convertView.findViewById(R.id.show_title)).getText());
//((TextView) convertView.findViewById(R.id.episode_number)).setText(episode.getGrayLine());
return convertView;
}
}
Just in case it could be an issue with the layout [main.xml]:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</FrameLayout>
list_show_row.xml:
<?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">
<TextView
android:textSize="17.0dip"
android:textStyle="bold"
android:textColor="#ff000000"
android:gravity="center_vertical"
android:id="#+id/show_title"
android:layout_width="fill_parent"
android:layout_height="0.0dip"
android:text="Show Title"
android:layout_weight="1.0"
/>
<TextView
android:textStyle="italic" android:textColor="#ff666666"
android:id="#+id/episode_number"
android:layout_width="fill_parent" android:layout_height="0.0dip" android:text="Episode Number" android:layout_weight="1.0" />
</LinearLayout>
Don't set fill_parent on the layout_height of the root element of list_row_show.xml layout.
Related
I used RelativeLayout for my ListView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox" />
<TextView
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox1"
android:layout_alignBottom="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:text="TextView" />
</RelativeLayout>
Here is my ListView code,
private void displayList(){
ArrayList<String> diyListArray = new ArrayList<String>();
diyListArray.add("1");
diyListArray.add("2");
diyListArray.add("3");
diyListArray.add("4");
diyListArray.add("5");
diyListArray.add("6");
diyListArray.add("7");
listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, R.id.test, diyListArray);
diyList.setAdapter( listAdapter );
}
We can see here that I used ArrayAdapter with resource id of TextView.
I am able to display the checkboxes and their corresponding texts.
How can I get user selected texts from checkboxes?
Try the following:
Demo10.class:----
public class Demo10 extends AppCompatActivity implements Listener {
private ListView lv;
private boolean[] state_ = new boolean[4];
private String[] text_ = new String[4];
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo11);
for(int i = 0 ; i<4 ; i++) {
state_[i] = false;
text_[i] = "text"+i;
}
lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(new ItemAdapter(Demo10.this , this));// This includes a Listener that listens to onCheckBoxStateChanges.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { // used to handle ListView onItemClicks and how they should affect the corresponding checkBox
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox cb = view.findViewById(R.id.cb);
cb.setChecked(!cb.isChecked());
displayCheckBoxStateText();
}
});
}
private void displayCheckBoxStateText(){
for(int i = 0 ; i<4 ; i++){
Log.e("CheckBox", text_[i]+" : " + state_[i]);
}
}
#Override
public void checkBox1(boolean state) {
state_[0] = state;
displayCheckBoxStateText();
}
#Override
public void checkBox2(boolean state) {
state_[1] = state;
displayCheckBoxStateText();
}
#Override
public void checkBox3(boolean state) {
state_[2] = state;
displayCheckBoxStateText();
}
#Override
public void checkBox4(boolean state) {
state_[3] = state;
displayCheckBoxStateText();
}
}
ItemAdapter.class:-----
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private Listener callback;
public ItemAdapter(Context c , Listener l) {
mContext = c;
callback = l;
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return s.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
CheckBox cb;
View view = convertView;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.demo10, null);
}
}
cb = view.findViewById(R.id.cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (position) {
case 0:
callback.checkBox1(isChecked);
break;
case 1:
callback.checkBox2(isChecked);
break;
case 2:
callback.checkBox3(isChecked);
break;
case 3:
callback.checkBox4(isChecked);
break;
default:
break;
}
}
});
cb.setText(s[position]);
return view;
}
private String[] s = {
"test1",
"test2",
"test3",
"test4"
};
}
Listener interface:----
public interface Listener {
public void checkBox1(boolean state);
public void checkBox2(boolean state);
public void checkBox3(boolean state);
public void checkBox4(boolean state);
}
demo10.xml:----
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/cb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="" />
</RelativeLayout>
demo11.xml:-----
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv">
</ListView>
</android.support.constraint.ConstraintLayout>
Make choice mode first
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
I am making a button by clicking on it you can retrieve all the items you checked
button.setOnClickListener(this);
#Override
public void onClick(View v) {
SparseBooleanArray checked = listview.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(listAdapter.getItem(position));
}
}
here you get all the items checked in your selectedItems ArrayList.
You can override getView() of ArrayAdapter and handles views by yourself. Replace:
listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, R.id.test, diyListArray);
with
listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, diyListArray){
boolean[] checked = new boolean[diyListArray.size()];
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView == null) convertView = getLayoutInflater().inflate(R.layout.selectrow, null);
TextView textView = convertView.findViewById(R.id.test);
CheckBox checkBox = convertView.findViewById(R.id.checkBox1);
textView.setText(getItem(position));
checkBox.setChecked(checked[position]);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checked[position] = !checked[position];
String msg = "Checked Item: ";
if(!checked[position]) msg = "Unchecked Item: ";
Toast.makeText(getContext(), msg + getItem(position), Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
return convertView;
}
};
I have blog about ListView: http://programandroidlistview.blogspot.com/
Hope that helps!
I have an app which uses listview to show data received from a JSON.Now, I want an onItemclick listener in the listview so that, after displaying the listview users can click on any row to start a new activity. But the onclicklistener is not working.I am a new developer so am unable to make it work. Kindly help me so that I can implement the onclick Listener. Thanks in advance.
Edited:- Another problem I am facing is that switch case doesnt seem to work because I don't know how many ids will be added to the rows i.e the rows are unknown to me, it may be anything. So what should I use instead of switch case?
Thanks in advance
This is my StatementsActivity.java which displays the listview
public class StatementsActivity extends AppCompatActivity {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(OpeningScreenActivity.getContextOfApplication());
String token = myPrefs.getString("GCMTOKEN", "");
String JSON_URL = "http://xyz.in/view_json.php?device_id=" + token;
private ListView listView;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statements);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_layout, ParseJSON.ids);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent newActivity = new Intent(StatementsActivity.this, MainActivity.class);
startActivity(newActivity);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v){
}
});
sendRequest();
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void sendRequest() {
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(StatementsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.mem_codes,ParseJSON.created_ons);
listView.setAdapter(cl);
}
}
This is my CustomList.java class
public class CustomList extends ArrayAdapter<String> {
private String[] ids;
private String[] mem_codes;
private String[] created_ons;
private Activity context;
public CustomList(Activity context, String[] ids, String[] mem_codes, String[] created_ons) {
super(context, R.layout.list_view_layout, ids);
this.context = context;
this.ids = ids;
this.mem_codes = mem_codes;
this.created_ons = created_ons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
TextView textViewMemCode = (TextView) listViewItem.findViewById(R.id.textViewMem_code);
TextView textViewCreatedOn = (TextView) listViewItem.findViewById(R.id.textViewCreated_on);
textViewId.setText(ids[position]);
textViewMemCode.setText(mem_codes[position]);
textViewCreatedOn.setText(created_ons[position]);
return listViewItem;
}
}
And this is my ParseJSON.java class
public class ParseJSON {
public static String[] ids;
public static String[] mem_codes;
public static String[] created_ons;
public static final String KEY_ID = "id";
public static final String KEY_MEM_CODE = "mem_code";
public static final String KEY_CREATED_ON = "created_on";
public static final String JSON_ARRAY = "result";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
mem_codes = new String[users.length()];
created_ons = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
mem_codes[i] = jo.getString(KEY_MEM_CODE);
created_ons[i] = jo.getString(KEY_CREATED_ON);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is my activity_statements.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"
android:background="#color/buttonColor" tools:context=".StatementsActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="#layout/toolbar_layout"/>
</LinearLayout>
</RelativeLayout>
And this is my list_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/buttonColor">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewId"
android:layout_alignParentStart="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewMem_code"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewCreated_on"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
I have built an android application which displays in Listview style and on clicking on them, shows their respective cost.
Below is the code of that. Hope, it helps you...
public class ListViewActivity extends AppCompatActivity {
private static ListView lv;
private static String[] prod_names = new String[] {"E", "G", "E2", "G2", "X"};
private static int[] cost = new int[] {6500, 13000, 7500, 16000, 25000};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Listener();
}
public void Listener(){
lv = (ListView)findViewById(R.id.listView);
ArrayAdapter <String> adp = new ArrayAdapter<String>(this, R.layout.products_list, prod_names);
lv.setAdapter(adp);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String val = (String)lv.getItemAtPosition(position);
Toast.makeText(ListViewActivity.this, " Release# : "+ (position+1)+"\n Model : "+val+"\n Cost : Rs "+cost[position], Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Do it like this in your onItemClick:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newActivity = new Intent(StatementsActivity.this, MainActivity.class);
// Adding your variable to intent
newActivity.putExtra("position",position);
startActivity(newActivity);
break;
}
});
In your MainActivity.java :
public class MainActivity extends Activity
{
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Receiving your variable in another activity
position = getIntent().getIntExtra("position",0);
}
}
And kindly refer this : How do I pass data between Activities in Android application?
Edit :
Check this out
OnItemCLickListener not working in listview
ListView OnItemClickListener Not Responding?
OnItemClickListener and OnClickListener not working for ListView
ListView.onItemClick not working
Listview itemclick not work
I have two button at bottom i.e after listview ends.
I am using a custom listview which display list items with alternate colors.
how to set setOnClickListener for both button at bottom?
public class PieMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRes = getResources();
new Random(new Date().getTime());
solbtn = (Button)findViewById(R.id.solution);
String recive ;
Bundle b = getIntent().getExtras();
final int piewrong=b.getInt("piewrong");
final int pieright=b.getInt("pieright");
final int pieunclick=b.getInt("pieunclick");
setContentView(R.layout.piechart_result);
recive = pieright+"/20";
mPie.setUnit(recive);
data1 = new ArrayList<String>();
fillData() ;
listtotal =getIntent().getStringArrayListExtra("listtotal");
timeuse =getIntent().getStringArrayListExtra("timeused");
adapter1 = new ListAdapter(this, data1, listtotal,timeuse);
ListView lvMain = (ListView) findViewById(R.id.list);
lvMain.setAdapter(adapter1);
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int questionno = position+1;
Bundle b = new Bundle();
b.putInt("questionno",questionno);
b.putInt("piewrong",piewrong);
b.putInt("pieright",pieright);
b.putInt("pieunclick",pieunclick);
Intent in=new Intent(PieMainActivity.this,Solution.class);
in.putStringArrayListExtra("listtotal", (ArrayList<String>) listtotal);
in.putStringArrayListExtra("timeused", (ArrayList<String>) timeuse);
in.putExtras(b);
startActivity(in);
finish();
}
});
}
void fillData() {
for (int i = 1; i <= 20; i++) {
data1.add("Question " + i);
}
}
void fillcmp() {
for (int i = 1; i <= 20; i++) {
cmp.add("cmp " + i);
}
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.staritsolutions.apptitude"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:layout_weight="1.0">
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<Button
android:id="#+id/home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Main Menu"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
<Button
android:id="#+id/solution"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Solutions"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
BaseAdapter file
public class ListAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
List<String> data1;
List<String> cmp;
List<String> timeused;
ListAdapter(Context context, List<String> data1 ,List<String> cmp ,List<String> timeused) {
ctx = context;
this.data1 = data1;
this.cmp = cmp;
this.timeused = timeused;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data1.size();
}
public int getCount1() {
return cmp.size();
}
#Override
public Object getItem(int position) {
return data1.get(position);
}
public Object getItem1(int position1) {
return cmp.get(position1);
}
#Override
public long getItemId(int position) {
return position;
}
public long getItemId1(int position1) {
return position1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.listitem, parent, false);
}
/*if (position % 2 == 0) {
view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
} else {
view.setBackgroundResource(R.drawable.artists_list_background_alternate);
}*/
TextView text = (TextView) view.findViewById(R.id.heading);
int no = position;
if(cmp.get(position).equals("GREEN"))
{
text.setTextColor(Color.parseColor("#00D50E"));
}else if(cmp.get(position).equals("RED"))
{
text.setTextColor(Color.parseColor("#e84040"));
}else
{
text.setTextColor(Color.parseColor("#B441E9"));
}
((TextView) view.findViewById(R.id.heading)).setText(data1.get(position));
((TextView) view.findViewById(R.id.duration)).setText(timeused.get(position));
return view;
//String.valueOf(value);
}
}
So these buttons are not part of your ListView? Well, than in your onCreate do something like:
solbtn = (Button)findViewById(R.id.solution);
solbth.setOnClickListener( toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourMethod();
}
});
And the same goes for the second button.
Or you can make your Activity implement View.OnClickListener, after doing this you can set your click listeners like this:
//this two lines in your OnCreate
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//somewhere later in the code
#Override
public void onClick(View v) {
//do something
}
Just add the clickListeners in your onCrete() method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
solbtn = (Button) findViewById(R.id.home);
homebtn = (Button) findViewById(R.id.solution);
solbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for solution button
}
});
homebtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for home button
}
});
.....
}
I am working on a project where I am displaying a list of Car owners. Upon accessing the application, an empty list is displayed. The user search for an owner, and we display all available owners that matche the search criteria.
The issue that I ran into is that the owner list is updated, but it also show "No record to be displayed" which is what an empty list is supposed to show. What I am missing here?
Here are the relevant classes
public class OwnerDetail extends ListFragment {
ListView mListView;
ArrayList<Owner> listItem = new ArrayList<Owner>();
public OwnerAdapter ownerAdapter;
private String[] searchParameter = null;
public void SearchParameters(String[] parameters)
{
searchParameter = parameters;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v1 = inflater.inflate(R.layout.customize_layout,container, false);
mListView = (ListView) v1.findViewById(android.R.id.list);
return v1;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail, listItem);
if(!(searchParameter == null))
{
ownerAdapter.clear();
ownerAdapter.addAll(listItem);
new OnwerAsyncTask().execute();
ownerAdapter.notifyDataSetChanged();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mListView.setAdapter(ownerAdapter);
ownerAdapter.notifyDataSetChanged();
}
private class OnwerAsyncTask extends AsyncTask<Void, Void, List<Owner>> {
#Override
protected List<Owner> doInBackground(Void... params) {
try
{
Owner items = new Owner();
items.setFirstName("John");
items.setLastName("Smith");
items.setCarId("1");
listItem.add(items);
Owner item1 = new Owner();
item1.setFirstName("Samantha");
item1.setLastName("Right");
item1.setCarId("2");
listItem.add(item1);
Owner item2 = new Owner();
item2.setFirstName("Regie");
item2.setLastName("Miller");
item2.setCarId("3");
listItem.add(item2);
Owner item3 = new Owner();
item3.setFirstName("Mark");
item3.setLastName("Adam");
item3.setCarId("4");
listItem.add(item3);
} catch(Exception ex)
{
ex.toString();
}
return listItem;
}
#Override
protected void onPreExecute() {
listItem.clear();
ownerAdapter.clear();
super.onPreExecute();
}
#Override
protected void onPostExecute(List<Owner> result) {
/*OwnerDetail fragment = (OwnerDetail) mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.SetAdapter(result);*/
super.onPostExecute(result);
if(listItem.size() > 0)
{
ownerAdapter.notifyDataSetChanged();
}
}
}
}
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText(item.getLastName());
holder.tvCId.setText(item.getCarId());
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
Edit on 08/06/2013
I updated the OwnerDetail class and added the asyncktask as a private inner class. It displayed the list, but it showed the "No Record to be displayed" too.
owner_detail.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" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// customize_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="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:text="No record to be displayed."
/>
</LinearLayout>
You are not adding data to adapter in onPostExecute:
#Override
protected void onPostExecute(List<Owner> result) {
super.onPostExecute(result);
ownerAdapter.clear();
ownerAdapter.addAll(result);
ownerAdapter.notifyDataSetChanged();
Log.i("TESTING","Added " + result.size() + " items to adapter");
}
Also, I see you are using custom list layout, make sure empty TextView has id #android/id/empty and visibility set to gone.
You have to refresh the Adapter because when you create the Fragment owner will be null and so the fragment is initialized with the empty row.
Modify your SetAdapter(Owner[] o) as follows:
public void SetAdapter(Owner[] o) {
owner = o;
ownerAdapter.clear();
ownerAdapter.addAll(o);
ownerAdapter.notifyDataSetChanged();
}
I've got a custom BaseAdapter and an add button in the main activity. The button opens a dialog with a textbox and you can add new elements to the list that way. The problem is that the list is not refreshing. In the onActivityResult() function I print the number of elements in the list and each time I hit OK in the dialog box the number increases, so I know it's just the refreshing that doesn't work. My BaseAdapter and my activity:
class ListaOrase extends BaseAdapter{
private Activity context;
ArrayList<String> orase;
public ListaOrase(Activity context){
this.context=context;
orase=new ArrayList<String>();
}
public void add(String string){
orase.add(string);
this.notifyDataSetChanged();
}
public View getView (int position, View convertView, ViewGroup list) {
View element;
if (convertView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
element = inflater.inflate(R.layout.lista, null);
}
else element = convertView;
TextView elementLista=(TextView)element.findViewById(R.id.elementLista);
elementLista.setText(orase.get(position));
return element;
}
}
public class WeatherAppActivity extends ListActivity {
Button buton;
ListaOrase lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lista=new ListaOrase(this);
buton=(Button)findViewById(R.id.buton);
lista.add("Bucuresti");
lista.add("Sibiu");
setListAdapter(lista);
}
public void add(View view){
Intent intent=new Intent();
intent.setClass(this, Adauga.class);
startActivityForResult(intent, 0);
}
public void onActivityResult (int requestCode, int responseCode, Intent data){
System.out.println("Apelata");
if(responseCode==1){
lista.add(data.getStringExtra("oras")); // e chiar getText()
System.out.println(lista.getCount());
lista.notifyDataSetChanged();
}
}
}
As you can see, I'm trying to refresh (notifyDataSetChanged();) both when adding a new element (in the BaseAdapter extending class) and in method onActivityResult, after the dialog passes the new element to the main Activity. I repeat, the element IS added to the list because the count increases, it just doesn't refresh.
Thanks for your answers!
It's normal that it doesn't refresh, you are adding an item to "lista" but the adapter keeps its own copy of that list, so or you set again the list in the adapter and then you call notifyDataChanged or you add the new item to the adapter.
Anyway I see couple of weird things, I thing you could semplify everything using an array adapter, you don't need to implement add,etc. I wrote some code simplyfing yours:
public class WeatherAppActivity extends ListActivity {
Button buton;
ItemsAdapter lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> initialList = new ArrayList<String>();
initialList.add("Bucuresti");
initialList.add("Sibiu");
lista=new ItemsAdapter(this, initialList);
buton=(Button)findViewById(R.id.button1);
buton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista.add(""+System.currentTimeMillis()); // e chiar getText()
lista.notifyDataSetChanged();
}
});
setListAdapter(lista);
}
class ItemsAdapter extends ArrayAdapter<String> {
public ItemsAdapter(Context context, List<String> list) {
super(context, R.layout.lista, list);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
}
}
These are the xml that I have used:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Button" />
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
lista.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="vertical" >
<TextView
android:id="#+id/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
This is the version of the adapter using a baseadapter:
class ItemsBaseAdapter extends BaseAdapter {
private List<String> items;
private Context mContext;
public ItemsBaseAdapter(Context context, List<String> list) {
items = list;
mContext = context;
}
public void addItem(String str) {
items.add(str);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = (String) getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
And this is the version of the list item wich also include an imageview on the left:
<?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:layout_height="wrap_content"
android:src="#android:drawable/btn_star_big_on"
android:scaleType="fitCenter"
android:layout_width="wrap_content"
/>
<TextView
android:id="#+id/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>