Android ListView and ArrayAdapter implementation - java

So, I'm trying to create a screen that when clicking a button this takes the data from some EditText and add them to a ListView item, now I know there are a lot of examples on the web and I've done them and they work, but when I took them to what I want to do it just adds one item and stops working it doesn't throw any exception or anything, it just add one item, this is what I got so far...
create_class.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
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.eduardolaguna.mariela.app.activities.CreateClass">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/cc_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/cc_hint_class_name" />
<View
android:id="#+id/cc_divider1"
style="#style/Divider"
android:layout_below="#+id/cc_name" />
<TextView
android:id="#+id/tv_cc_professors_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/cc_divider1"
android:text="#string/cc_tv_professors_data" />
<EditText
android:id="#+id/cc_professors_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_cc_professors_data"
android:hint="#string/cc__hint_professors_name"
android:inputType="textPersonName|textAutoComplete|textAutoCorrect" />
<EditText
android:id="#+id/cc_professors_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_professors_name"
android:hint="#string/cc_hint_professors_email"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/cc_professors_phonenumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_professors_email"
android:hint="#string/cc_hint_professors_phonenumber"
android:inputType="phone" />
<View
android:id="#+id/cc_divider2"
style="#style/Divider"
android:layout_below="#id/cc_professors_phonenumber" />
<TextView
android:id="#+id/tv_cc_schedule"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_divider2"
android:text="#string/cc_tv_class_schedule" />
<Spinner
android:id="#+id/sp_cc_day_of_the_week"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_cc_schedule"
android:entries="#array/dow" />
<EditText
android:id="#+id/cc_from_schedule"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/sp_cc_day_of_the_week"
android:hint="#string/cc_hint_from_schedule"
android:inputType="time" />
<EditText
android:id="#+id/cc_to_schedule"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_below="#id/sp_cc_day_of_the_week"
android:layout_toRightOf="#id/cc_from_schedule"
android:hint="#string/cc_hint_to_schedule"
android:inputType="time" />
<EditText
android:id="#+id/cc_floor_number"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_below="#id/sp_cc_day_of_the_week"
android:layout_toRightOf="#id/cc_to_schedule"
android:hint="#string/cc_hint_floor"
android:inputType="number" />
<EditText
android:id="#+id/cc_classroom"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_below="#id/sp_cc_day_of_the_week"
android:layout_toRightOf="#id/cc_floor_number"
android:hint="#string/cc_hint_classroom" />
<Button
android:id="#+id/btn_cc_add_schedule"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_from_schedule"
android:text="#string/cc_add_schedule" />
<ListView
android:id="#+id/cc_schedule_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btn_cc_add_schedule" />
</RelativeLayout>
</ScrollView>
</LinearLayout>
schedule_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/sch_day_of_the_week"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="MiƩrcoles"
android:textSize="60dp" />
<TextView
android:id="#+id/sch_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="5:45"
android:textSize="20dp" />
<TextView
android:id="#+id/sch_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="7:15"
android:textSize="20dp" />
<TextView
android:id="#+id/sch_floor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="7"
android:textSize="20dp" />
<TextView
android:id="#+id/sch_clasroom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="lab1"
android:textSize="20dp" />
</LinearLayout>
ScheduleAdapter.java
public class ScheduleAdapter extends ArrayAdapter<Actividad> {
private int layoutResourceId;
private LayoutInflater inflater;
private List<Actividad> shifts;
public ScheduleAdapter(Context context, int resource, List<Actividad> objects) {
super(context, resource, objects);
layoutResourceId = resource;
shifts = objects;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
Holder holder = null;
row = inflater.inflate(layoutResourceId, null);
holder = new Holder();
holder.actividad = shifts.get(position);
holder.dow = (TextView) row.findViewById(R.id.sch_day_of_the_week);
holder.fromTXT = (TextView) row.findViewById(R.id.sch_from);
holder.toTXT = (TextView) row.findViewById(R.id.sch_to);
holder.floorTXT = (TextView) row.findViewById(R.id.sch_floor);
holder.roomTXT = (TextView) row.findViewById(R.id.sch_clasroom);
setupItem(holder);
row.setTag(holder);
return row;
}
private void setupItem(Holder holder) {
holder.dow.setText(holder.actividad.getDiaDeLaSemana());
holder.fromTXT.setText(holder.actividad.getDesdeStr());
holder.toTXT.setText(holder.actividad.getHastaStr());
holder.floorTXT.setText(holder.actividad.getPiso());
holder.roomTXT.setText(holder.actividad.getSalon());
}
public static class Holder {
Actividad actividad;
TextView dow;
TextView fromTXT;
TextView toTXT;
TextView floorTXT;
TextView roomTXT;
}
}
And finally the CreateClass.java
public class CreateClass extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_class);
ListView view = (ListView) findViewById(R.id.cc_schedule_list);
final ScheduleAdapter adapter = new ScheduleAdapter(getApplicationContext(), R.layout.schedule_item, new ArrayList<Actividad>());
view.setAdapter(adapter);
Button addSchedule = (Button) findViewById(R.id.btn_cc_add_schedule);
addSchedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Resources res = getResources();
ListView scheduleView = (ListView) findViewById(R.id.cc_schedule_list);
ScheduleAdapter adapter1 = (ScheduleAdapter) scheduleView.getAdapter();
Actividad act = new Actividad(TipoEvento.CLASE);
Spinner dow = (Spinner) findViewById(R.id.sp_cc_day_of_the_week);
act.setDiaDeLaSemana(dow.getSelectedItem().toString());
TextView from = (TextView) findViewById(R.id.cc_from_schedule);
act.setDesdeStr(res.getString(R.string.from) + ": " + from.getText().toString());
TextView to = (TextView) findViewById(R.id.cc_to_schedule);
act.setHastaStr(res.getString(R.string.to) + ": " + to.getText().toString());
TextView floor = (TextView) findViewById(R.id.cc_floor_number);
act.setPiso(res.getString(R.string.floor) + ": " + floor.getText().toString());
TextView classroom = (TextView) findViewById(R.id.cc_classroom);
act.setSalon(res.getString(R.string.classroom) + ": " + classroom.getText().toString());
adapter1.add(act);
}
});
}
}

You should instantiate your adapter with the Activity context, not the application context.
Storing a copy of the constructed list in shifts can be dangerous.
Don't store shifts in the Holder. Only views go in there.
When populating the convertView, reference the internal getItem(position) method to obtain the Actividad data...not your shifts variable.
You're also using the ViewHolder paradigm incorrectly. Example here.

Turns out the problem is the ListView is inside the ScrollView, this does not work properly when the list grows dynamically, I move it out the ScrollView and it works like a charm.
This was according to #Romain Guy a developer in the Android project, where he stated that
Using a ListView to make it not scroll is extremely expensive and goes against the whole purpose of ListView. You should NOT do this. Just use a LinearLayout instead.
So I use a LinearLayout to draw the new items on the layout.

Related

Textview cannot set text but Imageview working

I have some problem with my code. I cannot set Textview but ImageView is working. This is my xml textview. I using adapter and listener interface.
error : textview on a null object reference
<?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:descendantFocusability="blocksDescendants"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto">
<View
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_middle" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/spacing_middle"
android:layout_marginRight="#dimen/spacing_middle"
android:visibility="visible"
app:cardCornerRadius="0dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/spacing_medium"
android:layout_marginLeft="#dimen/spacing_large"
android:layout_marginRight="#dimen/spacing_large"
android:layout_marginTop="#dimen/spacing_large"
android:gravity="center_vertical"
android:orientation="horizontal">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgGambar"
android:layout_width="#dimen/spacing_xxlarge"
android:layout_height="#dimen/spacing_xxlarge"
android:foreground="#color/overlay_light_20"
app:civ_shadow="true"
app:civ_shadow_radius="0"
android:src="#drawable/photo_female_2"
app:civ_border="false" />
<View
android:layout_width="#dimen/spacing_large"
android:layout_height="0dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Emma Richmond"
android:textAppearance="#style/TextAppearance.AppCompat.Subhead"
android:textColor="#color/grey_90" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/spacing_small"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="in "
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_40" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Hwy, Carthage"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/light_blue_400"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/tvKonten"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/spacing_large"
android:lineSpacingExtra="4dp"
android:text="#string/middle_lorem_ipsum"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_60" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="#dimen/spacing_medium"
android:background="#color/grey_5" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_xxlarge"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_large">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgLike"
android:layout_width="#dimen/spacing_mlarge"
android:layout_height="#dimen/spacing_mlarge"
android:layout_marginEnd="#dimen/spacing_middle"
android:layout_marginRight="#dimen/spacing_middle"
android:tint="#color/light_green_300"
android:src="#drawable/ic_thumb_up" />
<TextView
android:id="#+id/txtsuka"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="12 likes"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_40" />
</LinearLayout>
<View
android:layout_width="#dimen/spacing_large"
android:layout_height="0dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="#dimen/spacing_mlarge"
android:layout_height="#dimen/spacing_mlarge"
android:layout_marginEnd="#dimen/spacing_middle"
android:layout_marginRight="#dimen/spacing_middle"
android:tint="#color/light_blue_400"
android:src="#drawable/ic_textsms" />
<TextView
android:id="#+id/tvKomentar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="4 Comments"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_40" />
</LinearLayout>
<TextView
android:id="#+id/tvLalu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="end|right"
android:text="2h ago"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#color/grey_40" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
and this is my adapter : https://pastebin.com/csiW52h4
public class AdapterCardPostList extends RecyclerView.Adapter<AdapterCardPostList.ViewHolder> {
private Context context;
private List<PostItem> list;
private List<Check> checkList;
private OnItemClickListener mOnItemClickListener;
public AdapterCardPostList(Context context, List<PostItem> list, List<Check> checkList, OnItemClickListener monItemClickListener) {
this.context = context;
this.list = list;
this.checkList = checkList;
this.mOnItemClickListener = monItemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public ImageView image, imglike;
public TextView name;
public TextView konten;
public TextView like;
public TextView komentar;
public TextView lalu;
public ViewHolder(View v) {
super(v);
image = (ImageView) v.findViewById(R.id.imgGambar);
name = (TextView) v.findViewById(R.id.tvName);
konten = (TextView) v.findViewById(R.id.tvKonten);
like = (TextView) v.findViewById(R.id.txtsuka);
komentar = (TextView) v.findViewById(R.id.tvKomentar);
lalu = (TextView) v.findViewById(R.id.tvLalu);
imglike = (ImageView) v.findViewById(R.id.imgLike);
imglike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mOnItemClickListener.onItemClick(view, checkList.get(getAdapterPosition()), getAdapterPosition(), list.get(getAdapterPosition()));
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v = layoutInflater.inflate(R.layout.item_post, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
PostItem p = list.get(position);
holder.konten.setText(p.getContent());
holder.like.setText(p.getLike());
holder.name.setText(p.getName());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
// long time = sdf.parse(p.getTanggal()).getTime();
Date date = sdf.parse(p.getTanggal());
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(date.getTime(), now, DateUtils.MINUTE_IN_MILLIS);
holder.lalu.setText(ago);
} catch (ParseException e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
holder.komentar.setText(p.getKomen() + " Comments");
Glide.with(context).load("https://graph.facebook.com/" + p.getUid() + "/picture?type=normal").into(holder.image);
if (p.getUid().equals(MainActivity.id)){
holder.imglike.setColorFilter(ContextCompat.getColor(context, R.color.red_200), android.graphics.PorterDuff.Mode.MULTIPLY);
checkList.add(new Check(true));
}else{
holder.imglike.setColorFilter(ContextCompat.getColor(context, R.color.light_green_300), android.graphics.PorterDuff.Mode.MULTIPLY);
checkList.add(new Check(false));
}
}
#Override
public int getItemCount() {
return list.size();
}
}
my error like this
why my imageview working but textview not working
thank you for attention
mOnItemClickListener.onItemClick(view, checkList.get(getAdapterPosition()), getAdapterPosition(), list.get(getAdapterPosition()));
change to
mOnItemClickListener.onItemClick(v, checkList.get(getAdapterPosition()), getAdapterPosition(), list.get(getAdapterPosition()));
This is because the id tvKonten does not exist. In your XML code, the id of the TextView is txtsuka, not tvKonten. Change tvKonten to txtsuka.
Try these options, it might work for you :
Invalidate Caches and Restart
Check if you have a different version of the same layout file in your res folder such as ...v26.xml or something like that ; if you find any then delete the unwanted version of the file.

my app in android studio is crashing when i come to the part recyclerView.setAdapter(adapter);

I am trying to fetch some data in android studio from my online database backendless.com but the proplem is not with the online serves it is when i try to inflate the data. i dont know is it in the layaot file or in the java class
this is my java activitiy ViewMyBusiness.java
public class ViewMyBusiness extends AppCompatActivity {
ListView recyclerView;
private View mProgressView;
private View mLoginFormView;
private TextView tvLoad;
ContactsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_my_business);
recyclerView = findViewById(R.id.recycler_view);
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
tvLoad = findViewById(R.id.tvLoad);
String whereClause = "userEmail = '" + BackendlessCall.user.getEmail() + "'";
DataQueryBuilder queryBuilder = DataQueryBuilder.create();
queryBuilder.setWhereClause(whereClause);
queryBuilder.setGroupBy("companyName");
showProgress(true);
Backendless.Persistence.of(Contact.class).find(queryBuilder, new AsyncCallback<List<Contact>>() {
#Override
public void handleResponse(List<Contact> response) {
adapter = new ContactsAdapter(ViewMyBusiness.this, response);
//the crash is here
recyclerView.setAdapter(adapter);
showProgress(false);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(ViewMyBusiness.this, "ERROR: " + fault.getMessage(), Toast.LENGTH_SHORT).show();
showProgress(false);
}
});
}
this is the contacts adapter java class
public class ContactsAdapter extends ArrayAdapter<Contact> {
private Context context;
private List<Contact> contacts;
public ContactsAdapter(Context context, List<Contact> list)
{
super(context, R.layout.row_layout, list);
this.context = context;
this.contacts = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_layout, parent, false);
TextView tvChar = convertView.findViewById(R.id.tvChar);
TextView tvCName = convertView.findViewById(R.id.tvCName);
TextView tvBField = convertView.findViewById(R.id.tvBField);
tvChar.setText(contacts.get(position).getCompanyName().toUpperCase().charAt(0) + "");
tvCName.setText(contacts.get(position).getCompanyName());
tvBField.setText(contacts.get(position).getBusinessField());
return convertView;
}
}
the layout for the listview in activity_view_my_business.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ViewMyBusiness">
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="200dp"
android:visibility="gone" />
<TextView
android:id="#+id/tvLoad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:clickable="true"
android:focusable="true"
android:gravity="center_horizontal"
android:text="Loading...please wait..."
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/login_form"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:text="Business"
android:textSize="24sp"
android:textStyle="bold" />
<ListView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/row_layout"/>
</LinearLayout>
</LinearLayout>
this is the view file that will inflate when data is passed
the row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/List"
android:orientation="horizontal">
<TextView
android:id="#+id/tvChar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="A"
android:textColor="#color/ListText"
android:textSize="48sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="8"
android:orientation="vertical">
<TextView
android:id="#+id/tvCName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:text="TextView"
android:textColor="#color/ListText"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvBField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:text="TextView"
android:textColor="#color/ListText" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
You are getting NullPointerException in that line, becasue in this line -
recyclerView = findViewById(R.id.recycler_view);
you are assigning null value to recyclerView variable !
It's because in the activity layout file you have defined a list view not RecyclerView, change this part
<ListView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/row_layout"/>
to this part of xml code -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/row_layout"/>
and to use recyclerView you have to add these -->
implementation 'com.android.support:recyclerview-v7:28.0.0' ,
dependency to your build.gradle (app:module) file
and here is official documentation about RecyclerView - Andorid RecyclerView
Enjoy!!

Android CustomListAdapter Setting TextView from EditText OnClick in TAB

On one of my tabs I have a Listview that I want to populate when a user enters text on the edittext and then presses a button. The edittext and the button are on the tabbed layout along with the listview.
The textview and imageview are set in the customlistadapter. But when I press the button nothing happens and I can't seem to work out why.
Tab3.java
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.tab3, container, false);
final EditText notes = (EditText) v.findViewById(R.id.editText);
listView=(ListView)v.findViewById(R.id.list);
Button button = (Button) v.findViewById(R.id.button3);
String note = notes.getText().toString();
int[] cross = new int[]{R.drawable.cross};
String [] notesofrules = new String[]{note};
final CustomListAdapter adapter=new CustomListAdapter(this.getActivity(), notesofrules, cross);
listView=(ListView) v.findViewById(R.id.list);
Button rulesSet = (Button)v.findViewById(R.id.button3);
rulesSet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
listView.setAdapter(adapter);
}
});
return v;
}
CustomListAdaper:
public CustomListAdapter(Activity context, String[] notes, int[] imageCross) {
super(context, R.layout.item);
// TODO Auto-generated constructor stub
this.context=context;
this.notes = notes;
this.imageCross = imageCross;
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.item, null,false);
TextView ruleNotesSet = (TextView) rowView.findViewById(R.id.textView1);
ImageView image = (ImageView) rowView.findViewById(R.id.icon);
image.setImageResource(imageCross[position]);
ruleNotesSet.setText(notes[position]);
return rowView;
}
tab3.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
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"
>
<TextView android:text="#string/thirdTabTitle" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF9900"
android:id="#+id/textView"
android:textIsSelectable="true"
android:textSize="55px"
android:shadowColor="#73ffffff"
android:fontFamily="sans-serif-bold" />
<EditText
android:layout_width="wrap_content"
android:layout_height="100px"
android:ems="10"
android:padding="10dp"
android:id="#+id/editText"
android:background="#drawable/edittext_rounded_corners"
android:layout_marginTop="18dp"
android:layout_below="#+id/textView"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/addnote"
android:background="#drawable/calculate_button"
android:textColor="#000000"
android:fontFamily="sans-serif-bold"
android:layout_below="#+id/editText"
android:textSize="40px"/>
<TextView
android:id="#+id/notes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textSize="45px"
android:layout_below="#+id/button3"
android:fontFamily="sans-serif-bold"
android:layout_toRightOf="#id/autohighlight_checkbox"
/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/notes" />
</RelativeLayout>
item.xml
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#4CBE99"
android:textSize="14dp"
android:text="Item"
android:textAllCaps="true"
android:textStyle="bold" />
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
</LinearLayout>
</LinearLayout>
I think your adapter is empty. You only need to set it once, then make a refresh function in your adapter you'll call in your activity's onClick
public void refresh(String[] notes, int[] imageCross) {
this.notes = notes;
this.imageCross = imageCross;
this.notifySataSetChanged();
}

Get textview of custom adapter android

I have a custom view adapter with four buttons and a title that populate a ListView.
When a user clicks one of those buttons, I want to retrieve the title associated with that specific adapter.
So far I have tried retrieving the parent and getting the textView but that does not return the correct title.
So...how would I get the specific title affiliated to the adapter that has the button the user clicked on?
I'd be happy to clarify if you need more information.
Here is the layout of the adapter.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/fragment_student_home_classTitle_textView"
android:paddingTop="20dp"
android:layout_toLeftOf="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/linearLayout">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_grades"
android:background="#ffff130c" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fragment_student_home_grades_imageButton"
android:src="#drawable/ic_grades_512"
android:background="#00000000" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_notification_textEdit"
android:background="#ffff130c" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fragment_student_home_notification_imageButton"
android:src="#drawable/ic_bell_512"
android:background="#00000000" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_homework"
android:background="#ffff130c" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fragment_student_home_homework_imageButton"
android:src="#drawable/ic_foundation_book_bookmark_simple_black_512x512"
android:contentDescription="#string/homework_notification_icon"
android:background="#00000000" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_attendance"
android:background="#ffff130c" />
<ImageButton
android:layout_width="42dp"
android:layout_height="40dp"
android:id="#+id/fragment_student_home_attendance_imageButton"
android:src="#drawable/ic_attendance"
android:contentDescription="#string/homework_notification_icon"
android:background="#00000000" />
</LinearLayout>
</LinearLayout>
And here is the adapter where I implemented the onClick
public class ClassAdapter extends ArrayAdapter<SchoolClass> implements View.OnClickListener{
private SchoolClass aClass;
public ClassAdapter(Context context, int resource, ArrayList<SchoolClass> objects) {
super(context, resource, objects);
}
public SchoolClass getSchoolClass(){
return this.aClass;
}
public void setSchoolClass(SchoolClass schoolClass){
this.aClass = schoolClass;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.classes_adapter, null);
}
aClass = getItem(position);
if(aClass != null){
TextView title = (TextView) v.findViewById(R.id.fragment_student_home_classTitle_textView);
if(title != null){
title.setText(aClass.getTitle());
}
setSchoolClass(aClass);
}
//set buttons
ImageButton notificationsButton = (ImageButton) v.findViewById(R.id.fragment_student_home_notification_imageButton);
ImageButton gradesButton = (ImageButton) v.findViewById(R.id.fragment_student_home_grades_imageButton);
ImageButton attendanceButton = (ImageButton) v.findViewById(R.id.fragment_student_home_attendance_imageButton);
ImageButton homeworkButton = (ImageButton) v.findViewById(R.id.fragment_student_home_homework_imageButton);
notificationsButton.setOnClickListener(this);
gradesButton.setOnClickListener(this);
attendanceButton.setOnClickListener(this);
homeworkButton.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ClassActivity.class);
View parent = (View) v.getRootView();
//v.getParent() returns null when I look for the textView
TextView title = (TextView) parent.findViewById(R.id.fragment_student_home_classTitle_textView);
System.out.println("\n\n title: " + title.getText().toString() + " \n\n");
intent.putExtra("__CLASS_NAME__", title.getText().toString());
It populates a list view and if I were to click on fragment_student_home_attendance_imageButton I would want to get the fragment_student_home_classTitle_textView associated with that ClassAdapter.
Just give a idea to you, hope this can help to fix the problem :)
#Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
// ....
ImageButton notificationsButton = (ImageButton) v.findViewById(R.id.fragment_student_home_notification_imageButton);
notificationsButton.setTag(R.id.fragment_student_home_notification_imageButton);
// ....
return v;
}
#Override
public void onClick(View v) {
if(v!=null && v.getTag()!=null && v.getTag()==R.id.fragment_student_home_notification_imageButton){
// do something you like
}
}
Ok nevermind, I got it.
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ClassActivity.class);
//It's the parent of the parent OF THE parent where
//the textView lies in my layout.
View parent = (View) v.getParent().getParent().getParent();
TextView title = (TextView) parent.findViewById(R.id.fragment_student_home_classTitle_textView);
System.out.println("\n\n title: " + title.getText().toString() + " \n\n");
intent.putExtra("__CLASS_NAME__", title.getText().toString());
If there is a better way to get this solution, as it seems like a head on approach to the problem, I welcome any comments!

How to set parent background on ArrayAdapter

I am building an app and have some difficulties on setting backround on a array adapter, hope someone can help!
public class ListAdapter extends ArrayAdapter {
// List context
private final Context context;
// List values
private final List<RssItem> items;
public ListAdapter(Context context, List<RssItem> items) {
// Set the layout for each item
super(context, R.layout.item, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Build each element of the list
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item, parent, false);
// Populate each layout element with the data from the items list
TextView itemPos = (TextView) rowView.findViewById(R.id.position_aa);
itemPos.setText(items.get(position).getPosition());
// Populate each layout element with the data from the items list
TextView itemTitle = (TextView) rowView.findViewById(R.id.textViewTitle);
itemTitle.setText(items.get(position).getTitle());
TextView itemPublishDate = (TextView) rowView.findViewById(R.id.textViewPublishDate);
itemPublishDate.setText(items.get(position).getPublishDate());
// Set the icon base on the post's category
ImageView icon = (ImageView) rowView.findViewById(R.id.imageViewCategoryIcon);
icon.setImageResource(CategoryMapper.getIconIdForCategory(items.get(position).getCategory()));
return rowView;
}
}
And this is the item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/bg">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#0FFF3300"
android:id="#+id/item">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageViewCategoryIcon"
android:layout_width="100dp"
android:layout_height="100dp"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="1dp">
<TextView
android:id="#+id/textViewTitle"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="[TITLE-GOES-HERE]"
android:textColor="#000"
android:textStyle="bold"/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textViewPublishDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="#555"
android:text="[PUB-DATE-GOES-HERE]"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/position_aa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="#555"
android:text="[AA-GOES-HERE]"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
</TableLayout>
</TableRow>
</TableLayout>
</LinearLayout>
</LinearLayout>
Here I deploy some rss data into RowViews Via the list adapter class, but how can I set a parent layout so I can give a fixed upon scroll background?
Thanks in advance
P.S I`m stuck for a day at this......
Set background color to your ListItem like
rowView.setBackgroundResource(R.color.yourcolor);

Categories

Resources