Getting Null pointer Exception in CustomListViewAdapter in Android - java

I am inserting my List in a ListView, Which has some constant image and dynamic images with text.
So I wrote my CustomListViewAdapter, but when I am calling this I am getting NULL pointer exception at
holder.desc.setText(EventItems.getDesc());
in CustomListViewAdapterForEvent.
Here is my complete code.
Events.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/drop_shadow"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_below="#+id/imageView2"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="343dp"
android:cacheColorHint="#515151"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:fadeScrollbars="false"
android:fastScrollEnabled="true"
android:scrollX="0px"
android:scrollY="8px"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarSize="20dip"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:scaleType="fitXY"
android:src="#drawable/cat_header" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView2"
android:layout_alignLeft="#+id/imageView2"
android:layout_alignRight="#+id/imageView2"
android:layout_alignTop="#+id/imageView2" >
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/menu_icon1" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/add_friend" />
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/message_icon" />
<ImageView
android:id="#+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/dollar_3d" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/friend_icons" />
</LinearLayout>
</RelativeLayout>
EventList.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="fill_parent"
android:background="#android:color/transparent" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/eventImage"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:contentDescription="#drawable/ic_launcher3"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/sweetIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:contentDescription="#drawable/ic_launcher3"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:scaleType="fitXY"
android:src="#drawable/aweet_icon" />
<TextView
android:id="#+id/sweetNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="sweetNo" />
<ImageView
android:id="#+id/facebookIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageView
android:id="#+id/googleIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageView
android:id="#+id/tweeterIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageView
android:id="#+id/pIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
</LinearLayout>
<TextView
android:id="#+id/eventDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="38dp"
android:text="Event Description" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/iAmThereIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_weight="0.25"
android:scaleType="fitXY"
android:src="#drawable/i_m_there_icon" />
<ImageView
android:id="#+id/maybeIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:scaleType="fitXY"
android:src="#drawable/may_be_icon" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
CustomListViewAdapterForEvent.java
public class CustomListViewAdapterForEvent extends ArrayAdapter<EventItems> {
Context context;
public CustomListViewAdapterForEvent(Context context, int resourceId,
List<EventItems> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView eventImage;
TextView sweetNo;
TextView desc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.e("TAG ", "1111111111111111");
EventItems EventItems = getItem(position);
Log.e("TAG ", "2222222222222222222");
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
Log.e("TAG ", "3333333333333333333");
if (convertView == null) {
Log.e("TAG ", "444444444444444444444");
convertView = mInflater.inflate(R.layout.event_list, null);
holder = new ViewHolder();
holder.desc = (TextView) convertView.findViewById(R.id.desc);
holder.sweetNo = (TextView) convertView.findViewById(R.id.sweetNo);
holder.eventImage = (ImageView) convertView.findViewById(R.id.eventImage);
Log.e("TAG ", "5555555555555555");
convertView.setTag(holder);
} else{
Log.e("TAG ", "6666666666666666");
holder = (ViewHolder) convertView.getTag();
}
Log.e("TAG ", "77777777777777777777777");
holder.desc.setText(EventItems.getDesc());
Log.e("TAG ", "88888888888888888");
holder.sweetNo.setText(EventItems.getSweetNo());
holder.eventImage.setImageBitmap(EventItems.getEventImage());
return convertView;
}
}
EventItems.java
import android.graphics.Bitmap;
public class EventItems {
private Bitmap eventImage;
private String sweetNo;
private String desc;
public EventItems(Bitmap eventImage, String sweetNo, String desc) {
this.eventImage = eventImage;
this.sweetNo = sweetNo;
this.desc = desc;
}
public Bitmap getEventImage() {
return eventImage;
}
public void setEventImage(Bitmap eventImage) {
this.eventImage = eventImage;
}
public String getSweetNo() {
return sweetNo;
}
public void setSweetNo(String sweetNo) {
this.sweetNo = sweetNo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
Events.java
public class Events extends Activity {
ListView listView;
List<EventItems> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final AlertDialog ad=new AlertDialog.Builder(this).create();
rowItems = new ArrayList<EventItems>();
Bitmap bm =getImageBitmap("http://192.168.1.5/Upload/Thumbnail/1/iqygbbfn.jpg");
EventItems item = new EventItems(bm,"hi", "ji");
rowItems.add(item);
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapterForEvent adapter = new CustomListViewAdapterForEvent(this,
R.layout.event_list, rowItems);
listView.setAdapter(adapter);
}
//Function for getting image from URL
private Bitmap getImageBitmap(String url)
{
Bitmap bm = null;
try
{
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e)
{
Log.e("TAG", "Error getting bitmap", e);
}
return bm;
}
}

Take a look on your EventList.xml, you have no element with id desc there, that is why you get null here (but you have eventDesc instead):
holder.desc = (TextView) convertView.findViewById(R.id.desc);
I believe it's just a typo and the correct line should be as following:
holder.desc = (TextView) convertView.findViewById(R.id.eventDesc);
P.S. Please read how to use debugger, it will make your life easier - placing a lot of Log objects is not the best solution for finding error.

Change this
holder.desc = (TextView) convertView.findViewById(R.id.desc);
To
holder.desc = (TextView) convertView.findViewById(R.id.eventDesc);
in your getView(....) into CustomListViewAdapterForEvent

Related

why is my recycler view only showing 1 card

the app is used to sign up for events. Now I am unable to display more then one card in the recycler view even though there is data in the database.it only would display only the first row of data. I know this as I have deleted the first row and the app shows the new first row.
The php works as i have loaded the page and it gives me the data from the database.
recycler view activity
public class MainActivity2 extends AppCompatActivity {
private static final String URL = "http://10.0.2.2/mad/activitydisplay.php";
RecyclerView recyclerView;
UserAdapter userAdapter;
List<Users> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
recyclerView = findViewById(R.id.recylcerList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
usersList=new ArrayList<>();
LoadAllUser();
}
private void LoadAllUser() {
JsonArrayRequest request =new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray array) {
for (int i=0;i<array.length();i++){
try {
JSONObject object=array.getJSONObject(i);
String name=object.getString("eventname").trim();
String type=object.getString("type").trim();
String location=object.getString("location").trim();
String time=object.getString("time").trim();
String date=object.getString("date").trim();
String maxparticipants=object.getString("maxparticipants").trim();
Users user= new Users();
user.setName(name);
user.setType(type);
user.setLocation(location);
user.setTime(time);
user.setDate(date);
user.setMaxparticipants(maxparticipants);
usersList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
userAdapter=new UserAdapter(MainActivity2.this,usersList);
recyclerView.setAdapter(userAdapter);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(MainActivity2.this, error.toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue=Volley.newRequestQueue(MainActivity2.this);
requestQueue.add(request);
}
}
recycler view adpater
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserHolder>{
Context context;
List<Users> usersList;
public UserAdapter(Context context, List<Users> usersList) {
this.context = context;
this.usersList = usersList;
}
#NonNull
#Override
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View userLayout= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_list,parent,false);
return new UserHolder(userLayout);
}
#Override
public void onBindViewHolder(#NonNull UserHolder holder, int position) {
Users users=usersList.get(position);
holder.Name_id.setText(users.getName());
holder.Type_id.setText(users.getType());
holder.Location_id.setText(users.getLocation());
holder.Time_id.setText(users.getTime());
holder.Date_id.setText(users.getDate());
holder.Slots_id.setText(users.getMaxparticipants());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, cardviewclick.class);
intent.putExtra("Name",holder.Name_id.getText());
intent.putExtra("Type",holder.Type_id.getText());
intent.putExtra("Location",holder.Location_id.getText());
intent.putExtra("Time",holder.Time_id.getText());
intent.putExtra("Date",holder.Date_id.getText());
intent.putExtra("Slots",holder.Slots_id.getText());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return usersList.size();
}
public class UserHolder extends RecyclerView.ViewHolder{
TextView Name_id,Type_id,Location_id,Time_id,Date_id,Slots_id;
CardView cardView;
public UserHolder(#NonNull View itemView){
super(itemView);
Name_id=itemView.findViewById(R.id.textTitle);
Type_id=itemView.findViewById(R.id.textType);
Location_id=itemView.findViewById(R.id.textLocation);
Time_id=itemView.findViewById(R.id.textTime);
Date_id=itemView.findViewById(R.id.textDate);
Slots_id=itemView.findViewById(R.id.textSlots);
cardView=itemView.findViewById(R.id.card);
}
}
}
activitydisplay.php
conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT eventname, type ,location,maxparticipants,time,date FROM activitytable");
$stmt ->execute();
$stmt -> bind_result($eventname, $type, $location,$maxparticipants,$time,$date);
$data= array();
while($stmt ->fetch()){
$temp = array();
$temp['eventname'] = $eventname;
$temp['type'] = $type;
$temp['location'] = $location;
$temp['maxparticipants'] = $maxparticipants;
$temp['time'] = $time;
$temp['date'] = $date;
array_push($data,$temp);
}
echo json_encode($data);
?>
edit 1:add xml code
main activity 2
<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"
tools:context=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recylcerList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
card 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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:id="#+id/card"
app:cardElevation="12dp"
app:cardCornerRadius="16dp"
android:layout_margin="16dp"
android:backgroundTint="#efefef"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textTitle"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textType"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textLocation"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textDate"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Time:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textTime"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Slots:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textSlots"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
It is because the LinearLayout of the card has match_parent as its layout_height and layout_width so it is taking up the whole space. Can you try to scroll the card up?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent" <-------- here
android:layout_height="match_parent">. <-------- here
The layout_height should be wrap_content.

Android - OnClick inside gridview row

I'm trying to launch a activity from a button inside my gridview item, meaning that when user click on gridview Item it should do one function and when the user click on the button inside the gridview item it should do another function, let me elaborate, here is my single item layout that is being populated inside of my gridview;
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/single_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgFood"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:civ_border_color="#ffffff"
app:civ_border_width="2dp"
app:civ_shadow="true"
app:civ_shadow_color="#000000"
app:civ_shadow_radius="10" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imgFood">
<TextView
android:id="#+id/txtName"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/currentid"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_below="#+id/txtName"
android:text="Current ID : "
android:visibility="visible"
/>
<TextView
android:id="#+id/studentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp"
android:layout_below="#+id/txtName"
android:layout_toRightOf="#+id/currentid"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
/>
</RelativeLayout>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/editit"
android:background="#android:drawable/btn_dialog"/>
</RelativeLayout>
here is how the above layout looks:
and here is my adapter getview from where I try to do the intent/actions from;
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.studentid);
holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
holder.dit = (Button) row.findViewById(R.id.editit);
final ViewHolder finalHolder = holder;
holder.dit.setOnClickListener(new View.OnClickListener() {
String getname = finalHolder.txtName.getText().toString();
String gethandicap = finalHolder.txtPrice.getText().toString();
#Override
public void onClick(View v) {
// Do something
Intent editintent = new Intent(context, MainActivity.class);
editintent.putExtra("studentname", getname);
editintent.putExtra("studentid", getID);
context.startActivity(editintent);
}
});
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Sudentdb student = studentsList.get(position);
holder.txtName.setText(student.getName());
holder.txtPrice.setText(student.getID());
if (student.getImage() != null && student.getImage().length > 0) {
Glide.with(context)
.load(student.getImage())
.into(holder.imageView);
} else {
holder.imageView.setImageBitmap(null);
}
return row;
}
The problem I'm having is that the button inside the gridview item is not performing any actions, in log it only says ACTION_DOWN and since I added a button inside the item the item onclick also doesn't work.
EDIT; ADDING GRIDVIEW ONCLICK AND LAYOUT
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new StudentListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String dataFromGrid;
dataFromGrid = ((TextView)(view.findViewById(R.id.txtName))).getText().toString();
Intent i = new Intent(getApplicationContext(), Student.class);
i.putExtra("unfromstudent",dataFromGrid);
startActivity(i);
gridview layout (I have tried focusable and clickable)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
>
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:id="#+id/gridView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:columnWidth="120dp"
android:gravity="center"
android:layout_margin="2dp"
android:numColumns="1"
/>
</RelativeLayout>
Change you XML, i have tested below xml its works fine with
GridView
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:orientation="horizontal">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgFood"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="10dp"
app:civ_border_color="#ffffff"
app:civ_border_width="2dp"
app:civ_shadow="true"
app:civ_shadow_color="#000000"
app:civ_shadow_radius="10" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/currentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:text="Current ID : "
android:visibility="visible" />
<TextView
android:id="#+id/studentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
android:layout_toRightOf="#+id/currentid"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="30dp"
android:layout_height="30dp">
<Button
android:id="#+id/editit"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:background="#android:drawable/btn_dialog"
android:focusable="false" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Your Grid View XML will be Like this.
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true">
</GridView>
I don't have enough reputation so i can't comment your question, why don't you use a recyclerview with a gridLayoutManager? You can see a basic example here .
After that you can implement your recyclerview adapter this way:
public class StudentsAdapter extends RecyclerView.Adapter<StudentsAdapter.ViewHolder> {
private final OnStudentItemClickListener mListener;
private Context mContext;
private List<Student> mStudents;
public StudentsAdapter(Context context, List<Student> items, OnStudentItemClickListener listener) {
mContext = context;
mStudents =items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_student, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Student student = mStudents.get(position);
holder.mTextName.setText(student.getName());
holder.mTextPrice.setText(student.getID());
if (student.getImage() != null && student.getImage().length > 0) {
Glide.with(context)
.load(student.getImage())
.into(holder.imageView);
} else {
holder.imageView.setImageBitmap(null);
}
}
#Override
public int getItemCount() {
return mStudents.size();
}
public interface OnStudentItemClickListener {
void onStudentItemClick(Student student);
void onStudentButtonClick(Student student);
}
public class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
TextView mTextName;
TextView mTextPrice;
CircleImageView mImageView;
Button mDit;
public ViewHolder(View view) {
super(view);
mTextName = (TextView) view.findViewById(R.id.txtName);
mTextPrice = (TextView) view.findViewById(R.id.studentid);
mImageView = (CircleImageView) view.findViewById(R.id.imgFood);
mDit = (Button) view.findViewById(R.id.editit);
mDit.setOnClickListener(view1 -> {
if (null != mListener) {
mListener.onStudentButtonClick(mStudents.get(getAdapterPosition()));
}
});
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (null != mListener) {
mListener.onStudentItemClick(mStudents.get(getAdapterPosition()));
}
}
}
}

Listview items duplicated/wrong position when scrolling

This question is been asked multiple times, but everyone has his specific usage of listview adapters (ArrayAdapter or BaseAdapter).
I searched a lot before asking this question, and this same problem happened to me before and i solved it using Holder class, and cleaning code to make it the minimum possible.
But now, i am creating another interface which contains a listview and needs a BaseAdapter to fill it using a List of Object (List).
The weird thing in my case is, if my listview contains only 4 items ( 4 rows ) then everything is ok, but if it contains more than 4, first items will be duplicated, and if i scroll down/up fast , items got wrong positions.
Here is my code :
public class OrdersAdapter extends BaseAdapter {
List<Order> ordersList;
FragmentActivity activity;
private int height;
public OrdersAdapter(FragmentActivity activity, List<Order> ordersList){
this.activity = activity;
this.ordersList = ordersList;
height = Constants.getOneThirdScreenHight(activity);
}
#Override
public int getCount() {
return ordersList.size();
}
#Override
public Order getItem(int position) {
return ordersList.get(position);
}
#Override
public long getItemId(int position) {
return ordersList.hashCode();
}
private class MyHolder{
TextView orderNumber, orderDate, menuCount, orderPrice, orderStatus, orderTelephone, orderStoreName;
ImageView orderDelete, menuPicture;
Order order, mOrder;
String numberText = activity.getResources().getString(R.string.order_number);
HashMap<String, String> map;
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
}
#Override
public View getView (final int position, View convertView, ViewGroup parent) {
View vi;
final MyHolder holder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater)activity.getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new MyHolder();
vi = layoutInflater.inflate(R.layout.sent_order_item, null);
holder.order = getItem(position);
holder.mOrder = new Order();
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.height = height;
vi.findViewById(R.id.order_history_layout).setLayoutParams(layoutParams);
holder.orderNumber = (TextView) vi.findViewById(R.id.order_number);
holder.orderDate = (TextView) vi.findViewById(R.id.order_date);
holder.orderDelete = (ImageView) vi.findViewById(R.id.order_delete);
holder.orderPrice = (TextView) vi.findViewById(R.id.order_history_price);
holder.orderStatus = (TextView) vi.findViewById(R.id.order_history_status);
holder.orderStoreName = (TextView) vi.findViewById(R.id.order_history_store);
holder.orderTelephone = (TextView) vi.findViewById(R.id.order_history_phone);
holder.menuCount = (TextView) vi.findViewById(R.id.order_menu_count1) ;
holder.menuPicture = (ImageView) vi.findViewById(R.id.order_picture);
vi.setTag(holder);
}else{
vi = convertView;
holder = (MyHolder) vi.getTag();
}
//Getting Restaurants infos ( name and telephone ) from firebase
holder.mDatabase.child(Constants.STORES_PROFILES + "/" + holder.order.getOwner_uid() + "/" + holder.order.getStore_id())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(holder.map==null){
holder.map = (HashMap<String, String>)dataSnapshot.getValue();
}
if(dataSnapshot.getValue()!=null) {
holder.orderStoreName.setText(holder.map.get(Constants.NAME));
holder.orderTelephone.setText(holder.map.get(Constants.TELEPHONE));
}
//notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//checking Order's status (received, validated, in progress, delivered)
holder.mDatabase.child(Constants.ORDERS + "/" + holder.order.getOwner_uid() + "/" + holder.order.getStore_id() + "/" + holder.order.getOrderId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
try {
holder.mOrder = dataSnapshot.getValue(Order.class);
if (!holder.order.getStatus().equals(holder.mOrder.getStatus())) {
holder.order.setStatus(holder.mOrder.getStatus());
//update status value for the user
holder.mDatabase.child(Constants.USERS+"/"+ Authentication.getCurrentUser().getUid()+"/"+Constants.SUBMITTED_ORDERS_KEY
+"/"+holder.order.getOrderId()+"/"+Constants.STATUS).setValue(holder.mOrder.getStatus());
//notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
displayOrder(holder);
return vi;
}
public void displayOrder(MyHolder holder){
holder.orderStatus.setText(holder.order.getStatus());
holder.orderNumber.setText(holder.numberText + holder.order.getOrderNumber());
holder.orderDate.setText(Utils.parseDateToDisplay((Long)holder.order.getCreated_at()));
holder.menuCount.setText(holder.order.getMyMealsList().get(0).getQuantity()+"");
holder.orderPrice.setText(holder.order.getTotal_price_formatted());
Glide.with(activity)
.load(holder.order.getMyMealsList().get(0).getMain_image())
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(holder.menuPicture);
if(OrdersContainerFragment.pDialog.isShowing()){
OrdersContainerFragment.pDialog.dismiss();
}
}
}
Here is my "xml" file :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/order_history_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<LinearLayout
android:id="#+id/save_order_linear"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:background="#fcf5ef"
android:orientation="horizontal"
android:weightSum="100">
<TextView
android:id="#+id/order_number"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/order_number"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:typeface="serif"/>
<TextView
android:id="#+id/order_date"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="50"
android:gravity="center"
android:text="00/00/0000"
android:textColor="#color/colorPrimary"
android:typeface="serif"/>
</LinearLayout>
<LinearLayout
android:id="#+id/save_order_pics"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/save_order_linear"
android:layout_marginLeft="5dp"
android:layout_marginTop="15dp"
android:layout_weight="74"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:weightSum="100">
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="33">
<ImageView
android:id="#+id/order_picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ProgressBar
android:id="#+id/order_progressBar1"
style="#android:style/Widget.DeviceDefault.Light.ProgressBar.Large"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:indeterminate="true"
android:indeterminateDrawable="#drawable/my_progressbar"
android:padding="22dp"
android:visibility="gone"/>
<TextView
android:id="#+id/order_menu_count1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="false"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="false"
android:gravity="bottom|right"
android:paddingBottom="15dp"
android:paddingRight="15dp"
android:text="ABCD"
android:textColor="#color/gray"
android:textSize="22dp"
android:typeface="serif"/>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="67"
android:orientation="vertical"
android:paddingLeft="15dp"
android:weightSum="100">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="false"
android:layout_weight="1"
android:text="#string/order_price"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_price"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="false"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="#string/order_status"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_status"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorAccent"
android:typeface="monospace"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="#string/Phone"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_phone"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="#string/order_store"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_store"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/save_order_pics"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#fcf5ef"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>

ANDROID - Remove extra space of listview header image

I have a listview with a header image , there is extra space top and bottom of the image . I want to remove the space from it ,
My layout is LinierLayout if anyone knows please help ?
my xml files is down
this is the code for list items xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
android:textColor="#android:color/white"
android:id="#+id/tvHeader"
android:visibility="gone" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tvHeader"
android:orientation="horizontal"
android:paddingLeft="10dp">
<ImageView
android:id="#+id/imageView"
android:layout_gravity="center"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="0dp"
android:layout_marginTop="10dp"
android:paddingBottom="0dp"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="10dp"/>
<!-- img -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="15dp"
android:layout_marginTop="30dp"
android:layout_marginRight="5dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/fname"
android:text="Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="12sp"
android:textStyle="bold"
android:layout_weight="1"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lname"
android:textColor="#000"
android:textSize="12sp"
android:textStyle="bold"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/organizationname"
android:textSize="10sp"
android:paddingTop="10px" />
<TextView
android:text="yyyyyyyyyyyyyyyyy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idposition"
android:textSize="10sp"
android:layout_below="#+id/fname"
android:layout_alignLeft="#+id/fname"
android:layout_alignStart="#+id/fname" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
this is adapter file
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.parse.*;
import com.squareup.picasso.*;
import org.w3c.dom.Text;
import java.io.*;
import java.net.*;
import java.util.*;
public class IndividualsAdaptor extends ArrayAdapter {
private static final int TYPE_SECTION_HEADER = 0;
private static final int TYPE_LIST_ITEM = 1;
protected Context mContext;
ArrayList<Integer> mListHeader = new ArrayList<>();
// Code for Custom Filter.
protected List mBackupList = new ArrayList();
public IndividualsAdaptor(Context context, List status) {
super(context, R.layout.t3, status);
mContext = context;
// Code for Custom Filter.
mBackupList.addAll(status);
}
#Override
public int getViewTypeCount() { return 2; }
#Override
public int getItemViewType(int position)
{
if (mListHeader.contains(position)){
return TYPE_SECTION_HEADER;
} else {
return TYPE_LIST_ITEM;
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.t3, null);
holder = new ViewHolder();
holder.tvHeader = (TextView) convertView.findViewById(R.id.tvHeader);
holder.usernameHomepage = (TextView) convertView.findViewById(R.id.fname);
holder.statusHomepage = (TextView) convertView.findViewById(R.id.lname);
holder.pposition = (TextView) convertView.findViewById(R.id.idposition);
holder.orgName = (TextView) convertView.findViewById(R.id.organizationname);
holder.logo = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject statusObject = (ParseObject) getItem(position);
// title
String username = statusObject.getString("firstname");
holder.usernameHomepage.setText(username);
// content
String status = statusObject.getString("lastname");
holder.statusHomepage.setText(status);
// Header
if(getItemViewType(position) == TYPE_SECTION_HEADER){
holder.tvHeader.setVisibility(View.VISIBLE);
holder.tvHeader.setText(String.valueOf(status.charAt(0)));
}else{
holder.tvHeader.setVisibility(View.GONE);
}
// content
String positions = statusObject.getString("position");
holder.pposition.setText(positions);
// content
String org = statusObject.getString("organizationName");
holder.orgName.setText(org);
// logo
URL url = null;
Bitmap bmp = null;
try {
url = new URL("file location" + statusObject.getString("image"));
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
}catch (IOException e) {
}
holder.logo.setImageBitmap(bmp);
Picasso.with(mContext)
.load(String.valueOf(url))
.transform(new Rounded( ))
.into(((ImageView) convertView
.findViewById(R.id.imageView)));
return convertView;
}
public static class ViewHolder {
TextView tvHeader;
TextView usernameHomepage;
TextView statusHomepage;
TextView orgName;
TextView pposition;
ImageView logo;
}
#Override
public Filter getFilter() {return new Filter(){
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String queryString = charSequence.toString().toLowerCase();
List<ParseObject> filteredList = new ArrayList<>();
ParseObject tmpItem;
String tmpUsername, tmpStatus, tmpPositions, tmpOrg;
for(int i=0; i<mBackupList.size(); i++){
tmpItem = (ParseObject) mBackupList.get(i);
tmpUsername = tmpItem.getString("firstname").toLowerCase();
tmpStatus = tmpItem.getString("lastname").toLowerCase();
tmpPositions = tmpItem.getString("position").toLowerCase();
tmpOrg = tmpItem.getString("organizationName").toLowerCase();
// The matching condition
if(tmpUsername.contains(queryString)||tmpStatus.contains(queryString)||
tmpPositions.contains(queryString)||tmpOrg.contains(queryString)){
filteredList.add(tmpItem);
}
}
FilterResults filterResults = new FilterResults();
filterResults.count = filteredList.size();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
clear();
addAll((List<ParseObject>) filterResults.values);
}
};}
public void updateBackupList(List newList){
mBackupList.clear();
mBackupList.addAll(newList);
}
public void updateHeaderList(ArrayList<HashMap> newHeaderList){
for(int i=0; i<newHeaderList.size(); i++){
mListHeader.add(Integer.parseInt((String)newHeaderList.get(i).get("position")));
}
Log.d("Test", mListHeader.toString());
}
}
java file
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="110dp"
/>
<TextView android:id="#+id/tvEmpty"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#083266"/>
<SearchView
android:id="#+id/ser1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="Search.."
android:background="#color/FBC_RED"
android:layout_below="#id/tvEmpty"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="0dp">
</SearchView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_below="#+id/ser1">
<ListView
android:id="#id/android:list"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.89" />
<ListView
android:id="#+id/listIndex"
android:layout_width="0dp"
android:layout_height="match_parent"
android:scrollbars="none"
android:layout_weight="0.08">
</ListView>
</LinearLayout>
</LinearLayout>
This should work:
ListView listView = getListView();
ImageView mListHeader = new ImageView(getContext());
mListHeader.setImageResource(R.drawable.individuals_img);
mListHeader.setScaleType(ImageView.ScaleType.FIT_XY);
mListHeader.setLayoutParams(new AbsListView.LayoutParams(1400,974));
mListHeader.requestLayout();
listView.addHeaderView(mListHeader);
Inflate a custom layout as your listview header and add below imageview to it
code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.list);
View header = getLayoutInflater().inflate(R.layout.header, list, false); //custom layout
list.addHeaderView(header, null, false);
}
try this: in your header.xml add the header image
<ImageView
android:id="#+id/imageView"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:src="your_source"
android:layout_marginLeft="10dp"
android:layout_marginRight="0dp"
android:layout_marginStart="0dp"
android:adjustViewBounds="true"
android:background="#android:color/transparent"
android:paddingBottom="0dp"
android:scaleType="fitXY" />

Errors on Adding ListView to Fragment

I am trying to add a listview to an existing android fragment. I made a layout xml file for items in the listview, modified the previous fragment.xml, wrote a new arrayadapter and added something to the fragment.java. But whenever I call the notifyDataSetChanged() method in the fragment.java, I got an error: android.content.res.Resources$NotFoundException: String resource ID #0x0, and then the app crashes. Below please find my codes.
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="7dp">
<ImageView
android:layout_width="72dp"
android:layout_height="72dp"
android:id="#+id/iv_checkIcon"
android:layout_margin="7dp"
android:background="#EEEEEE"
android:contentDescription="Provider icon"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_toRightOf="#id/iv_checkIcon"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="5dp"
>
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkName"
android:text="Provider name"
android:textSize="20dp"
/>
<TextView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkInDate"
android:text="Check In Date"
android:textSize="14dp"
android:textColor="#888888"
android:layout_marginTop="4dp"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_checkPoints"
android:layout_alignParentRight="true"
android:text="100分"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textSize="18dp"
android:textColor="#CF1A12"
/>
</RelativeLayout>
fragment.xml
<FrameLayout 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"
tools:context=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</FrameLayout>
Arrayadapter.java
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRecList;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRecList)
{
super(context, resourceId, checkInRecList);
this.resourceId = resourceId;
this.context = context;
this.checkInRecList = checkInRecList;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_checkName);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkInDate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_checkPoints);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_checkIcon);
CheckInRecord.CheckInRec checkInRec = checkInRecList.get(position);
textViewName.setText(checkInRec.providerName);
textViewCheckInDate.setText(checkInRec.checkInDate);
textViewPoints.setText(checkInRec.providerPoints);
ImageLoader.getInstance().displayImage(checkInRec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRecList.get(position).isPrize);}
}
fragment.java
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRecList = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View fragmentView = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) fragmentView.findViewById(R.id.tv_name);
textViewPoints = (TextView) fragmentView.findViewById(R.id.tv_points);
ListView listViewRec = (ListView) fragmentView.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity(), R.layout.row_record, checkInRecList);
listViewRec.setAdapter(recordArrayAdapter);
return fragmentView;
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
this.checkInRecList.clear();
this.checkInRecList.addAll(checkInRecord.checkInRecList);
recordArrayAdapter.notifyDataSetChanged();
}
}
}
Make sure checkInRec.providerName, checkInRec.checkInDate and checkInRec.providerPoints values that you set as TextView text have a type of String and cast it to String if it's integer.
// cast to String if checkInRec.checkInDate is integer
textViewPoints.setText(String.valueOf(checkInRec.providerPoints));
UPD:
It seems ListView is located behind header view. Try to change root view of fragment.xml from FrameLayout to LinearLayout with android:orientation="vertical" attribute. Like this:
<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"
tools:context=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</LinearLayout>

Categories