Hi I am creating a layout and a ListView within it to display small icon in 5 columns. I am using AysncTask to parse JSON to get the images details which I need to display in list view. Now I am getting error. I don't know how to solve. Please help me to solve.
My layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_seatvisible"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.notebook.runtowin.Activity.Seatvisible">
<TextView
android:id="#+id/from_to"
android:layout_width="match_parent"
android:layout_height="35sp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/colorPrimaryDark"
android:text="Select your seat"
android:padding="5sp"
android:gravity="center_vertical"
android:textStyle="bold"
android:textColor="#color/colorwhite" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/from_to">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#FFEB3B"
android:id="#+id/headinglayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/busname"
android:padding="5sp"
android:text="RUN TO WIN"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/busname"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/seatnumber"
android:padding="5sp"
android:text="Seats :"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#+id/seatnumber"
android:text="25,24"
android:id="#+id/seatsnumber"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ticketprice"
android:layout_alignParentRight="true"
android:text="hsdshd"
android:textStyle="bold"
android:padding="5sp"
android:textSize="30sp"
android:layout_marginRight="10sp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/headinglayout"
android:layout_marginTop="3sp"
android:paddingTop="10sp"
android:paddingRight="25sp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/iconsteer"
android:id="#+id/imageView2"
android:layout_marginEnd="50sp"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView2"
android:layout_marginTop="20sp"
android:id="#+id/listviewseat">
</ListView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="25sp"
android:layout_alignParentEnd="true"
android:gravity="center_horizontal"
android:background="#color/colorPrimaryDark"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BOOK TICKETS"
android:padding="10sp"
android:id="#+id/bt_book"
android:textSize="20sp"/>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
My Listview Layout is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8sp"
android:gravity="top">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewseat"/>
</LinearLayout>
My code is:
public class Seatvisible extends AppCompatActivity {
ArrayList<HashMap<String, String>> busdetails1;
private String BusID, servicedate;
private static String url="http://appsilonz.com/demo/v2/bus_seat_abhi.php?journey_date=2017-01-05&bus_id=20";
private ListView lv;
private TextView busname, from_to, seatsnumber, ticketprice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seatvisible);
lv = (ListView) findViewById(R.id.listviewbusdetails);
inilize();
new Seatparsing().execute();
}
private void inilize() {
Intent intent = getIntent();
BusID = intent.getStringExtra("BusID");
servicedate = intent.getStringExtra("servicedate");
busname = (TextView) findViewById(R.id.busname);
from_to = (TextView) findViewById(R.id.from_to);
seatsnumber = (TextView) findViewById(R.id.seatsnumber);
ticketprice = (TextView) findViewById(R.id.ticketprice);
}
public class Seatparsing extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
String response;
String jsonstr, seat_name, ticket_status, seatladies;
ProgressDialog dialog = new ProgressDialog(Seatvisible.this);
AndroidHttpClient maclient = AndroidHttpClient.newInstance("");
#Override
protected void onPreExecute() {
dialog.setCancelable(false);
dialog.setMessage("Please wait..");
dialog.setIndeterminate(false);
dialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
HttpGet request = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
response = maclient.execute(request, responseHandler);
} catch (ClientProtocolException exception) {
exception.printStackTrace();
return null;
} catch (IOException exception) {
exception.printStackTrace();
return null;
}
Log.i("Seats", "" + response);
Log.i("seaturl", "" + url);
jsonstr = response;
busdetails1 = new ArrayList<>();
if (jsonstr != null) {
HashMap<String, String> map2 = new HashMap<>();
try {
JSONArray array1 = new JSONArray(jsonstr);
for (int i = 0; i < array1.length(); i++) {
JSONObject objct1 = array1.getJSONObject(i);
JSONArray array2 = objct1.getJSONArray("row1");
for (int j = 0; j < array2.length(); j++) {
JSONObject objct2 = array2.getJSONObject(j);
seat_name = objct2.getString("seat_name ").toString();
ticket_status = objct2.getString("ticket_status");
seatladies = objct2.getString("seatIsLadies");
map2.put("seat_name", seat_name);
map2.put("ticket_status", ticket_status);
map2.put("seatIsLadies", seatladies);
}
busdetails1.add(map2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return busdetails1;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> busdetails1) {
dialog.dismiss();
customadapter adapter = new customadapter(getApplicationContext(), R.layout.seatlistview, busdetails1);
lv.setAdapter(adapter);
}
}
public class customadapter extends ArrayAdapter {
private ArrayList<HashMap<String, String>> list;
private int resource;
private LayoutInflater inflater;
public customadapter(Context context, int resource, ArrayList<HashMap<String, String>> busdetails1) {
super(context, resource, busdetails1);
list = busdetails1;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(int i, View convertView, ViewGroup parent) {
convertView = inflater.inflate(resource, null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageViewseat);
String seat_name = list.get(i).get("seat_name");
String ticket_status = list.get(i).get("ticket_status");
String seatIsLadies = list.get(i).get("seatIsLadies");
if (!seat_name.equals(null)) {
if (ticket_status.equals("booked")) {
if (seatIsLadies.equals("true")) {
imageView.setImageResource(R.drawable.reservedladies);
imageView.setClickable(false);
} else {
imageView.setImageResource(R.drawable.bookedseat);
imageView.setClickable(false);
}
} else {
imageView.setImageResource(R.drawable.available_seat_img);
}
} else {
imageView.setImageDrawable(null);
imageView.setClickable(false);
}
return convertView;
}
}
}
You should use dp for dimensions and sp for textSize. Currently you are using sp for dimensions.
See the edited layout below,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_seatvisible"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.notebook.runtowin.Activity.Seatvisible">
<TextView
android:id="#+id/from_to"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/colorPrimaryDark"
android:text="Select your seat"
android:padding="5dp"
android:gravity="center_vertical"
android:textStyle="bold"
android:textColor="#color/colorwhite" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/from_to">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#FFEB3B"
android:id="#+id/headinglayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/busname"
android:padding="5dp"
android:text="RUN TO WIN"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/busname"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/seatnumber"
android:padding="5dp"
android:text="Seats :"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="25,24"
android:id="#+id/seatsnumber"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ticketprice"
android:layout_alignParentRight="true"
android:text="hsdshd"
android:textStyle="bold"
android:padding="5dp"
android:textSize="30sp"
android:layout_marginRight="10dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/headinglayout"
android:layout_marginTop="3dp"
android:paddingTop="10dp"
android:paddingRight="25dp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/iconsteer"
android:id="#+id/imageView2"
android:layout_marginEnd="50dp"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView2"
android:layout_marginTop="20dp"
android:id="#+id/listviewseat">
</ListView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_alignParentEnd="true"
android:gravity="center_horizontal"
android:background="#color/colorPrimaryDark"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BOOK TICKETS"
android:padding="10dp"
android:id="#+id/bt_book"
android:textSize="20sp"/>
</RelativeLayout>
</LinearLayout>
For ListView layout,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:gravity="top">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewseat"/>
</LinearLayout>
Also you can't layout_marginRight to an id at this line,
android:layout_marginRight="#+id/seatnumber"
You probably meant,
android:layout_marginRight="5dp"
See #Baseem Samy's answer too.
I see sp units in ur layout files for padding size. sp is for font size only where dp or dip is for all dimensions.
in the textview with id android:id="#+id/seatsnumber"
you set layout_marginRight to an id, that's not available in android you can't set a padding with a view
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#+id/seatnumber"
android:text="25,24"
android:id="#+id/seatsnumber"/>
Related
// mainactivity.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"
android:background="#color/red"
android:gravity="bottom" >
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#android:color/background_light" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:contentDescription="#string/app_name"
android:src="#drawable/ic_action_logo" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="14dp"
android:layout_toRightOf="#+id/imageView1"
android:text="#string/app_name" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_action_overflow" />
</RelativeLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="0.01dp" >
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.91"
android:background="#android:color/background_light" >
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="3dp"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="3dp"
android:src="#drawable/add"
android:onClick="moreEvent" />
</RelativeLayout>
<RelativeLayout
android:layout_width="162dp"
android:layout_height="match_parent"
android:background="#android:color/background_light" >
<ImageView
android:id="#+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:src="#drawable/book"
android:onClick="chatNow" />
</RelativeLayout>
</LinearLayout>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp">
<RelativeLayout
android:id="#+id/relativeLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:background="#android:color/background_light"
android:gravity="center" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView7"
android:layout_marginLeft="14dp"
android:layout_marginTop="14dp"
android:text="Event Name" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:text="Venue, Date"
android:textSize="12sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/textView4"
android:text="Description"
android:textSize="12sp" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="14dp"
android:src="#drawable/demo" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="Event of the Week" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/relativeLayout2"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:background="#android:color/background_light" >
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="Today's Events" />
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="30dp"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:verticalSpacing="10dp" >
</GridView>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
//mainactivity.java
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EventHome.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("All Events: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try{
event = new JSONObject(json);
final ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
JSONArray user = event.getJSONArray("events");
for (int i = 0; i < user.length(); i++) {
JSONObject object = user.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", object.getString("id"));
map.put("name", object.getString("name"));
map.put("date_d", object.getString("date_d"));
map.put("location", object.getString("location"));
map.put("images", "http://www.example.com/"+object.getString("images"));
arraylist.add(map);
}
String[] from = {"name", "date_d", "location", "images"};
int[] to = {R.id.textView1, R.id.textView2, R.id.textView3, R.id.iv_flag};
ListAdapter adapters = new MyAdapter(EventHome.this,arraylist,R.layout.list_event_home,from,to);
gv1.setAdapter(adapters);
gv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ""+arg2, Toast.LENGTH_LONG).show();
}
});
}catch(Exception e)
{
e.printStackTrace();
}
}
//MyAdapter.java
public class MyAdapter extends SimpleAdapter{
public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to){
super(context, data, resource, from, to);
}
public View getView(int position, View convertView, ViewGroup parent){
// here you let SimpleAdapter built the view normally.
View v = super.getView(position, convertView, parent);
// Then we get reference for Picasso
ImageView img = (ImageView) v.getTag();
if(img == null){
img = (ImageView) v.findViewById(R.id.iv_flag);
v.setTag(img); // <<< THIS LINE !!!!
}
// get the url from the data you passed to the `Map`
#SuppressWarnings("rawtypes")
String url = (String) ((Map)getItem(position)).get("images");
// do Picasso
Picasso.with(v.getContext()).load(url).into(img);
// return the view
return v;
}
}
while executing the above code my gridview shows only 2 items. Why is it so. Is there any mistake in my xml. Can anyone knows how to fix it. I am stuck in here. Waiting for answers.
your gridview contains scroll view so there is a chance to reduce the actual items in your gridview. So try to remove scroll view.
[EDIT] code updated
I have a listview which going to have about 100-200 rows, I'have created a AsyncTask class which loads the data from server side using http request and because there is many items I decided to load 10 items/call, and display them in the list and let the user to interact with them while I call the AsyncTask class again to load more 10 items....
Here is the design of the listview (photoshop)
It works great BUT when the listview is being updated it's NOT responding for few moments to scroll, and then it responds good and then it's being updated again and it's not responding for few moments...till it fully loaded from server side. I also tried RUNNABLE thread but the same behavior :-(
How can I populate the listview SMOOTHLY and let the user interact with it while it's populating.
class DBreadInvItems extends AsyncTask<Void, Void, String> {
Connection dbConnection = null;
Statement statement = null;
ResultSet resultSet = null;
ImageView splash;
CstmrInvoice activity;
JSONObject jObj;
String phpResult;
String db;
ItemsDialog itemsdialog;
Integer ttl_read=0;
//----------------------------------------------------------------------------------------------
protected DBreadInvItems(CstmrInvoice a,ItemsDialog itemsdialog) {
this.activity = a;
this.itemsdialog=itemsdialog;
Intent iin= this.activity.getIntent();
Bundle b = iin.getExtras();
db = b.getString("db");
}
//----------------------------------------------------------------------------------------------
#Override
protected void onPreExecute() {
phpResult="";
AnimateImgLoad();
}
//----------------------------------------------------------------------------------------------
#Override
protected String doInBackground(Void... params) {
fetchitems();
return null;
}
//----------------------------------------------------------------------------------------------
#Override
protected void onPostExecute(String result) {
if(phpResult.equals(""))
{
Toast.makeText(itemsdialog.dialog.getContext(), R.string.msg_nointernet, Toast.LENGTH_LONG).show();
return;
}
else
{
if(ttl_read>=10) {
itemsdialog.adapter_items.notifyDataSetChanged();
itemsdialog.finalData = itemsdialog.list_items;
itemsdialog.setListViewHeightBasedOnChildren((ListView) itemsdialog.dialog.findViewById(R.id.listViewInvPopupItems));
//try reading more...
AnimateImgLoad();
itemsdialog.ReadMoreData();
}
}
AnimateImgLoad();
}
//----------------------------------------------------------------------------------------------
private void fetchitems()
{
try
{
JSONObject json=new JSONObject();
json.put("db",db);
json.put("action","fetchitems");
json.put("seq",itemsdialog.SEQ.toString());
HttpParams httpparams= new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparams, 10000);
HttpClient client=new DefaultHttpClient(httpparams);
String url="http://roya4u.com:8972/roya/invoices.php";
HttpPost request=new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json",json.toString());
HttpResponse response=client.execute(request);
HttpEntity entity=response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
phpResult= RestClient.convertStreamToString(instream);
}
}
catch (Throwable t)
{
}
if(phpResult.equals(""))
{
//Toast.makeText(itemsdialog.dialog.getContext(), R.string.msg_nointernet, Toast.LENGTH_LONG).show();
return;
}
try
{
JSONObject object = new JSONObject(phpResult);
final String islogged = object.getString("success");
if(Boolean.valueOf(islogged))//success=true
{
ttl_read=Integer.parseInt(object.getString("total").toString());
if(ttl_read>0) {
itemsdialog.SEQ = Integer.parseInt(object.getString("seq"));
//Toast.makeText(itemsdialog.dialog.getContext(),itemsdialog.SEQ, Toast.LENGTH_SHORT).show();
for (int i = 0; i < object.getJSONArray("items").length(); i++) {
JSONObject j = object.getJSONArray("items").optJSONObject(i);
itemsdialog.list_items.add(new MyInvoiceItems(Integer.parseInt(j.get("id").toString()), j.get("mkat").toString(), 1, Double.parseDouble(j.get("ccost").toString()), j.get("iname").toString(), 0));
}
}
}
else
{
//Toast.makeText(itemsdialog.dialog.getContext(), R.string.msg_errorlogin, Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
//Toast.makeText(itemsdialog.dialog.getContext(),R.string.msg_nointernet, Toast.LENGTH_LONG).show();
}
}
//----------------------------------------------------------------------------------------------
//------------------------------
private void AnimateImgLoad()
{
RotateAnimation anim;
if(splash==null)
{
anim = new RotateAnimation(0f, 360f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
//Start animating the image
splash = (ImageView) itemsdialog.dialog.findViewById(R.id.imgReload);
splash.startAnimation(anim);
ProgressBar progressbar=(ProgressBar) itemsdialog.dialog.findViewById(R.id.invPopupProgressBar);
progressbar.setVisibility(View.VISIBLE);
}
else
{
splash.setAnimation(null);
splash=null;
ProgressBar progressbar=(ProgressBar) itemsdialog.dialog.findViewById(R.id.invPopupProgressBar);
progressbar.setVisibility(View.GONE);
}
}
}
ADAPTER:
public class SearchableItemsAdapter extends BaseAdapter implements Filterable
{
ArrayList<MyInvoiceItems> filteredData = new ArrayList<MyInvoiceItems>();
private ItemFilter mFilter;
private LayoutInflater mInflater;
//
public SearchableItemsAdapter(Context context, ArrayList<MyInvoiceItems> data) {
filteredData = data;
mInflater = LayoutInflater.from(context);
}
//
public int getCount() {
return filteredData.size();
}
//
public Object getItem(int position) {
return filteredData.get(position);
}
//
public long getItemId(int position) {
return position;
}
//
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItems itemsholder;
if(convertView==null)
{
convertView=mInflater.inflate(R.layout.lstcstmrinvoicepopupitems,null);
itemsholder=new ViewHolderItems();
itemsholder.iTaken=(CheckBox) convertView.findViewById(R.id.inv_popupTaken);
itemsholder.iName=(TextView) convertView.findViewById(R.id.inv_popupName);
itemsholder.iQuan=(EditText) convertView.findViewById(R.id.inv_popupQuan);
itemsholder.iPrice=(EditText) convertView.findViewById(R.id.inv_popupPrice);
itemsholder.iTotal=(TextView) convertView.findViewById(R.id.inv_popupTotal);
convertView.setTag(itemsholder);
}
else
{
itemsholder=(ViewHolderItems) convertView.getTag();
}
if(filteredData!=null) {
itemsholder.iTaken.setChecked(false);
if (filteredData.get(position).getTaken() == 1)
itemsholder.iTaken.setChecked(true);
itemsholder.iName.setText(filteredData.get(position).getItem_desc());
itemsholder.iQuan.setText(filteredData.get(position).getItem_num().toString());
itemsholder.iPrice.setText(filteredData.get(position).getItem_cost().toString());
itemsholder.iTotal.setText(filteredData.get(position).getAmountTotal());
}
return convertView;
}
//
public class ViewHolderItems {
CheckBox iTaken;
TextView iName;
EditText iQuan;
EditText iPrice;
TextView iTotal;
}
//
public Filter getFilter() {
if(mFilter==null) mFilter = new ItemFilter();
return mFilter;
}
//
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
//validate
if(filterString.toString().trim().equals(""))
{
results.values = list_items;
results.count = list_items.size();
}
else
{
ArrayList<MyInvoiceItems> tempData =list_items;
finalData = new ArrayList<MyInvoiceItems>();
//mhmd
int count = tempData.size();
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = tempData.get(i).getItem_desc();
if (filterableString.toLowerCase().contains(filterString)) {
finalData.add(new MyInvoiceItems(tempData.get(i).getItem_key(),tempData.get(i).getItem_mkat(),tempData.get(i).getItem_num(),tempData.get(i).getItem_cost(),tempData.get(i).getItem_desc(),tempData.get(i).getTaken()));
}
}
results.values = finalData;
results.count = finalData.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
filteredData =(ArrayList<MyInvoiceItems>) results.values;
notifyDataSetChanged();
}
}
}
popup_invitems.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"
android:background="#ffe3e3e3">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:id="#+id/tbl_mainTitle"
android:background="#ffffffff">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_searchIcon"
android:layout_alignParentRight="false"
android:layout_marginTop="8dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="8dp">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgReload"
android:src="#drawable/ic_reload" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="false"
android:id="#+id/tbl_txtName"
android:layout_marginTop="11dp"
android:layout_marginRight="4dp"
android:layout_toLeftOf="#+id/tbl_sort">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="45dp"
android:layout_height="wrap_content"
android:text="#string/inv_popup_itemname_title"
android:singleLine="true"
android:id="#+id/txtName"
android:textSize="16dp"
android:textColor="#ff3c3c3c" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tbl_edtName"
android:layout_toLeftOf="#+id/tbl_txtName"
android:layout_marginTop="6dp"
android:layout_toRightOf="#+id/tbl_searchIcon"
android:layout_marginLeft="10dp"
android:stretchColumns="*">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edtName"
android:background="#drawable/edittext" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="#+id/tbl_sort"
android:layout_marginTop="13dp"
android:layout_marginRight="8dp" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgSort"
android:src="#drawable/ic_sortb"
android:cropToPadding="false" />
</TableRow>
</TableLayout>
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminateOnly="false"
style="#style/ProgressBar.Horizontal"
android:indeterminate="true"
android:id="#+id/invPopupProgressBar"
android:visibility="gone"
android:layout_below="#+id/tbl_sort"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp" />
</RelativeLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView"
android:layout_below="#+id/tbl_mainTitle"
android:layout_above="#+id/Relative_Buttons"
android:layout_marginBottom="2dp"
android:layout_marginTop="5dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/listViewInvPopupItems"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:background="#fff4f4f4" />
</RelativeLayout>
</ScrollView>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/Relative_Buttons"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_yes"
android:layout_alignParentRight="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="161dp"
android:layout_height="50dp"
android:text="#string/inv_popup_btnOK_title"
android:id="#+id/txtYes"
android:drawableRight="#drawable/ic_ok"
android:drawablePadding="10dp"
android:singleLine="true"
android:textSize="16dp"
android:background="#fff4f4f4"
android:paddingRight="50dp"
android:gravity="center_vertical"
android:textColor="#ff828282" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_no"
android:layout_toLeftOf="#+id/tbl_yes"
android:layout_marginRight="2dp">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="161dp"
android:layout_height="50dp"
android:text="#string/inv_popup_btnCancel_title"
android:id="#+id/txtNo"
android:drawableRight="#drawable/ic_delete"
android:drawablePadding="10dp"
android:singleLine="true"
android:textSize="16dp"
android:background="#fff4f4f4"
android:paddingRight="50dp"
android:gravity="center_vertical|right"
android:textColor="#ff828282" />
</TableRow>
</TableLayout>
</RelativeLayout>
</RelativeLayout>
lstcstmrinvoicepopupitems.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"
android:background="#fff4f4f4"
android:paddingBottom="8dp"
android:paddingTop="3dp">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_check"
android:layout_alignParentRight="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inv_popupTaken" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="285dp"
android:layout_height="wrap_content"
android:id="#+id/tbl_name"
android:layout_toLeftOf="#+id/tbl_check"
android:layout_marginTop="7dp">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="צבע יסוד טרי מתאים לברזל וגם לעץ מהיר בייבוש"
android:id="#+id/inv_popupName"
android:textSize="15dp"
android:textColor="#ff000000"
android:singleLine="true" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_txtQuan"
android:layout_below="#+id/tbl_check"
android:layout_alignParentRight="true"
android:layout_marginRight="7dp"
android:layout_marginTop="3dp">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="45dp"
android:layout_height="wrap_content"
android:text="#string/inv_quan_title"
android:id="#+id/inv_txtQuan"
android:textSize="15dp"
android:textColor="#ff8c8a8a"
android:singleLine="true" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_edtQuan"
android:layout_below="#+id/tbl_check"
android:layout_toLeftOf="#+id/tbl_txtQuan">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="60dp"
android:layout_height="wrap_content"
android:id="#+id/inv_popupQuan"
android:background="#drawable/edittext"
android:text="15400"
android:textColor="#ff8c8a8a"
android:textSize="15dp"
android:singleLine="true" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_txtPrice"
android:layout_below="#+id/tbl_check"
android:layout_alignParentRight="false"
android:layout_marginRight="12dp"
android:layout_marginTop="3dp"
android:layout_toLeftOf="#+id/tbl_edtQuan">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="45dp"
android:layout_height="wrap_content"
android:text="#string/inv_price_title"
android:id="#+id/txt_Price"
android:textSize="15dp"
android:textColor="#ff8c8a8a"
android:singleLine="true" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_edtPrice"
android:layout_below="#+id/tbl_check"
android:layout_toLeftOf="#+id/tbl_txtPrice" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:layout_width="70dp"
android:layout_height="wrap_content"
android:id="#+id/inv_popupPrice"
android:background="#drawable/edittext"
android:text="19540.66"
android:textColor="#ff8c8a8a"
android:textSize="15dp"
android:singleLine="true" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_equal"
android:layout_below="#+id/tbl_check"
android:layout_alignParentRight="false"
android:layout_marginRight="2dp"
android:layout_marginTop="3dp"
android:layout_toLeftOf="#+id/tbl_edtPrice" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:id="#+id/txt_equal"
android:textSize="15dp"
android:textColor="#ff8c8a8a"
android:singleLine="true" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbl_total"
android:layout_below="#+id/tbl_check"
android:layout_alignParentRight="false"
android:layout_marginRight="2dp"
android:layout_marginTop="3dp"
android:layout_toLeftOf="#+id/tbl_equal" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="128549.87"
android:id="#+id/inv_popupTotal"
android:textSize="15dp"
android:textColor="#ff8c8a8a"
android:singleLine="true" />
</TableRow>
</TableLayout>
</RelativeLayout>
If the listview is not responding while being updated it means the "update" is doing heavy work on the main thread. What you want to do to make it smoother is delegate as much of this work to an other thread. This includes :
Network operations or any I/O operations
reading a database
parsing / unserializing JSON, xml, ... into objects
EDIT: As per your edit on the question, I can see you are doing some parsing in your onPostExecute() method of your asynctask which is executed on the main thread. You should do this work in the doInBackground() method and only update the adapter in the onPostExecute() method. In order to do that, you can return a list of MyInvoiceItems from your doInBackground method which will be passed as a parameter on your onPostExecute() method and then do something like this:
#Override
protected void onPostExecute(List<MyInvoiceItems> result) {
if(result == null)
Toast.makeText(itemsdialog.dialog.getContext(), R.string.msg_nointernet, Toast.LENGTH_LONG).show();
else{
itemsdialog.list_items.add(result);
itemsdialog.adapter_items.notifyDataSetChanged();
}
}
I think, your heavy work is here:setListViewHeightBasedOnChildren
this method will measure each child and get each item height,and add up to a total height for listView. (does it work so?).
as you have many rows,it will become a dangerous work.
this method works well at showing a few rows all in a vertical scrollview.
and, why you call notifyDatasetChange before dataset Changed?
itemsdialog.adapter_items.notifyDataSetChanged();
itemsdialog.finalData = itemsdialog.list_items;
It sounds like 10 items may even be too many. Try loading 1 at a time and see if performance improves.
I have a list-view with a custom list row. In each list-view's row, there is a Radio-group with 2 Radio-buttons.
I need to know the state of the RadioButtons, for each row of the ListView (checked or not), dynamically, as the user click on one of the RadioGroup's options.
My main xml:
<?xml version="1.0" encoding="utf-8"?>
<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="#fff3f2f2"
android:orientation="horizontal" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#00ffffff"
android:gravity="center" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ffffff"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="#string/titulo_cabecalho"
android:textColor="#ff000000"
android:textSize="36sp" >
</TextView>
</RelativeLayout>
<!-- Footer aligned to top -->
<include layout="#layout/footer" />
<RelativeLayout
android:id="#+id/selectEscola"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/footer"
android:layout_below="#id/header"
android:layout_centerInParent="true"
android:layout_marginBottom="10dp"
android:layout_marginTop="4dp"
android:background="#00ffffff"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Chamada"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#c0000000" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:layout_marginBottom="80dp"
android:scrollbars="none"
android:background="#drawable/border" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listChamada"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:padding="2dp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
</RelativeLayout>
My custom row is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:padding="2dip"
android:background="#drawable/border2" >
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="34dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip"
android:orientation="horizontal" >
<ImageView
android:id="#+id/listEdit"
android:layout_width="24dip"
android:layout_height="24dip"
android:layout_marginTop="2dip"
android:src="#drawable/list" />
<ImageView
android:id="#+id/list_image"
android:layout_width="24dip"
android:layout_height="24dip"
android:layout_marginLeft="20dip"
android:layout_marginTop="2dip"
android:src="#drawable/boy" />
</LinearLayout>
<TextView
android:id="#+id/nomealuno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/matriculaaluno"
android:layout_alignTop="#+id/thumbnail"
android:text="Nome:"
android:textColor="#040404"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/matriculaaluno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/nomealuno"
android:layout_marginTop="2dp"
android:layout_toRightOf="#+id/thumbnail"
android:text="Matrícula: "
android:textColor="#343434"
android:textSize="10sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="4dp"
android:orientation="vertical" >
<RadioGroup
android:id="#+id/radiogroupChamada"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:textColor="#343434"
android:textSize="12sp"
android:textStyle="bold" >
<RadioButton
android:id="#+id/radiobuttonPresente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#drawable/btn_check"
android:paddingLeft="22dip"
android:text="Presente" >
</RadioButton>
<RadioButton
android:id="#+id/radiobuttonAusente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#drawable/btn_check"
android:paddingLeft="22dip"
android:text="Ausente" >
</RadioButton>
</RadioGroup>
</LinearLayout>
</RelativeLayout>
This is how I populate the ListView:
1 - Code to put the data received from server received in Json format, in arrays and hashmap (I use the arrays to have a reference to the data present in the ListView and hashmap to populate it) :
if (success2 == 1) // If data from server was sent without errors
{
int lenght = jArray.length();
optionsMatriculas = new ArrayList<String>(lenght);
optionsNomesAlunos = new ArrayList<String>(lenght);
optionsSexoAlunos = new ArrayList<String>(lenght);
for (int i = 0; i < jArray.length(); i++)
{
try
{
JSONObject oneObject = jArray.getJSONObject(i);
resultDataCodigoAluno = oneObject.getString("cdaluno");
resultDataNomes = oneObject.getString("nome");
resultDataSexo = oneObject.getString("sexo");
optionsMatriculas.add(resultDataCodigoAluno);
optionsNomesAlunos.add(resultDataNomes);
optionsSexoAlunos.add(resultDataSexo);
HashMap<String, String> hm = new HashMap<String, String>();
if (resultDataSexo.equals("M"))
{
hm.put("sexo", Integer.toString(R.drawable.boy));
}
else
{
hm.put("sexo", Integer.toString(R.drawable.girl));
}
hm.put("matricula", resultDataCodigoAluno);
hm.put("nome", resultDataNomes);
alunosLista.add(hm);
}
catch (JSONException e)
{
Log.e("log_tag", "Error in parsing JSon: " + e.toString());
}
}
Message msg = myHandler.obtainMessage();
myHandler.sendMessage(msg);
}
This is the code to populate the listview:
final Handler myHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
try
{
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), alunosLista, R.layout.list_row, from, to);
listaChamada.setAdapter(adapter);
int lenght = adapter.getCount();
int totalHeight = 0;
for (int i = 0; i < lenght; i++)
{
View listItem = adapter.getView(i, null, listaChamada);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listaChamada.getLayoutParams();
params.height = totalHeight + 4 + (listaChamada.getDividerHeight() * (adapter.getCount() - 1));
listaChamada.setLayoutParams(params);
listaChamada.requestLayout();
}
catch (Exception e)
{
Log.e("log_tag", "Erro no ListView: " + e.toString());
}
}//handleMessage
};//myHandler
I have searched, in Google, but still no luck.
Thanks for any clue about this.
Actually, Android adapters is not that simple. SimpleAdapter can be applied only in some very simple/trivial cases. Usually, it's preferred to create own BaseAdapter: it gives much more flexibility and doesn't require lot of code.
In your case I would suggest to use smth like the following (You failed to provide any information about that is from and to in your SimpleAdapter constructor, so I guessed):
Main part is proper adapter, which should store selected radio button id and provide it back to the activity/receiver.
MyAdapter.java
public class MyActivity extends Activity implements MyListAdapter.RadioButtonsListener {
private static final String TAG = "MyActivity";
ArrayList<HashMap<String, String>> mAlunosLista = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView listaChamada = (ListView) findViewById(R.id.listChamada);
// Fill list with data
Random sexGen = new Random();
for (int i = 0; i < 20; i++) {
addTextData(sexGen.nextBoolean() ? "M" : "F", Integer.toString(i + 100), "Name" + i + " Surname" + i);
}
final MyListAdapter adapter = new MyListAdapter(mAlunosLista);
listaChamada.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
final MyListAdapter adapter = (MyListAdapter) ((ListView) findViewById(R.id.listChamada)).getAdapter();
adapter.setRadioListener(this);
}
#Override
protected void onPause() {
super.onPause();
final MyListAdapter adapter = (MyListAdapter) ((ListView) findViewById(R.id.listChamada)).getAdapter();
adapter.setRadioListener(null);
}
/**
* Adds test data to adapter array
*/
private void addTextData(final String resultDataSexo, final String resultDataCodigoAluno, final String resultDataNomes) {
HashMap<String, String> hm = new HashMap<String, String>();
// NOTE: not sure why you convert ids to strings
if (resultDataSexo.equals("M")) {
hm.put("sexo", Integer.toString(R.drawable.boy));
} else {
hm.put("sexo", Integer.toString(R.drawable.girl));
}
hm.put("matricula", resultDataCodigoAluno);
hm.put("nome", resultDataNomes);
mAlunosLista.add(hm);
}
#Override
public void onRadioButtonClicked(final int position, final HashMap<String, String> itemData, final int clickedId) {
Log.d(TAG, "Clicked item at " + position + ", checked id: " + (clickedId == R.id.radiobuttonPresente ? "Presente" : "Ausente"));
}
}
Below other files I've changed to have compilable example (please refer help topic on how to ask questions about code questions body).
main.xml
<?xml version="1.0" encoding="utf-8"?>
<!--suppress AndroidLintUselessParent, AndroidLintContentDescription -->
<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="#fff3f2f2"
android:orientation="horizontal" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#00ffffff"
android:gravity="center" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ffffff"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Title"
android:textColor="#ff000000"
android:textSize="36sp" >
</TextView>
</RelativeLayout>
<!-- Footer aligned to top
<include layout="#layout/footer" />
-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/footer"
android:layout_alignParentBottom="true" />
<RelativeLayout
android:id="#+id/selectEscola"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_above="#id/footer"
android:layout_below="#id/header"
android:layout_centerInParent="true"
android:layout_marginBottom="10dp"
android:layout_marginTop="4dp"
android:background="#00ffffff"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Chamada"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#c0000000" />
<ListView
android:id="#+id/listChamada"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#android:drawable/list_selector_background"
android:padding="2dp" />
</RelativeLayout>
</RelativeLayout>
list_row.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:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:padding="2dip"
android:background="#android:color/darker_gray" >
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="5dip"
android:padding="3dip"
android:orientation="horizontal" >
<ImageView
android:id="#+id/listEdit"
android:layout_width="24dip"
android:layout_height="24dip"
android:layout_marginTop="2dip"
android:src="#android:drawable/ic_menu_add" />
<ImageView
android:id="#+id/list_image"
android:layout_width="24dip"
android:layout_height="24dip"
android:layout_marginLeft="20dip"
android:layout_marginTop="2dip"
android:src="#android:drawable/ic_delete" />
</LinearLayout>
<TextView
android:id="#+id/nomealuno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/matriculaaluno"
android:layout_alignTop="#+id/thumbnail"
android:text="Nome:"
android:textColor="#040404"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/matriculaaluno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/nomealuno"
android:layout_marginTop="2dp"
android:layout_toRightOf="#+id/thumbnail"
android:text="Matrícula: "
android:textColor="#343434"
android:textSize="10sp" />
<RadioGroup
android:id="#+id/radiogroupChamada"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/thumbnail"
android:orientation="vertical"
android:textColor="#343434"
android:textSize="12sp"
android:textStyle="bold" >
<RadioButton
android:id="#+id/radiobuttonPresente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="22dip"
android:text="Presente" />
<!--android:drawableRight="#drawable/btn_check"-->
<RadioButton
android:id="#+id/radiobuttonAusente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="22dip"
android:text="Ausente" />
<!--android:drawableRight="#drawable/btn_check"-->
</RadioGroup>
</RelativeLayout>
MyActivity.java
public class MyActivity extends Activity implements MyListAdapter.RadioButtonsListener {
private static final String TAG = "MyActivity";
ArrayList<HashMap<String, String>> mAlunosLista = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView listaChamada = (ListView) findViewById(R.id.listChamada);
// Fill list with data
Random sexGen = new Random();
for (int i = 0; i < 20; i++) {
addTextData(sexGen.nextBoolean() ? "M" : "F", Integer.toString(i + 100), "Name" + i + " Surname" + i);
}
final MyListAdapter adapter = new MyListAdapter(mAlunosLista);
listaChamada.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
final MyListAdapter adapter = (MyListAdapter) ((ListView) findViewById(R.id.listChamada)).getAdapter();
adapter.setRadioListener(this);
}
#Override
protected void onPause() {
super.onPause();
final MyListAdapter adapter = (MyListAdapter) ((ListView) findViewById(R.id.listChamada)).getAdapter();
adapter.setRadioListener(null);
}
/**
* Adds test data to adapter array
*/
private void addTextData(final String resultDataSexo, final String resultDataCodigoAluno, final String resultDataNomes) {
HashMap<String, String> hm = new HashMap<String, String>();
// NOTE: not sure why you convert ids to strings
if (resultDataSexo.equals("M")) {
hm.put("sexo", Integer.toString(R.drawable.boy));
} else {
hm.put("sexo", Integer.toString(R.drawable.girl));
}
hm.put("matricula", resultDataCodigoAluno);
hm.put("nome", resultDataNomes);
mAlunosLista.add(hm);
}
#Override
public void onRadioButtonClicked(final int position, final HashMap<String, String> itemData, final int clickedId) {
Log.d(TAG, "Clicked item at " + position + ", checked id: " + (clickedId == R.id.radiobuttonPresente ? "Presente" : "Ausente"));
}
}
PS Also, it looks like You're trying to make some hack to ListView. I have no idea why do You need it here, but it's better to avoid until completely necessary.
i was previously populating my spinner with String[] array while testing, now i have changed it to use an ArrayList that retrieves the List from JSON service, the list displays fine but when i select an item the spinner does not display it(this does work when it was just using a declared array, all i have changed is how the list is created, i am new to programming in general and android so go easy on me if its obvious. i have genuinely looked through many other issues regarding the same topic and tutorials before posting this but cannot spot whats wrong with mine. Any help is much appreciated
import android.widget.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class AddCall extends Activity {
Spinner customer,jobType;
Button getSignature;
//String[] customerList={"Company1","Company2","Company3","Company4"};
//String[] jobTypeList={"Service","Phone","Installation","Upgrade"};
ArrayList<String> customerList = new ArrayList<String>();
ArrayList<String> jobTypeList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcall);
getCallTypes();
getCustomers();
//setup customer adapter
customer =(Spinner) findViewById(R.id.spinnerCustomer);
ArrayAdapter<String> customerAdapter = new ArrayAdapter<String>
(AddCall.this,R.layout.spinner_item_text,customerList);
customer.setAdapter(customerAdapter);
//setup jobtype adapter
jobType =(Spinner) findViewById(R.id.spinnerJobType);
ArrayAdapter<String> jobTypeAdapter = new ArrayAdapter<String>
(AddCall.this,R.layout.spinner_item_text,jobTypeList);
jobType.setAdapter(jobTypeAdapter);
//initialise Signature button
getSignature =(Button) findViewById(R.id.getSignature);
getSignature.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(AddCall.this, CaptureSignature.class);
startActivity(intent);
}
});
}
public void getCallTypes() {
DownloadCallTypes taskCallType = new DownloadCallTypes();
taskCallType.execute(new String[] { "http://192.168.0.14:8080/return_call_type.json" });
}
public void getCustomers() {
DownloadCustomers taskCustomers = new DownloadCustomers();
taskCustomers.execute(new String[] { "http://192.168.0.14:8080/return_customers.json" });
}
private class DownloadCallTypes extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... urls) {
ArrayList<String> response = new ArrayList<String>();
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
HttpEntity entity= execute.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
response.add(row.getString("call_type"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
String list="";
for (int i=0;i< result.size();i++){
list= result.get(i);
jobTypeList.add(list);
}
//textView.setText(list);
}
}
private class DownloadCustomers extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... urls) {
ArrayList<String> response = new ArrayList<String>();
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
HttpEntity entity= execute.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
response.add(row.getString("customer_name"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
String list="";
for (int i=0;i< result.size();i++){
list= result.get(i);
customerList.add(list);
}
//textView.setText(list);
}
}
}
and here is my xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#92add2">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fefefe" android:clickable="true" android:baselineAligned="false">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_gravity="left"
android:src="#drawable/header_image" android:adjustViewBounds="true"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:paddingTop="10dp">
<TextView
style="#style/text"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Customer"
android:id="#+id/tvCustomer" android:layout_weight="1"/>
<TextView
style="#style/text"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Job Type"
android:id="#+id/tvJobType" android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:layout_marginLeft="10dp" android:layout_marginRight="10dp">
<Spinner
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/spinnerCustomer" android:clickable="true"/>
<Spinner
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/spinnerJobType" android:clickable="true"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_margin="10dp">
<TextView
style="#style/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Address"
android:id="#+id/tvAddress"/>
<EditText
style="#style/editText"
android:layout_width="fill_parent"
android:layout_height="120dp"
android:text=""
android:id="#+id/etAddress"
android:background="#drawable/rounded_corners_white"
/>
<TextView
style="#style/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:id="#+id/tvPhone"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/etPhone"
android:background="#drawable/rounded_corners_white" android:textColor="#000000"
android:paddingLeft="10dp"/>
<TextView
style="#style/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/tvContact"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/etContact"
android:background="#drawable/rounded_corners_white"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="4" android:layout_margin="10dp">
<TextView
android:layout_weight="1"
style="#style/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Logged By"
android:id="#+id/tvLoggedBy" />
<EditText
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/etLoggedBy"
android:background="#drawable/rounded_corners_white"
style="#style/editText"/>
<TextView
android:layout_weight="1"
style="#style/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Date Logged"
android:id="#+id/tvDateLogged" android:layout_marginLeft="5dp"/>
<EditText
android:background="#drawable/rounded_corners_white"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/editText1"
style="#style/editText"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call Notes"
android:id="#+id/textView1" style="#style/text"/>
<EditText
android:background="#drawable/rounded_corners_white"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:id="#+id/etCallNotes" style="#style/editText"
android:gravity="left|top"/>
</LinearLayout>
<LinearLayout
android:weightSum="4"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<Button
style="#style/btnStyleOrange"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/bSave" android:layout_gravity="center"
android:layout_marginRight="5dp"/>
<Button
android:layout_weight="1"
style="#style/btnStyleOrange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:id="#+id/bClose" android:layout_gravity="center"/>
<CheckBox
android:layout_weight="1"
style="#style/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="Completed"
android:id="#+id/checkBox"/>
<Button
android:layout_weight="1"
style="#style/btnStyleOrange"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="Signature"
android:id="#+id/getSignature"/>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Real Document Management"
android:id="#+id/textView2" style="#style/text"
android:gravity="center_vertical|center_horizontal"
/>
</LinearLayout>
This is because you are setting the Adapter in the main thread, while AsyncTask has not finished. Simply add the following line at the end of your onPostExecute methods:
#Override
protected void onPostExecute(ArrayList<String> result) {
String list="";
for (int i=0;i< result.size();i++){
list= result.get(i);
jobTypeList.add(list);
}
//textView.setText(list);
jobTypeAdapter.notifyDataSetChanged();
}
and
#Override
protected void onPostExecute(ArrayList<String> result) {
String list="";
for (int i=0;i< result.size();i++){
list= result.get(i);
customerList.add(list);
}
//textView.setText(list);
customerAdapter.notifyDataSetChanged();
}
You should basically do this each time you change the backing ArrayList.
Note: You will need to declare customerAdapter & jobTypeAdapter as class level variables to be visible in AsyncTask classes.
I have a list view inside a ViewSwitcher that works fine in android version 2.2 but it does not show in my device which has android 4.1.2 version.
I also debugg it and dont see any errors, and also checked to see if the list I pass to adapter is not null, and saw that it was not empty.
I have another list view which is located in a TabHost that is being shown correctly.
Regards
Edited:
Here is my code:
<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/viewswitcher"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical"
android:layout_gravity="center|top"
>
<TextView
android:id="#+id/dateLbl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/lblChooseaDate" />
<DatePicker
android:id="#+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center" />
<Button
android:id="#+id/btnChooseDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/startdayexpensebtn" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical"
>
<TextView
android:id="#+id/descLbl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:text="#string/lbldaydescription" />
<EditText
android:id="#+id/dayDesctiptionText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:singleLine="false"
android:minLines="1"
android:maxLines="3"
android:inputType="textMultiLine" />
<Button
android:id="#+id/addnewItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:enabled="false"
android:text="#string/btnAddnewItem" />
<LinearLayout
android:id="#+id/listcontaioner"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="250dp"
android:scrollbars="vertical"
>
<ListView
android:id="#+id/android:list"
android:divider="#bababa"
android:dividerHeight="1dp"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp" >
</ListView>
</LinearLayout>
<LinearLayout
android:id="#+id/btnlinearlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="bottom"
android:paddingRight="10dp"
android:paddingLeft="10dp" >
<Button
android:id="#+id/cancelbtn"
android:layout_weight="2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btncancel" />
<Button
android:id="#+id/savebtn"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btnAdd" />
</LinearLayout>
</LinearLayout>
</ViewSwitcher>
also for each row:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp" >
<ImageView
android:id="#+id/expenselisitem_imgaetype"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_marginLeft="5dp"
android:layout_marginBottom="35dp"
android:src="#drawable/fail" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/expenselisitem_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/expenselisitem_category"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="#+id/expenselisitem_desc"
android:paddingBottom="6dp"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/expenselisitem_amount"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignBaseline="#+id/expenselisitem_category"
android:layout_alignBottom="#+id/expenselisitem_category"
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:paddingBottom="6dp"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
and here is the adapter:
public class CustomAddExpenseItemListAdapter extends BaseAdapter {
private ArrayList<ExpenseItem> _list=new ArrayList<ExpenseItem>();
private final Activity _context;
private static LayoutInflater inflater=null;
public CustomAddExpenseItemListAdapter(Activity activity,ArrayList<ExpenseItem> data){
_list = data;
_context=activity;
}
public long getItemId(int position) {
return position;
}
public int getCount() {
return _list.size();
}
public Object getItem(int position) {
return position;
}
static class ViewHolder {
protected TextView _cexpenseDesctiption;
protected TextView _cAmount;
protected ImageView _cType;
protected TextView _cCategory;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=null;
if(convertView==null)
{
inflater = _context.getLayoutInflater();
vi = inflater.inflate(R.layout.expense_item_list_row, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder._cexpenseDesctiption= (TextView) vi.findViewById(R.id.expenselisitem_desc);
viewHolder._cAmount = (TextView) vi.findViewById(R.id.expenselisitem_amount);
viewHolder._cType=(ImageView)vi.findViewById(R.id.expenselisitem_imgaetype);
viewHolder._cCategory=(TextView)vi.findViewById(R.id.expenselisitem_category);
vi.setTag(viewHolder);
}
else
{
vi = convertView;
}
ViewHolder holder = (ViewHolder) vi.getTag();
ExpenseItem item;
item = _list.get(position);
holder._cexpenseDesctiption.setText(item.get_description());
holder._cAmount.setText(String.valueOf(item.get_amount()));
if(item.get_type()==0)
{
holder._cCategory.setText(item.get_category().get_title());
holder._cType.setImageResource(R.drawable.downarrow);
}
else
{
holder._cCategory.setText("-");
holder._cType.setImageResource(R.drawable.uparrow);
}
return vi;
}
}
Usually this is solved by wrapping the ListView inside a LineaLayout or RelativeLayout but depending on the problem you've countered the solution might be something entirely different.
Here is a working example of a ViewSwitcher that switches between a ListView and TextView.
From the following XML text you can see that ListView has been wrapped in a RelativeLayout together with a Button that enables the switch between the views(layouts).
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ViewSwitcher
xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "#+id/viewswitcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Show Next" />
<ListView android:id="#+id/listview" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_above="#id/btn_next"></ListView>
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text"
android:layout_height="fill_parent"
android:layout_width="wrap_content"
android:text="HEllO WORLD">
</TextView>
<Button
android:id="#+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Previous" />
</LinearLayout>
</ViewSwitcher>
</RelativeLayout>
And here is the Java code that delivers the magic:
public class MainActivity extends Activity {
ViewSwitcher mViewSwitcher;
ListView listview;
String[] values = new String[] { "Hello1", "Hello2", "Hello3",
"Hello4", "Hello5", "Hello6", "Hello7", "Hello8",
"Hello9", "Hello10", "Hello11", "Hello12", "Hello13", "Hello14",
"Hello15"};
Button shownext;
Button showprevious;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewSwitcher = (ViewSwitcher)findViewById(R.id.viewswitcher);
listview = (ListView) findViewById(R.id.listview);
shownext = (Button)findViewById(R.id.btn_next);
showprevious = (Button)findViewById(R.id.btn_previous);
shownext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mViewSwitcher.showNext();
}
});
showprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mViewSwitcher.showPrevious();
}
});
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This has been tested successfully on Android 4.1.2.
Hope that helps!