Android Base Adapter not writing to text view - android

I have a problem, the class DataListAdapter is not writing to the text views given to it, leaving the text views blank. The activity which this concerns is thus:
public class LoadData extends Activity
{
ListView dataList;
MachineDataAdapter adapter;
Context context;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.load_data);
dataList = (ListView) findViewById(R.id.machineList);
//Log.d("intent", getIntent().getStringExtra("json"));
dataList.setAdapter(new DataListAdapter(getIntent().getStringExtra("json")));
context = this;
}
public void backClicked(View view)
{
Intent mainMenu = new Intent(getApplicationContext(), MainMenu.class);
startActivity(mainMenu);
}
public void launchScan(View view)
{
Intent scanLaunch = new Intent(getApplicationContext(), ScanTag.class);
startActivity(scanLaunch);
}
class DataListAdapter extends BaseAdapter
{
private JSONObject json;
private Iterator<String> keys;
LayoutInflater inflater;
public DataListAdapter(String jsonString)
{
try
{
json = new JSONObject(jsonString);
} catch (JSONException e)
{
e.printStackTrace();
}
keys = json.keys();
inflater = getLayoutInflater();
}
public int getCount() {
return json.names().length();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int i, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = inflater.inflate(R.layout.machine_data_row, parent, false);
TextView title = (TextView) convertView.findViewById(R.id.machineRowTitle);
TextView data = (TextView) convertView.findViewById(R.id.machineRowData);
if(keys.hasNext())
{
String key = keys.next();
String value = null;
try
{
value = json.getString(key);
} catch (JSONException e)
{
e.printStackTrace();
}
Log.d("json", key);
title.setText(key);
data.setText(value);
}
return (convertView);
}
}
}
And here is machine_data_row.xml for completeness:
<?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/machineRowTitle"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#0000FF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/machineRowData"
android:textColor="#5C002E"
android:textSize="17sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
The json works just fine, I am successfully printing each key using Log.d. Any help would be greatly appreciated.
Edit: This is the json data:
{"a":"b","c":"d","e":"f"}

Typically I like to do something like this in the getView:
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
//Make sure the textview exists in this xml
} else {
row = convertView;
}
TextView titleLabel = (TextView) row.findViewById(R.id.titleText);

I have no idea why this worked, but getting the key using key = json.names().getString(i);
Solved the issue.

Related

Android: Custom ArrayAdapter not working, getView() not getting called

I am using CustomArrayAdapter with ListView. But, even after setting setAdapter it is not working. Following are my code snippets:
PastOrders.java Fragment displaying listView
public class PastOrders extends Fragment {
private View view;
private ListView pastOrdersList;
private Context context;
private ArrayList<Order> orders;
public PastOrders() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.fragment_pastorders, container, false);
context = getActivity();
pastOrdersList = (ListView) view.findViewById(R.id.pastOrdersList);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Order");
query.whereEqualTo("user_id", Vars.currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e != null) {
Log.e("TAG", e.getLocalizedMessage());
} else {
ArrayList<Order> orders = new ArrayList<Order>();
Log.i("TAG", objects.toString());
for (ParseObject object: objects) {
Order temp = new Order();
temp.orderId = object.getObjectId();
temp.date = object.getCreatedAt();
temp.status = object.getString("status");
Log.i("TAG", "orderID: "+ object.getObjectId() + " temp orderID"+ temp.orderId);
orders.add(temp);
Vars.pastOrders.add(object);
}
Log.i("TAG", "after for loop past orders: "+ orders.toString());
PastOrdersAdapter pastOrdersAdapter = new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, orders);
pastOrdersList.setAdapter(pastOrdersAdapter);
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
PastOrdersAdapter.java Custom Adapter
public class PastOrdersAdapter extends ArrayAdapter<Order> {
private Context context;
private ViewHolder holder;
//private ArrayList<Order> orders;
public PastOrdersAdapter(Context context, int resource, List<Order> orders) {
super(context, resource);
// this.orders = orders;
Log.i("TAG", "POA adapter called");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("TAG", "getView from POA");
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = inflater
.inflate(R.layout.past_orders_row, parent, false);
holder = new ViewHolder();
holder.orderId = (TextView) convertView.findViewById(R.id.orderId);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.details = (ImageView) convertView.findViewById(R.id.details);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject order = Vars.pastOrders.get(position);
Log.i("TAG", "order id in adapter: "+ order.getObjectId());
if(order != null) {
holder.orderId.setText(order.getObjectId());
holder.date.setText(getFormattedDate(order.getCreatedAt()));
holder.status.setText(order.getString("status"));
if(order.getString("status").equals("Delivered")) {
holder.status.setTextColor(Color.GREEN);
} else if(order.getString("status").equals("Cancelled")) {
holder.status.setTextColor(Color.RED);
} else {
holder.status.setTextColor(Color.YELLOW);
}
}
return convertView;
}
static class ViewHolder {
TextView orderId;
TextView date;
TextView status;
ImageView details;
}
}
Order.java
public class Order {
public String orderId;
public Date date;
public String status;
}
fragment_pastorders.xml Layout File for Fragment showing ListView
<?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" >
<ListView
android:id="#+id/pastOrdersList"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
past_orders_row.xml Layout file for each row of listview
<?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="150dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="150dp"
android:orientation="vertical"
android:id="#+id/LinearLayout01">
<TextView
android:id="#+id/orderId"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textStyle="italic"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/status"/>
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_next_item"
android:layout_toRightOf="#id/LinearLayout01"
android:layout_centerVertical="true"
android:id="#+id/details"/>
</RelativeLayout>
I have tried printing getCount() as well and it is non-zero. I have tried everything. Kindly help
Thanks,
Arpit
In the constructor of your custom adapter, your forgot to pass your orders parameter to the parent constructor. So your adapter does not know what to display.
You are passing empty list orders to you adapter. And then in adapter you are using different list: Vars.pastOrders.
So your adapter has empty list.
Replace this:
PastOrdersAdapter pastOrdersAdapter =
new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, orders);
with this:
PastOrdersAdapter pastOrdersAdapter =
new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, Vars.pastOrders);

listview does not show anything

i can not figure out the problem my listview suddenly disappeared. I searched solution and tried every possible change in xml file but i still get the empty screen.
xml for listview
<?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="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
listview items
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/dcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="drcode"
android:textColor="#000000" />
<TextView
android:id="#+id/dname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="18dp"
android:text="docname"
android:textColor="#000000" />
<TextView
android:id="#+id/a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="43dp"
android:text="adr"
android:textColor="#000000" />
<TextView
android:id="#+id/cd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="38dp"
android:layout_toRightOf="#+id/adr"
android:text="class_desc"
android:textColor="#000000" />
<TextView
android:id="#+id/tvshift"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="25dp"
android:text="shift"
android:textColor="#000000" />
<TextView
android:id="#+id/tcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="24dp"
android:layout_toRightOf="#+id/docname"
android:text="terrcode"
android:textColor="#000000" />
code of listview adapter
public class planningListViewAdapter extends BaseAdapter {
Context context;
public ArrayList<Planning> planArraylist;
private static LayoutInflater inflater = null;
public Activity attdSetupActivity;
public planningListViewAdapter(Context context,ArrayList<Planning> planArraylist) {
this.context = context;
this.planArraylist = planArraylist;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return planArraylist.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_lv_item, null);
}
Planning p = planArraylist.get(position);
TextView tvdrCode = (TextView) convertView.findViewById(R.id.dcode);
TextView tvDrName = (TextView) convertView.findViewById(R.id.dname);
TextView tvTerr = (TextView) convertView.findViewById(R.id.tcode);
TextView tvAdr = (TextView) convertView.findViewById(R.id.a);
TextView tvClassDesc = (TextView) convertView.findViewById(R.id.cd);
//TextView tvSpeciality= (TextView) convertView.findViewById(R.id.speciaility);
TextView tvShift = (TextView) convertView.findViewById(R.id.tvshift);
tvdrCode.setText(p.getDrCode());
tvDrName.setText(p.getDocName());
tvTerr.setText(p.getTerrCode());
tvAdr.setText(p.getAdr());
tvClassDesc.setText(p.getClassDesc());
//tvSpeciality.setText(p.getSpeciality());
tvShift.setText(p.getShift());
return convertView;
}
}
Activity code
public class PlanningList_activity extends Activity{
private Db_sqlite dbHelper;
private planningListViewAdapter dataAdapter;
private ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.planning_listview);
/* TextView columnHeader1 = (TextView) findViewById(R.id.column_header1);
TextView columnHeader2 = (TextView) findViewById(R.id.column_header2);
TextView columnHeader3 = (TextView) findViewById(R.id.column_header3);
TextView columnHeader4 = (TextView) findViewById(R.id.column_header4);
TextView columnHeader5 = (TextView) findViewById(R.id.column_header5);
TextView columnHeader6 = (TextView) findViewById(R.id.column_header6);
columnHeader1.setText("Plan No");
columnHeader2.setText("Plan Date");
columnHeader2.setText("Mon");
columnHeader2.setText("Dr Code");
columnHeader2.setText("Morn_Even");
columnHeader2.setText("FF_Code"); */
Log.e("on create", "yes");
listView = (ListView) findViewById(R.id.listView1);
dbHelper = new Db_sqlite(PlanningList_activity.this);
new AsyncLoadplanList().execute();
}
public class AsyncLoadplanList extends
AsyncTask<Void, Void, ArrayList<Planning>> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(PlanningList_activity.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
Log.e("pre execute", "yes");
}
#Override
public ArrayList<Planning> doInBackground(Void... params) {
try {
Log.e("In background", "yee");
return loadData();
} catch (Exception e) {
Log.e("get lost", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Planning> result) {
super.onPostExecute(result);
dbHelper.close();
Log.e("data saving", "yoo");
dataAdapter = new planningListViewAdapter(getApplicationContext(),result);
listView.setAdapter(dataAdapter);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
Toast.makeText(getApplicationContext(), "data loaded",Toast.LENGTH_LONG).show();
}
private ArrayList<Planning> loadData() {
// Load data here from database
return dbHelper.getPlanningList();
}
}
Database method
public ArrayList<Planning> getPlanningList() {
SQLiteDatabase db = getReadableDatabase();
ArrayList<Planning> planningList = new ArrayList<Planning>();
Cursor mCursor = db.query(DOC_PLANNING_TABLE_NAME, null,null,null,null,null,null);
if (mCursor != null && mCursor.moveToFirst()) {
do {
Planning planning = new Planning();
String docCode = mCursor.getString(mCursor.getColumnIndex(DCP_COLUMN_dr_code));
String planno = mCursor.getString(mCursor.getColumnIndex(DCP_COLUMN_PLAN_NO));
String terrCode = mCursor.getString(mCursor
.getColumnIndex(DCP_COLUMN_terr_code));
String adr = mCursor.getString(mCursor
.getColumnIndex(DCP_COLUMN_PLAN_DATE));
String classdesc= mCursor.getString(mCursor
.getColumnIndex(DCP_COLUMN_MON));
String speciality= mCursor.getString(mCursor
.getColumnIndex(DCP_COLUMN_REF_NO));
String shift= mCursor.getString(mCursor
.getColumnIndex(DCP_COLUMN_MORN_EVEN));
planning.setDrCode(docCode);
planning.setDocName(planno);
planning.setTerrCode(terrCode);
planning.setAdr(adr);
planning.setClassDesc(classdesc);
planning.setShift(shift);
planning.setSpeciality(speciality);
} while (mCursor.moveToNext());
mCursor.close();
}
return planningList;
}
I have wasted a lot of time finding the problem but i cannnot understand why it is not showing on the screen. please guide me.
Correct in your code as below:
#Override
public Object getItem(int arg0) {
return planArraylist.get(planArraylist.get(arg0-1)); }
#Override
public long getItemId(int arg0) {
return arg0; }
I think you write you getView method differently and use a holder class, as shown below:
#Override
public Object getItem(int arg0) {
return planArraylist.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.single_lv_item, parent, false);
holder = new ViewHolder();
holder.tvdrCode = (TextView) convertView.findViewById(R.id.dcode);
holder.tvDrName = (TextView) convertView.findViewById(R.id.dname);
holder.tvTerr = (TextView) convertView.findViewById(R.id.tcode);
holder.tvAdr = (TextView) convertView.findViewById(R.id.a);
holder.tvClassDesc = (TextView) convertView.findViewById(R.id.cd);
holder.tvShift = (TextView) convertView.findViewById(R.id.tvshift);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Planning p = planArraylist.get(position);
holder.tvdrCode.setText(p.getDrCode());
holder.tvDrName.setText(p.getDocName());
holder.tvTerr.setText(p.getTerrCode());
holder.tvAdr.setText(p.getAdr());
holder.tvClassDesc.setText(p.getClassDesc());
holder.tvShift.setText(p.getShift());
return convertView;
}
static class ViewHolder {
TextView tvdrCode;
TextView tvDrName;
TextView tvTerr;
TextView tvAdr;
TextView tvClassDesc;
TextView tvShift;
}
Also, your list view xml file uses a Linear layout but you have properties that can only be found in a Relative layout such as android:layout_alignParentTop="true". Could you fix that as well?

CheckBox in custom ListView on Android

I got a custom ListView, and I put three TextView in the List using a custom List Adapter! How I can to add a CheckBox with each List Item and make each CheckBox checked on list item click?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#7a4b9d"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/calorie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="sdf"
android:textColor="#ffffff" />
<TextView
android:id="#+id/price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="sdf"
android:textColor="#ffffff" />
<CheckBox
android:id="#+id/chkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox" />
</LinearLayout>
MainActivity
public class Main_Activity extends Fragment implements OnClickListener {
private ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.main_activity, null);
ArrayList<SearchResults> searchResults = GetSearchResults();
final ListView lv = (ListView) root.findViewById(R.id.list_two);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(true);
lv.setAdapter(new MyCustomBaseAdapter(getActivity(), searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
boolean result = searchResults.get(position).isSolved();
if (result) {
searchResults.get(position).setSolved(false);
} else {
searchResults.get(position).setSolved(true);
}
Toast.makeText(getActivity(),"You have chosen: " + " " +
fullObject.getPhone(), Toast.LENGTH_SHORT).show();
}
});
return root;
}
private ArrayList<SearchResults> GetSearchResults() {
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr = new SearchResults();
sr.setName("Apple");
sr.setCalorie("35");
sr.setPrice("5");
results.add(sr);
return results;
}
}
Custom Base Adapter
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtCalorie = (TextView) convertView
.findViewById(R.id.calorie);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.chkBox1 = (CheckBox)convertView.findViewById(R.id.chkBox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtCalorie.setText(searchArrayList.get(position)
.getCalorie());
holder.txtPrice.setText(searchArrayList.get(position).getPrice());
holder.chkBox1.setChecked(searchArrayList.get(position).isSolved());
return convertView;
}
static class ViewHolder {
CheckBox chkBox1;
TextView txtName;
TextView txtCalorie;
TextView txtPrice;
}
Search Results
public boolean isSolved() {
// TODO Auto-generated method stub
return b;
}
public void setSolved(boolean b) {
// TODO Auto-generated method stub
this.b = b;
}
You will have to define your CheckBox view in custom_row_view.xml file first,
<CheckBox android:id="#+id/chkBox1"
android:layout_width=...
android:layout_height=... />
Then, you wll have to call this reference in your MyCustomBaseAdapter class or in the holder in your case, like
CheckBox chkBox1;
then,
holder.chkBox1 = = (CheckBox)convertView.findViewById(R.id.chkBox1);
You can define a boolean value in your SearchResults class which can take care of chkBox check and use
holder.chkBox1.setChecked(searchArrayList.get(position).isSolved());
Something on these lines and you will be good to go :)
EDIT: Remember to change the value of boolean in searchResult instance on itemClick.
boolean result = searchResults.get(position).isSolved();
if (result) {
searchResults.get(position).setSolved(false);
} else {
searchResults.get(position).setSolved(true);
}
lv.getAdapter().notifyDataSetChanged();

android edittext custom listview

I have a custom listview with textview and edittext.there is no problem when listview has 6 item or less but more than 6 item listview like this video .How can I solve this problem?
public class Form2 extends ListActivity {
CustomListAdapter cla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form2);
cla = new CustomListAdapter(this);
setListAdapter(cla);
}
my custom adapter is
public class CustomListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
private ArrayList<Siparis> notlar;
public CustomListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
notlar = new ArrayList<Siparis>();
DBHandler db = new DBHandler(context);
db.getWritableDatabase();
notlar=db.getSiparis();
db.close();
}
#Override
public int getCount() {
return notlar.size();
}
#Override
public Siparis getItem(int position) {
return notlar.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_kap, null);
holder = new ViewHolder();
holder.mKonu = (TextView) convertView.findViewById(R.id.malzeme);
holder.mTarih2 = (EditText) convertView.findViewById(R.id.miktar);
}
else {
holder = (ViewHolder) convertView.getTag();
}
//holder.mTarih2.setText(String.valueOf(notlar.get(position).miktar));
holder.mKonu.setText(notlar.get(position).malzeme_adi);
convertView.setTag(holder);
return convertView;
}
public class ViewHolder {
TextView mKonu;
EditText mTarih2;
}
}
You need to implement the ViewHolder pattern.
See this blog post for more details: http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_kap, null);
holder = new ViewHolder();
holder.mKonu = (TextView) convertView.findViewById(R.id.malzeme);
holder.mTarih2 = (EditText) convertView.findViewById(R.id.miktar);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mTarih2.setText(String.valueOf(notlar.get(position).miktar));
holder.mKonu.setText(notlar.get(position).malzeme_adi);
return convertView;
}
public static class ViewHolder {
TextView mKonu;
EditText mTarih2;
}
hi this is my solution handmade listview
xml file:
<?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:layout_weight="1"
android:orientation="vertical" >
<ScrollView
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/mylinear"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="fill_parent"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
<LinearLayout
android:id="#+id/group4ff"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/vazgecff"
android:layout_width="0dp"
android:layout_weight=".30"
android:layout_height="wrap_content"
android:onClick="cagir"
android:text="vazgec" />
<Button
android:id="#+id/kaydetff"
android:layout_width="0dp"
android:layout_weight=".70"
android:layout_height="wrap_content"
android:onClick="cagir"
android:text="kaydet" />
</LinearLayout>
</LinearLayout>
java code:
public class Form3 extends Activity {
LinearLayout[] llx ;
TextView[] tx ;
EditText[] ex ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form3);
DBHandler db = new DBHandler(this);
ArrayList<Siparis> listem = db.getSiparis();
db.close();
LinearLayout ll = (LinearLayout) findViewById(R.id.mylinear);
llx = new LinearLayout[listem.size()];
tx = new TextView[listem.size()];
ex = new EditText[listem.size()];
for (int i = 0; i < listem.size(); i++) {
llx[i] = new LinearLayout(this);
tx[i] = new TextView(this);
ex[i] =new EditText(this);
tx[i].setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT,0.8f));
ex[i].setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT,0.2f));
tx[i].setText(listem.get(i).getMalzeme_adi());
ex[i].setInputType(InputType.TYPE_CLASS_NUMBER);
llx[i].setId(i);
llx[i].setClickable(true);
final int j = i;
llx[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
msg(tx[j].getText().toString());
}
});
llx[i].addView(tx[i]);
llx[i].addView(ex[i]);
ll.addView(llx[i]);
}
}
private void msg(String x){
Toast.makeText(this, x, Toast.LENGTH_LONG).show();
}
public void cagir(View view){
switch (view.getId()) {
case R.id.kaydetff:
for (int i = 0; i < ex.length; i++) {
if(!ex[i].getText().toString().equals("")){
Log.e(tx[i].getText().toString(),ex[i].getText().toString());
}
}
break;
default:
break;
}
}
}
So the problem is when getView() is called you need to set the value of the EditText just like you set the value of the TextView
So each time the user types something, you put the value in the corresponding Siparis object. At the time of getView() you pick out the value from the object and set it in the view.
This is what you are doing with your TextView (Item1, Item2.. etc) They are never displayed wrongly. But with the edit text, since the value changes, you must update the miktar variable of the corresponding Siparis object. And bind it on getView()
...
...
holder.mKonu.setText(notlar.get(position).malzeme_adi);
//every time the user changes the edit text, save
//the current value of the edit text to retrieve later
holder.mTarih2.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable editable) {
notlar.get(position).miktar = Integer.parseInt(editable.toString());
}
....
};
holder.mTarih2.setText(String.valueOf(notlar.get(position).miktar));
...
Take a look at this similar question. The answer recommends exactly the same thing.

Gridview click not working inside the Custom Listview

I'm using gridview inside a Listview, but I have a focusable problem.
I have set the width of the gridview, but I fill some items of gridview, on the left space of gridview (which is blank) means items not fill of gridview in listview. If I click on it, it does not perform a listitem click
As given in the image, I want to perform a listview item click if it is clicked anywhere in the list item. I want to get a listitem click.
But when I click on ListView item, that is, GridView then the ListItem click is not working...
public class History extends Activity {
String name, id, description, count, total;
ArrayList<String> TAG_ID = new ArrayList<String>();
ArrayList<String> TAG_COFFEESHOP_NAME = new ArrayList<String>();
ArrayList<String> TAG_COUNT = new ArrayList<String>();
ArrayList<String> TAG_TOTAL = new ArrayList<String>();
Context context;
JSONArray CoffeeUser = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
ListView listView = (ListView) findViewById(R.id.listnew);
listView.setAdapter(new MyCustomAdapter());
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
{
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)paramAnonymousView.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
}
class MyCustomAdapter extends BaseAdapter {
Context ctx;
public MyCustomAdapter() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
SharedPreferences prfs = getSharedPreferences("GUID_FILE_NAME", Context.MODE_PRIVATE);
JSONObject json = jParser.methodhistory("http://api.com");
try {
// Getting Array of Employee
CoffeeUser = json.getJSONArray("CoffeeUser");
// Looping of List
for (int i = 0; i < CoffeeUser.length(); i++) {
JSONObject c = CoffeeUser.getJSONObject(i);
// Storing each json item in variable
id = c.getString("CS_Id");
name = c.getString("ShopName");
count = c.getString("totalstamps");
total = c.getString("threshholdcount");
// Adding all get values into array
if (name != "null") {
TAG_COFFEESHOP_NAME.add(name);
TAG_ID.add(id);
TAG_TOTAL.add(total);
TAG_COUNT.add(count);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return TAG_COFFEESHOP_NAME.size();
}
#Override
public Object getItem(int paramInt) {
return TAG_COFFEESHOP_NAME.get(paramInt);
}
#Override
public long getItemId(int paramInt) {
return paramInt;
}
public class MyCustomHolder {
public GridView localGrid;
public TextView CoffeeShopName,coffeeshopsdescription,coffeeshopid;
}
#Override
public View getView(int paramInt, View paramView,ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) History.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.historylist, null);
holder = new MyCustomHolder();
holder.CoffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
holder.localGrid = (GridView) localView.findViewById(R.id.gridViewdistorylist);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.CoffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
holder.localGrid.setAdapter(new GridAdapterA(History.this, TAG_TOTAL.get(paramInt), TAG_COUNT.get(paramInt)));
holder.localGrid.setFocusable(false);
holder.localGrid.setFocusableInTouchMode(false);
holder.CoffeeShopName.setFocusable(false);
holder.CoffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
}
public class GridAdapterA extends BaseAdapter {
private Context context;
String total,count;
public GridAdapterA(Context context) {
this.context = context;
}
public GridAdapterA(Context context, String total, String count) {
// TODO Auto-generated constructor stub
this.context = context;
this.total = total;
this.count = count;
}
public boolean areAllItemsEnabled()
{
return false;
}
public boolean isEnabled(int position)
{
return false;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.customgrid_row, null);
gridView.setFocusable(false);
ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_item_image);
imageView.setFocusable(false);
int i = 0;
if(count!="null")
i = Integer.parseInt(count);
if (position<i ) {
//imageView.setImageResource(R.drawable.ii);
// textView.setText(gridlist[position]);
}
else {
imageView.setImageResource(R.drawable.changedcup);
// textView.setText("");
}
}
else {
gridView = (View) convertView;
}
/*gridView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent); }
});*/
return gridView;
}
#Override
public int getCount() {
int j=0;
if(total!="null"){
j = Integer.parseInt(total);
}
return j;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
}
historylist
<?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:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:background="#drawable/image_bg"
android:padding="3dip" >
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/rcup" />
</LinearLayout>
<!-- hlcoffeeshopname Of Song -->
<TextView
android:id="#+id/hlcoffeeshopname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Rihanna Love the way lie"
android:textColor="#040404"
android:textSize="20dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/hlcoffeeshopid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridViewdistorylist"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/hlcoffeeshopname"
android:layout_toRightOf="#+id/thumbnail"
android:columnWidth="20dp"
android:background="#null"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
android:numColumns="10"
android:stretchMode="none" >
</GridView>
</RelativeLayout>
New GetView
#Override
public View getView(int paramInt,
View paramView,
ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) CopyOfHistory.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.copyhistorylist, null);
holder = new MyCustomHolder();
holder.coffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.coffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
int looplimit = Integer.parseInt(TAG_TOTAL.get(paramInt));
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
} else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
}
holder.coffeeShopName.setFocusable(false);
holder.coffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView) v
.findViewById(R.id.hlcoffeeshopid)).getText());
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
You might have solved it, but I have another solution that may help someone.
Use android:descendantFocusability="beforeDescendants" in the root layout of your list_cell XML.
Order to have lists within other lists. You must generate a custom view. If you want one the simple, consisting of a Java class and an XML file, then in the code you only have to instantiate it and add it to a linear layout.
Here I leave a small example.
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<TextView
android:id="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical"
android:text="-"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtListadoZonasNombreZona"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_toRightOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:singleLine="true"
android:text="TextView"
android:textColor="#000000" />
</RelativeLayout>
Java code
public class CVTexto extends RelativeLayout {
public TextView txtTexto;
public int idCv;
public CVTexto(Context context) {
super(context);
// TODO Auto-generated constructor stub
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs) {
super(context, attrs);
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs, int defStyle) {
super( context, attrs, defStyle );
IniciarCuadro();
}
private void IniciarCuadro()
{
//Utilizamos el layout 'control_login' como interfaz del control
String infService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li =
(LayoutInflater)getContext().getSystemService(infService);
li.inflate(R.layout.ll_adapter_listado_zonas_asignadas_usuario, this, true);
AsignarElemetos();
//Obtenemoslas referencias a los distintos control
//Asociamos los eventos necesarios
// asignarEventos();
}
private void AsignarElemetos(){
txtTexto = (TextView)findViewById(R.id.txtListadoZonasNombreZona);
}
}
Add to linearlayout:
cvTextp objCV = new cvTexto(context);
LinearLayout.addView(objCv);
And delete views:
LinearLayout.removeallViews;
I got this answer by changing the grid layout to LinearLayout. I added items dynamically into linearLayout, and then my problem was solved.
I have done research on it and I get to know that inside a scrollable widget which uses an adapter you should not use any other widget which is scrollable which also uses an adapter such as gridview inside listview because of touch events complexity.
So I think you should move to another approach for this. In your case, you can add a linear layout and can add cup images dynamically into that layout by setting parameters. I hope this helped you.
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}

Categories

Resources