I am using a loop to read all the spinner elements (inside a cardview) in the listview.
But the loop gives one item less i.e. the last item.
I have included all the source code.
What may be the problem?
Is there any other way to read all the items in listview?
Main Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/ll_gpa"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ListView
android:id="#+id/listSubs"
android:scrollbars="none"
android:layout_height="0dip"
android:layout_width="match_parent"
android:layout_weight="1"
/>
<Button
android:text="Calculate GPA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnGpa"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Single Item Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv_subject"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/rl_subject"
>
<TextView
android:id="#+id/subTitle"
android:textSize="16sp"
android:text="Subject"
android:layout_toStartOf="#+id/subGrade"
android:layout_toLeftOf="#+id/subGrade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:dropDownWidth="40dp"
android:textAlignment="center"
android:entries="#array/grades"
android:id="#+id/subGrade"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
MainActivity
public class MainActivity extends AppCompatActivity {
private static SubjectArrayAdapter adapter;
private ProgressDialog progress;
JsonArray subs = new JsonArray();
JsonArray dataGrades = new JsonArray();
ListView listView;
ArrayList<SubjectClass> subjects = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = new GetSubNames().execute();
subs = res.getAsJsonArray("subjects");
for (int i = 0; i < subs.size(); i++){
JsonObject temp = subs.get(i).getAsJsonObject();
subjects.add(new SubjectClass(temp.get("subCode").getAsString(), temp.get("subTitle").getAsString()));
}
adapter = new SubjectArrayAdapter(subjects,GpaActivity.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Button btnGpa = (Button) findViewById(R.id.btnGpa);
btnGpa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CalcGPA().execute();
JsonArray temparr = new JsonArray();
for (int i = 0; i < listView.getChildCount(); i++) {
// Get row's spinner
View listItem = listView.getChildAt(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
dataGrades = temparr;
}
});
}
}
Custom Class
class SubjectClass{
String title;
String code;
SubjectClass(String code, String title) {
this.code = code;
this.title = title;
}
String getTitle(){
return this.title;
}
String getCode(){
return this.code;
}
void setCode(String code){
this.code = code;
}
void setTitle(String title){
this.title = title;
}
}
Custom ArrayAdapter
public class SubjectArrayAdapter extends ArrayAdapter<SubjectClass>{
private ArrayList<SubjectClass> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
}
public SubjectArrayAdapter(ArrayList<SubjectClass> data, Context context) {
super(context, R.layout.item_subject, data);
this.dataSet = data;
this.mContext=context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
SubjectClass dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_subject, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.subTitle);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
viewHolder.txtName.setText(dataModel.getCode() + " " + dataModel.getTitle());
// Return the completed view to render on screen
return convertView;
}
}
for (int i = 0; i < listView.getCount(); i++) {
// Get row's spinner
View listItem = listView.getItemAtPosition(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
Check for above code in main activity. Use .getCount() instead .getChildCount()
and use .getItemAtIndex() instead .getChildAt().
I hope this solves the issue.
Related
I am trying to retrieve data from parse,therefore I need to make a custom adapter for the listview but its not working,I created a custom adapter but the listview is not showing and I can't figure out what is the problem.
I am getting no errors or crashes so I can't point the exact problem.
This is what I have done:
The adapter:
public class MyListView extends BaseAdapter {
private final ArrayList<HashMap<String, String>> contentList;
private static LayoutInflater inflater = null;
public MyListView(Activity a, ArrayList<HashMap<String, String>> contentForList) {
this.contentList = contentForList;
inflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return contentList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.mylist, null);
ImageView logo = (ImageView) vi.findViewById(R.id.icon); // title
TextView titleText = (TextView) vi.findViewById(R.id.title); // artist name
TextView subtitleText = (TextView) vi.findViewById(R.id.subtitle);
HashMap<String, String> info = new HashMap<String, String>();
info = contentList.get(position);
String title = (String) info.get("businessname");
String peopleinBusiness = (String) info.get("peopleinbusiness");
// Setting all values in listview
titleText.setText(title);
subtitleText.setText(peopleinBusiness);
// Bitmap bmp = (Bitmap) info.get("photo");
// logo.setImageBitmap(bmp);
return vi;
}
}
listView XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
MainActivity:
ArrayList<HashMap<String,String>> feedData = new ArrayList<>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("User");
query.orderByDescending("createdAt");
query.setLimit(20);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null){
for (ParseObject feed : objects){
HashMap<String, String> PlacesInfo = new HashMap<>();
PlacesInfo.put("username",feed.getString("username"));
PlacesInfo.put("worthcomming",feed.getString("worthcomming"));
PlacesInfo.put("businessname",feed.getString("BusinessName"));
PlacesInfo.put("peopleinbusiness",feed.getString("PeopleInBusiness"));
feedData.add(PlacesInfo);
}
MyListView listview = new MyListView(FeedActivity.this,feedData);
feedListView.setAdapter(listview);
listview.notifyDataSetChanged();
}else{
Log.e("findinBackground","Failed");
e.printStackTrace();
}
}
});
Thank you !!
I can't believe I spend so much time only to figure out I was missing a " _ " .
I changed this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("User");
To this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
Thank everyone !
Good night android masters. Please help me. maybe those of you who understand better than me can help me solve the problem I'm facing right now.
1 https://imgur.com/S2TU08q
I made a listview on the fragment. I stopped because I was confused how I proceeded. maybe the code below can help you solve my problem!
This is the fragment I made. I name it Frag_Tour.java
public class Frag_Tour extends Fragment {
ListView listView;
ListViewAdapterTour adapter;
String[] judul1;
String[] judul2;
String[] durasi;
String[] harga;
int[] gambarTour;
ArrayList<Model> arrayList = new ArrayList<Model>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_tour, container, false);
judul1 = new String[]{"Paket Hemat", "Paket Reguler", "Paket Honeymoon"};
judul2 = new String[]{"Wisata Belitung", "Wisata Belitung", "Wisata Belitung"};
durasi = new String[]{"3 Hari 2 Malam", "4 Hari 3 Malam", "3 Hari 1 Malam"};
harga = new String[]{"Rp 750.000/pax", "Rp 750.000/pax", "Rp 750.000/pax"};
gambarTour = new int[]{
R.drawable.mercusuar_1, R.drawable.mercusuar_2, R.drawable.mercusuar_3
};
listView = rootView.findViewById(R.id.listView);
for (int i = 0; i < judul1.length; i++) {
Model model = new Model(judul1[i], judul2[i], durasi[i], harga[i], gambarTour[i]);
arrayList.add(model);
}
adapter = new ListViewAdapterTour(this, arrayList);
listView.setAdapter((ListAdapter) arrayList);
return rootView;
}
}
this is the xml file. frag_tour.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent_view"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
[2] https://imgur.com/ehPanZM
this is the ListViewAdapter that I have created. I named it ListViewAdapterTour.java
public class ListViewAdapterTour extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
List<Model> modellist;
ArrayList<Model> arrayList;
public ListViewAdapterTour (Context context, List<Model> modellist) {
mContext = context;
this.modellist = modellist;
inflater = LayoutInflater.from(mContext);
this.arrayList = new ArrayList<Model>();
this.arrayList.addAll(modellist);
}
public class ViewHolder {
TextView Judul1, Judul2, Durasi, Harga;
ImageView GambarTour;
}
#Override
public int getCount() {
return modellist.size();
}
#Override
public Object getItem(int i) {
return modellist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.row_tour, null);
holder.Judul1 = view.findViewById(R.id.judul1);
holder.Judul2 = view.findViewById(R.id.judul2);
holder.Durasi = view.findViewById(R.id.durasi);
holder.Harga = view.findViewById(R.id.harga);
holder.GambarTour = view.findViewById(R.id.GambarTour);
view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}
holder.Judul1.setText(modellist.get(position).getJudul1());
holder.Judul2.setText(modellist.get(position).getJudul2());
holder.Durasi.setText(modellist.get(position).getDurasi());
holder.Harga.setText(modellist.get(position).getHarga());
holder.GambarTour.setImageResource(modellist.get(position).getGambartour());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (modellist.get(position).getJudul1().equals("Paket Hemat 3 Hari 2 Malam")){
Intent intent = new Intent(mContext, TourDetail.class);
intent.putExtra("contentTv","PAKET HEMAT");
mContext.startActivity(intent);
}
}
});
return view;
}
}
and this is the xml file. row_tour.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:focusableInTouchMode="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="#dimen/spacing_middle"
android:layout_weight="1"
app:cardCornerRadius="2dp"
app:cardElevation="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="170dp"
android:orientation="vertical">
<ImageView
android:id="#+id/GambarTour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="#drawable/mercusuar_1"
tools:ignore="ContentDescription" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/overlay_dark_20" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#id/GambarTour"
android:layout_margin="#dimen/spacing_medium"
android:orientation="vertical"
tools:ignore="UselessParent">
<TextView
android:id="#+id/judul1"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Paket Hemat"
android:textColor="#color/White"
android:textStyle="bold" />
<TextView
android:id="#+id/judul2"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wisata Belitung"
android:textColor="#color/White"
android:textStyle="bold" />
<TextView
android:id="#+id/durasi"
style="#style/TextAppearance.AppCompat.Caption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/_3_hari_2_malam"
android:textColor="#color/White" />
</LinearLayout>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignEnd="#id/GambarTour"
android:layout_alignRight="#id/GambarTour"
android:layout_margin="#dimen/spacing_medium"
android:src="#drawable/ic_favorite_border"
android:tint="#color/White" />
<TextView
android:id="#+id/harga"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/GambarTour"
android:layout_alignRight="#id/GambarTour"
android:layout_alignBottom="#id/GambarTour"
android:layout_margin="#dimen/spacing_large"
android:background="#drawable/gradient_green"
android:padding="#dimen/spacing_xmedium"
android:text="Rp 750.000/pax"
android:textColor="#color/White" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
[3] https://imgur.com/h7WiBgK
and this is the code for the model.java that I use
package com.androidrion.sejengkalapp;
class Model {
private String judul1;
private String judul2;
private String durasi;
private String harga;
private int gambartour;
//constructor
Model(String judul1, String judul2, String durasi, String harga, int gambartour) {
this.judul1 = judul1;
this.judul2 = judul2;
this.durasi = durasi;
this.harga = harga;
this.gambartour = gambartour;
}
//getters
String getJudul1() {
return this.judul1;
}
String getJudul2() {
return this.judul2;
}
String getDurasi() {
return this.durasi;
}
String getHarga() {
return this.harga;
}
int getGambartour() {
return this.gambartour;
}
}
I hope the teachers and masters about Android can help me in solving this problem. what I want is row_tour.xml which I have designed to be listview in frag_tour.xml
[4] https://imgur.com/VLzOUiK
The context should be the activity holding the fragment. So instead of this in your adapter constructor, use getActivity()
adapter = new ListViewAdapterTour(getActivity(), arrayList);
I'm trying to implement my own ListView design with a custom adapter. But whenever I run my program, I get this error "ArrayAdapter: You must supply a resource ID for a TextView".
Here is my Custom Adapter
public class LayoutAdapter extends ArrayAdapter {
List list = new ArrayList();
public LayoutAdapter (Context context, int resource) {
super(context,resource);
}
static class DataHandler {
TextView accountName;
TextView availableBalance;
TextView totalBalance;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_layout,parent,false);
handler = new DataHandler();
handler.accountName = (TextView) row.findViewById(R.id.account_name);
handler.availableBalance = (TextView) row.findViewById(R.id.available_balance);
handler.totalBalance = (TextView) row.findViewById(R.id.total_balance);
row.setTag(handler);
}
else {
handler = (DataHandler)row.getTag();
}
Account account;
account = (Account)this.getItem(position);
handler.accountName.setText(account.returnName());
handler.availableBalance.setText("Available Balance: $"+account.returnAvailableBalance());
handler.totalBalance.setText("Total Balance: $"+account.returnTotalBalance());
return row;
}
}
Here is my custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:padding="8dp">
<TextView
android:text="#string/str_account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/account_name"
android:height="80dp"
android:textSize="24sp"
android:gravity="center_vertical" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/account_name">
<TextView
android:text="#string/str_available_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/available_balance"
android:textSize="16sp"
android:layout_gravity="right"
android:paddingTop="30dp" />
<TextView
android:text="#string/str_total_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/total_balance"
android:textSize="16sp"
android:layout_gravity="right" />
</LinearLayout>
</RelativeLayout >
Here is my main activity
LayoutAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new LayoutAdapter(getApplicationContext(),R.layout.custom_layout);
ArrayList<Account> accounts = new ArrayList<>();
accounts.add(new Account ("Checking",5.00));
accounts.add(new Account ("Cash",50.00));
Account acc1 = new Account("Checking",5.00);
Account acc2 = new Account("Cash",50.00);
adapter.add(acc1);
adapter.add(acc2);
listView.setAdapter(adapter);
I am trying to make an activity that provides a list of emergency phone numbers with the ability for the user to add their own custom entries and save them. For some reason, the ListView doesn't appear on the activity. I'm pretty sure I'm doing something wrong in the CustomAdapter class that I made to hold two text boxes in each segment of the ListView.
I'm also trying to set the listView to start a phone activity with the phone number of whatever segment was touched, and I'm unsure if I'm doing this correctly.
PhoneList.java :
public class PhoneList extends AppCompatActivity {
ArrayList<String> customList;
ArrayList<String> numList;
Bundle b;
TinyDB tinydb;
CustomAdapter dataAdapter;
ListView phoneListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);
phoneListView = (ListView)findViewById(R.id.listViewPhone);
Integer num = null;
String label = "";
customList = null;
numList = null;
tinydb = new TinyDB(this);
Button saveContact = (Button)(findViewById(R.id.button4));
b = new Bundle();
customList = tinydb.getListString("label");
ArrayList<Integer> temp = tinydb.getListInt("num");
for(int i = 0; i < temp.size(); i++){
numList.add(temp.get(i).toString());
}
saveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText enteredLabel = (EditText)findViewById(R.id.editText2);
EditText enteredNum = (EditText)findViewById(R.id.editText);
String label = enteredLabel.getText().toString();
Integer num = Integer.parseInt(enteredNum.getText().toString());
b.putString("label",label);
b.putInt("num",num);
addPhoneItem();
}
});
ArrayList<String> phoneList = new ArrayList<>();
phoneList.add("Emergencies");
phoneList.add("Travel Info ");
phoneList.add("Poison Control ");
phoneList.add("AAA: 1(800)836-2582");
if(customList != null && customList.size() > 0) phoneList.addAll(customList);
ArrayList<String> numberList = new ArrayList<>();
numberList.add("911");
numberList.add("511");
numberList.add("18002221222");
numberList.add("18008362582");
if(numList != null && numList.size()>0) {
for (int i = 0; i < numList.size(); i++) {
numberList.add(numList.get(i).toString());
}
}
dataAdapter = new CustomAdapter(this,numberList,phoneList);
phoneListView.setAdapter(dataAdapter);
}
public void addPhoneItem(){
customList.add(b.getString("label"));
numList.add(b.getString("num"));
tinydb.putListString("label",customList);
tinydb.putListString("num",numList);
dataAdapter = new CustomAdapter(this,numList,customList);
phoneListView.setAdapter(dataAdapter);
}
private class CustomAdapter extends ArrayAdapter<String> {
ArrayList<String> labels;
ArrayList<String> nums;
Context context;
public CustomAdapter(Context context, ArrayList<String> n,ArrayList<String> l) {
super(context,R.layout.phone_item);
this.context = context;
labels = new ArrayList<String>();
labels.addAll(l);
nums = new ArrayList<String>();
nums.addAll(n);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.phone_item, null);
holder = new ViewHolder();
holder.viewLabel = (TextView) convertView.findViewById(R.id.editText);
holder.viewNumber = (TextView) convertView.findViewById(R.id.editText2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String label = labels.get(position);
String num = nums.get(position);
holder.viewLabel.setText(label);
holder.viewNumber.setText(num);
holder.viewNumber.setTag(num);
holder.viewNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "tel:" + (EditText) v.getTag();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(str));
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getContext(),"Exception Caught in CustomAdapter",Toast.LENGTH_SHORT).show();
}
}
});
}
catch(Exception e){
Toast.makeText(getContext(),"Exception caught",Toast.LENGTH_SHORT).show();
}
return convertView;
}
}
private class ViewHolder{
TextView viewLabel;
TextView viewNumber;
}
}
activity_phone_list.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rvtripapp.dempsey.rvtripapp.PhoneList">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="#+id/listViewPhone"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:editable="true"
android:hint="Label" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Phone Number" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/button4"
android:textSize="40dp"
android:background="#44fe66"
android:layout_alignBottom="#+id/editText2"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView" />
</RelativeLayout>
phone_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3" />
</LinearLayout>
Any help is much appreciated, thank you.
Change the super keyword line to
super(context,R.layout.phone_item, n);
Have you tried to override the getCount method of the CustomAdapter class ?
#Override
public int getCount() {
return labels.size();
}
You are setting your custom adapter outside onCreate() try to set it inside the onCreate().
I'm new to programming for Android (and Java) and have managed to get a custom adapter working, but am stuck on how to update textViews inside of it. Below you will see my score_save function with the code I want, but I'm not sure how to apply this to all rows of my adapter at once.
public class MainActivity extends Activity {
private ListView listView1;
private int currentPlayer;
private int currentScore;
ArrayList<Integer> allScoreChange = new ArrayList<Integer>();
ArrayList<Integer> allScore = new ArrayList<Integer>();
Button button_add, button_add_big, button_sub, button_sub_big,
button_add_num, button_save;
TextView name;
TextView score;
TextView scoreChange;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Score score_data[] = new Score[] { new Score("NameA"),
new Score("NameB"), new Score("NameC"), new Score("NameD"),
new Score("NameE") };
//sets score lists to 0
for (int i = 0; i < 5; i++) {
allScoreChange.add(0);
allScore.add(0);
}
ScoreAdapter adapter = new ScoreAdapter(this,
R.layout.listview_item_row, score_data);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentScore = allScoreChange.get(position);
// Gets fields from current row
score = (TextView) view.findViewById(R.id.txtScore);
scoreChange = (TextView) view.findViewById(R.id.txtScoreChange);
currentPlayer = position;
}
});
button_save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
score_save();
}
});
}
public void score_save() {
// this needs to go through all rows of listview
currentPlayer = 0;
// update array with new score
allScore.set(currentPlayer, allScore.get(currentPlayer)
+ allScoreChange.get(currentPlayer));
// display new score
score.setText(allScore.get(currentPlayer));
// reset score change to zero
allScoreChange.set(currentPlayer, 0);
// display score change as blank
scoreChange.setText("");
}
}
Here's the XML for the row, I want to update txtScoreChange and txtScore with the values out of the allScoreChange and allScore ArrayLists. I cut out the code that defines these lists, in case you're wondering.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp" >
<TextView
android:id="#+id/txtTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="70"
android:text="Name"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtScoreChange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="15"
android:textColor="#ff0000"
android:textSize="22sp"
android:gravity="right" />
<TextView
android:id="#+id/txtScore"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="15"
android:text="1"
android:textColor="#666666"
android:textSize="22sp"
android:gravity="right" />
Here's my adapter:
public class ScoreAdapter extends ArrayAdapter<Score>{
Context context;
int layoutResourceId;
Score data[] = null;
public ScoreAdapter(Context context, int layoutResourceId, Score[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ScoreHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ScoreHolder();
holder.txtScore = (TextView)row.findViewById(R.id.txtScore);
holder.txtScoreChange = (TextView)row.findViewById(R.id.txtScoreChange);
holder.txtName = (TextView)row.findViewById(R.id.txtName);
row.setTag(holder);
}
else
{
holder = (ScoreHolder)row.getTag();
}
Score scoreData = data[position];
holder.txtName.setText(scoreData.name);
holder.txtScore.setText(scoreData.score);
return row;
}
static class ScoreHolder
{
TextView txtScore;
TextView txtName;
TextView txtScoreChange;
}
}
Call adapter.notifyDataSetChanged(). That will cause it to repopulate the listview, calling adapter.getView on all visible views. Have getView() set the correct values for its row.