How can i make TextView selected in GridView based on clicked position? - java

I am using a fragment where i am using a GridView to generate some categories. When user selects a category i am replacing the previous fragment with a new fragment which is used to take the details of the category. But when i get back to the previous fragment where the categories are displayed i want to make the category selected on which the user previously clicked. I have tried to use selector but it is not working for me. Here goes my code.
Here is my layout xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="20dp"
>
<GridView
android:id="#+id/hindernisTypGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="190dp"
android:verticalSpacing="20dp"
android:layout_below="#+id/topBar"
android:horizontalSpacing="5dp"
android:paddingLeft="32dp"
android:paddingRight="32dp"
/>
</LinearLayout>
Here is my custom xml for gridview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools=" http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="190dp"
android:layout_height="180dp"
android:padding="2dp"
tools:ignore="MissingPrefix"
>
<TextView
android:textColor="#color/redText"
android:textSize="37.14sp"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="180dp"
android:text="OBW"
android:id="#+id/hindernisTypTextView"
fontPath="DBSansRegular.otf"
android:textAppearance="#style/DBSansRegular"
android:background="#drawable/grid_view_item_selector"
/>
</RelativeLayout>
Here is my selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/redText" android:state_pressed="true"/>
</selector>
Here is the Fragment which is used to display the categories
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
import com.example.anikdey.railwayapp.models.HindernisTyp;
public class HindernisTypFragment extends Fragment {
private GridView projectListGridView;
private View view;
private HindernisTyp hindernisTyp;
private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
private OnHindernisTypSelectedListener hindernisTypSelectedListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
hindernisTyp = new HindernisTyp();
hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps());
projectListGridView.setAdapter(hindernisTypGridViewAdapter);
projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
fragmentTransaction.addToBackStack("df");
fragmentTransaction.commit();
}
});
return view;
}
}
The adapter i have used for displaying the categories in gridview
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.models.HindernisTyp;
import java.util.ArrayList;
import java.util.List;
public class HindernisTypGridViewAdapter extends BaseAdapter {
private Context context;
private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();
public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps){
this.context = context;
this.hindernisTyps = hindernisTyps;
}
#Override
public int getCount() {
return hindernisTyps.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private static final class ViewHolder {
private TextView hindernisTypTextView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
holder = new ViewHolder();
holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
return convertView;
}
}

When user going to details fragment send that selected category to main activity or shared preference or constant but not try to rely on onSaveInstanceState()
Now when you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView() in the fragment lifecycle, see Fragment Lifecycle.
Now start form onCreateView()
So add a boolean isRestoredFromBackstack to fragment and follow code below:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mIsRestoredFromBackstack = false;
}
#Override
public void onResume()
{
super.onResume();
if(mIsRestoredFromBackstack)
{
// The fragment restored from backstack,
// get selected state and set category selected again!
}
}
#Override
public void onDestroyView()
{
super.onDestroyView();
mIsRestoredFromBackstack = true;
}
OR
there is another simple solution.... depends on situation
just use add() not replace()
Fragment fragment=new DestinationFragment();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();

Here is the way by which i have solved my problem. Before starting the new fragment i am storing the position in a variable named previousPosition which was initialized whit a negative value of -1. Then i am passing the previousPosition in the Adapter. The code is given below.
The updated Fragment class
package com.example.anikdey.railwayapp.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
import com.example.anikdey.railwayapp.models.HindernisTyp;
public class HindernisTypFragment extends Fragment {
private GridView projectListGridView;
private View view;
private HindernisTyp hindernisTyp;
private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
private OnHindernisTypSelectedListener hindernisTypSelectedListener;
private int previousPosition = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
hindernisTyp = new HindernisTyp();
hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps(), previousPosition);
projectListGridView.setAdapter(hindernisTypGridViewAdapter);
projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
hindernisTypSelectedListener.enableCancelButton(true);
previousPosition = position;
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
fragmentTransaction.addToBackStack("df");
fragmentTransaction.commit();
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
hindernisTypSelectedListener = (OnHindernisTypSelectedListener) activity;
} catch (ClassCastException e) {
}
}
public interface OnHindernisTypSelectedListener {
public void setHindernisTyp(String hindernisTyp);
public void enableCancelButton(boolean state);
}
}
Here is the updated Adapter class
package com.example.anikdey.railwayapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.models.HindernisTyp;
import java.util.ArrayList;
import java.util.List;
public class HindernisTypGridViewAdapter extends BaseAdapter {
private Context context;
private int previousPosition;
private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();
public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps, int previousPosition){
this.context = context;
this.hindernisTyps = hindernisTyps;
this.previousPosition = previousPosition;
}
#Override
public int getCount() {
return hindernisTyps.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private static final class ViewHolder {
private TextView hindernisTypTextView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
holder = new ViewHolder();
holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position == previousPosition) {
holder.hindernisTypTextView.setBackgroundColor(context.getResources().getColor(R.color.redText));
holder.hindernisTypTextView.setTextColor(context.getResources().getColor(R.color.whiteText));
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
} else {
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
}
return convertView;
}
}

Related

Android YoutubePlayerView video is not visible

I'm using PierfrancescoSoffritti YouTubePlayerView but the videos are not visible in recycler view only the sound and thumbnail is showing. Need some help.
Here is the youtubeplayer 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:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent">
<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="#+id/video_player" app:autoPlay="false" app:videoId="S0Q4gqBUs7c" app:showFullScreenButton="true"
app:useWebUi="true" app:enableLiveVideoUi="true" app:enableAutomaticInitialization="true" />
</LinearLayout>
The Adapter Class where the youtubeplayerview is initialized
package aritra.code.chatters.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.YouTubePlayerListener;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import aritra.code.chatters.MainActivity;
import aritra.code.chatters.Models.DummyPOJO;
import aritra.code.chatters.R;
import aritra.code.chatters.databinding.SampleVideoBinding;
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {
Context context;
List<DummyPOJO> list;
public VideoAdapter(Context context, List<DummyPOJO> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public VideoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.sample_video, parent, false);
return new VideoViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull VideoViewHolder holder, int position) {
DummyPOJO data = list.get(position);
((MainActivity) context).addLifeCycleCallBack(holder.binding.videoPlayer);
holder.binding.videoPlayer.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
#Override
public void onReady(#NotNull YouTubePlayer youTubePlayer) {
super.onReady(youTubePlayer);
String videoId = data.getVideoId();
youTubePlayer.cueVideo(videoId, 0);
youTubePlayer.play();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
SampleVideoBinding binding;
public VideoViewHolder(#NonNull View itemView) {
super(itemView);
binding = SampleVideoBinding.bind(itemView);
}
}
}
Everything works fine except the visibility of the video
The issue seems to stem from adding the following inside manifest.
android:hardwareAccelerated="false"
Once that is removed, everything works fine.

getting java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm getting error in crimeholder class , which states
'java.lang.NullPointerException:Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference'
I copied pasted most of the code from the book which I bought from amazon.
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
//
private class CrimeHolder extends RecyclerView.ViewHolder {
private Crime mCrime;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
}
}
//
import android.support.v4.app.Fragment;
public class CrimeActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new CrimeFragment();
}
}
//
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
public CheckBox mSolvedCheckBox;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
mCrime.setmTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getmDate().toString());
mDateButton.setEnabled(false);
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setmSolved(isChecked);
}
});
return v;
}
}
//
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}
return sCrimeLab;
}
private CrimeLab(Context context) {
mCrimes = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Crime crime = new Crime();
crime.setmTitle("Crime #" + i);
crime.setmSolved(i % 2 == 0); // Every other one
mCrimes.add(crime);
}
}
public List<Crime> getCrimes() {
return mCrimes;
}
public Crime getCrime(UUID id) {
for (Crime crime : mCrimes) {
if (crime.getmId().equals(id)) {
return crime;
}
}
return null;
}
}
//
import android.support.v4.app.Fragment;
public class CrimeListActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new CrimeListFragment();
}
}
//
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
private class CrimeHolder extends RecyclerView.ViewHolder {
private Crime mCrime;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
}
}
//
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstract Fragment createFragment();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
}
//activity_fragment.xmml
FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_container"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CrimeActivity">
</FrameLayout>
//fragment_crime.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"/>
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/crime_title_hint" />
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"/>
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_solved_label"/>
</LinearLayout>
//
//fragment_crime_list.xml
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
//list_item_crime.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="crime_title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/crime_date"
android:text="crime_date"/>
Try as follows
In your CrimeAdapter under onCreateViewHolder, Pass views to CrimeHolder
class
#NonNull
#Override
public CrimeHolder onCreateViewHolder(#NonNull ViewGroup viewGroup,int i){
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate( R.layout.list_item_crime, viewGroup, false );
// here pass view as a constructor
return new CrimeHolder(view);
}
In your CrimeHolder, set to superclass and retrieve other property as follows
private class CrimeHolder extends RecyclerView.ViewHolder{
private TextView mTitleTextView;
private TextView mDateTextView;
CrimeHolder(View view){
super(view);
mTitleTextView = view.findViewById(R.id.textView);
mDateTextView = view.findViewById(R.id.textView2);
}
}
You are not finding the views properly, you are calling super() and in the same time trying to find the textviews from itemView which I don't where are you initialing it. Do the following:
Replace
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
with
mTitleTextView = (TextView) findViewById(R.id.crime_title);
mDateTextView = (TextView) findViewById(R.id.crime_date);
OR
Replace
super(inflater.inflate(R.layout.list_item_crime, parent, false));
with
itemView = (ViewGroup) inflater.inflate(R.layout.list_item_crime, parent, false);

when i use setOnItemClickListener in GridView return null

I have a problem when i use setOnItemClickListener to get the id of clicked item in GridView return null. I try to do that because I want when a user click an item I retrieve data from db then represent it in another fragment so there is a solution to get id or there are another way to deal with that. thanks a lot.
I use an Adapter:
The fragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.mohamed.osarelkheir.Adapters.Section_Adapter;
import com.example.mohamed.osarelkheir.First_Launch;
import com.example.mohamed.osarelkheir.Models.Section_Model;
import com.example.mohamed.osarelkheir.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Sections_Fragment extends Fragment {
private GridView Dep_grid_View; //object from GridView (list) -Session Fragment
private List<Section_Model> Dep_list; //Data Model Object
private Section_Adapter section_adapter; //Adapter Object
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private String Dep_id;
private String item;
private DocumentSnapshot lastVisible; //to print the last ....
//Empty Contractor
public Sections_Fragment() {
}
private FragmentManager fragmentManager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.section_fragment, container, false);
Dep_grid_View = view.findViewById(R.id.gridSection);
Dep_list = new ArrayList<>();
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
// myList = Arrays.asList(section_models); //he create its own array list to view it as a templet data cooooool
section_adapter = new Section_Adapter(getContext(), Dep_list);
Dep_grid_View.setAdapter(section_adapter);
//First Query
Query firstQuery = firebaseFirestore.collection("Department");
firstQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot snapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
// Toast.makeText(getActivity(), "No", Toast.LENGTH_SHORT).show();
for (DocumentChange doc : snapshots.getDocumentChanges()) {
// Toast.makeText(getActivity(), "NoO", Toast.LENGTH_SHORT).show();
if (doc.getType() == DocumentChange.Type.ADDED) {
// Toast.makeText(getActivity(), "No00", Toast.LENGTH_SHORT).show();
Dep_id = doc.getDocument().getId();
Toast.makeText(getActivity(), "Id" + Dep_id, Toast.LENGTH_SHORT).show();
// <<<<<<<<<<<<<GET DATA from DB >>>>>>>>>>>>>>>>>>
Section_Model section_model = doc.getDocument().toObject(Section_Model.class).withId(Dep_id);
//<<<<<<<<<<<<<<<then Put it in object of BlogList >>>>>>>>>>>>>>
Dep_list.add(section_model);
section_adapter.notifyDataSetChanged();
}
}
}
});
Dep_grid_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//it's return null
item = Dep_grid_View.getItemAtPosition(i).toString();
printadminview();
}
});
return view;
}
void printadminview() {
Intent intent = new Intent(getContext(), First_Launch.class);
intent.putExtra("value", 3);
intent.putExtra("Dep_ID", item );
// Toast.makeText(getActivity(), "pos " + pos, Toast.LENGTH_SHORT).show();
getContext().startActivity(intent);
}
}
The .xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#drawable/item_background_manage"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_weight="1"
android:queryHint="search"/>
</LinearLayout>
<GridView
android:id="#+id/gridSection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="3dp"
android:layout_margin="8dp" />
</LinearLayout>
Adapter class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mohamed.osarelkheir.First_Launch;
import com.example.mohamed.osarelkheir.Models.Section_Model;
import com.example.mohamed.osarelkheir.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.List;
public class Section_Adapter extends ArrayAdapter<Section_Model> { //1
private Context mContext;
private List<Section_Model> data;
public Section_Adapter(Context mContext,List<Section_Model> data) {//2
super(mContext,R.layout.item_section,data);
this.mContext = mContext;
this.data = data;
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.item_section, parent, false);
holder = new ViewHolder();
holder.txtSectionName = row.findViewById(R.id.sectionName);
holder.imageView = row.findViewById(R.id.imageSection);
holder.imageIc = row.findViewById(R.id.ic_sec);
row.setTag(holder);
row.setTag(new Integer(position));
} else {
holder = (ViewHolder) row.getTag();
}
setView(holder, position);
Section_Model model = getItem(position);
String id = model.getId();
Intent intent=new Intent(mContext, First_Launch.class);
intent.putExtra("value",1);
intent.putExtra("DepartmentId", id);
mContext.startActivity(intent);
return row;
}
private void setView(ViewHolder holder, int position) {
Section_Model section_model = data.get(position);
holder.txtSectionName.setText(section_model.getSection_name());
String downlaodUriImage = section_model.getSection_image();
String DownloadUriLogo = section_model.getSection_icon();
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.logo);
Glide.with(mContext).applyDefaultRequestOptions(requestOptions).load(downlaodUriImage).into(holder.imageView);
Glide.with(mContext).load(DownloadUriLogo).apply(requestOptions.override(40,40)).into(holder.imageIc);
}
static class ViewHolder {
TextView txtSectionName;
ImageView imageView;
ImageView imageIc;
}
}
To only get the id, you just need to use the following code lines.
firstQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String documentId = document.getId();
Log.d(TAG, documentId);
}
}
}
});
There is no need to use addSnapshotListener unless you need to get data in real-time. The output will be:
CIcg...
E30F...
rXY9...
If you need to get the corresponding id of item that was clicked, simply use getItem(position);
According to your comment, the simplest way would be to add a new property in your Section_Model class named id in which to can store the id of each particular document. So everytime you add a new document, that document will contain the id. Using getItem(position) will return an object of Section_Model class. See the code below:
Section_Model model = getItem(position);
String id = model.getId();
So model.getId() will return the id of the object that was set when you have added that document to the database.

OnCreateView method in Activity class

fragment reminder image - current problem
This current class that I am using called Fragment Reminder is used to display a list of the medications that have been entered. However this class before was a Fragment and I decided to change it to an Activity and the method which displays the list called onCreateView is unused now. When I click on that button to run this class the screen goes dark for some reason. Now that this class is an Activity the onCreateView cannot be used since that is for a Fragment. What should I change that to so I can create the list.
FragmentReminder:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.view.View.GONE;
public class FragmentReminder extends Activity implements View.OnClickListener{
private ArrayList al;
private List list=new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al)
{
this.al=al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
// #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setTitle("Medicine Reminder");
View v=inflater.inflate(R.layout.fragment_reminder, container, false);
fab=(FloatingActionButton)v.findViewById(R.id.floatingActionButton);
lv=(ListView)v.findViewById(R.id.rem_lv);
tv=(TextView) v.findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db=new DatabaseHandler(this);
list=db.getAllReminders();
if(list.size()==0)
{
lv.setVisibility(GONE);
return v;
}
tv.setVisibility(GONE);
adapter = new CustomList(this,list,desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in=new Intent(FragmentReminder.this,MedRemInfo.class);
in.putExtra("id",list.get(i).toString());
startActivity(in);
}
});
//***************************************************************************
return v;
}
#Override
public void onClick(View v) {
Intent in=new Intent(this,AddReminder.class);
startActivity(in);
}
}
fragment_reminder.xml:
<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="com.example.junai.mrtest2.FragmentReminder">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:id="#+id/reminder_tv"
android:textSize="20dp"
android:text="No Reminders to show, Add a reminder.."
android:gravity="center"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:src="#drawable/ic_add_black_24dp"
android:tint="#ffffff"
android:layout_gravity="bottom|center"
android:id="#+id/floatingActionButton" />
<ListView
android:layout_width="match_parent"
android:id="#+id/rem_lv"
android:layout_height="match_parent"
/>
</LinearLayout>
MainActivity:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Created by junai on 20/03/2018.
*/
public class MainActivity extends Activity {
private Button btn_addReminder, btn_reminderinfo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_addReminder = (Button) findViewById(R.id.btn_addReminder);
btn_addReminder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AddReminder.class));
}
});
btn_reminderinfo = (Button) findViewById(R.id.btn_reminderinfo);
btn_reminderinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, FragmentReminder.class));
}
});
}
}
CustomList:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
public class CustomList extends ArrayAdapter<String> {
private List names;
private String[] desc;
private Activity context;
public CustomList(Activity context, List names, String[] desc) {
super(context, R.layout.list_medinfo, names);
this.context = context;
this.names = names;
this.desc = desc;
}
String color_hex[]={"#ff4000","#0000ff","#003EFF","#5C246E","#8B668B","#CD2990","#D41A1F","#FBDB0C","#FF6600"};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//********************************************************************
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_medinfo, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(getItem(position));
String firstLetter = null;
//get first letter of each String item
Log.d("String",getItem(position));
String str=getItem(position);
firstLetter=String.valueOf(str.charAt(0)).toUpperCase();
// firstLetter.toUpperCase();
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
//int color = generator.getColor(getItem(position));
int color = generator.getRandomColor();
int pos= new Random().nextInt(color_hex.length);
color = Color.parseColor(color_hex[pos]);
Log.d("Color",""+pos);
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
holder.imageView.setImageDrawable(drawable);
return convertView;
//***********************************************************************
/* LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_medinfo, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.medname);
TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
textViewName.setText(names.get(position).toString());
textViewDesc.setText(desc[position]);
image.setImageResource(imageid[position]);
return listViewItem;*/
}
private class ViewHolder {
private ImageView imageView;
private TextView textView;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.medimage);
textView = (TextView) v.findViewById(R.id.medname);
Typeface typeface=Typeface.createFromAsset(context.getAssets(), "fonts/georgia.ttf");
textView.setTypeface(typeface);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
}
}
}
I've refactored your code:
public class FragmentReminder extends Activity implements View.OnClickListener {
private ArrayList al;
private List list = new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al) {
this.al = al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_reminder);
fab = (FloatingActionButton) findViewById(R.id.floatingActionButton);
lv = (ListView) findViewById(R.id.rem_lv);
tv = (TextView) findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db = new DatabaseHandler(this);
list = db.getAllReminders();
if (list.size() == 0) {
lv.setVisibility(GONE);
}
tv.setVisibility(GONE);
adapter = new CustomList(this, list, desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in = new Intent(FragmentReminder.this, MedRemInfo.class);
in.putExtra("id", list.get(i).toString());
startActivity(in);
}
});
}
#Override
public void onClick(View v) {
Intent in = new Intent(this, AddReminder.class);
startActivity(in);
}
}
You need only to move the code to onCreate() instead of onCreateView() and also you don't need to access the recently inflated view V to do findViewByID, all you have to do is setContentView() beforehand.

How to implement custom adapter to a nested fragment

i am trying to make a listview in a nested fragment which will hold as elements images with captions beneath it, though i keep getting nullpointer errors inside my custom adapter i created to fill the listview. here is the code:
The custom adapter:
import android.app.Activity;
import android.view.View;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ImageAdapter extends ArrayAdapter<Image> {
ArrayList<Image> imageList;
private Context mContext;
int resource;
public ImageAdapter(Context context, int resource, ArrayList<Image> imageObjects) {
super(context, resource, imageObjects);
this.imageList = imageObjects;
this.mContext = context;
this.resource = resource;
}
public ArrayList<Image> getImageList() {
return imageList;
}
public void setImageList(ArrayList<Image> imageList) {
this.imageList = imageList;
}
public Context getmContext() {
return mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public int getResource() {
return resource;
}
public void setResource(int resource) {
this.resource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView==null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.fragment_membership, null, true);
}
Image image = getItem(position);
ImageView layoutImage = (ImageView)convertView.findViewById(R.id.membershipimage);
layoutImage.setImageResource(image.getImageResourceID());
TextView layoutText = (TextView)convertView.findViewById(R.id.membershipCaption);
layoutText.setText(image.getImageCaption());
return super.getView(position, convertView, parent);
}
}
The fragment i use, within another fragment:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import java.util.ArrayList;
public class MembershipFragment extends Fragment {
ArrayList<Image> imageList;
ListView membershipListView;
public static MembershipFragment newInstance() {
MembershipFragment fragment = new MembershipFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_membership, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
imageList = new ArrayList<>();
for(int i=0; i<3; i++){
Image image = new Image(R.drawable.cinnamon_apple_breakfast, "Test Caption");
imageList.add(image);
}
membershipListView = (ListView)view.findViewById(R.id.membershipListView);
try{
ImageAdapter adapter = new ImageAdapter(getContext(), R.layout.list_view_item, imageList);
membershipListView.setAdapter(adapter);
}
catch (Exception e){
e.printStackTrace();
}
}
}
The app keeps crashing at startup, throwing nullpointer exceptions in the custom adapter in the getView method, when i try to set the image resource id to the imageview. Where is the problem?
I think you're confusing your layouts.
And you should use getActivity here.
ImageAdapter adapter = new ImageAdapter(getContext(), R.layout.list_view_item
You passed that layout resource there. But inside the adapter, you're using a different layout.
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView==null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.fragment_membership, null, true);
}
You made a getResource method, for a reason, I assume? You never call it.
I don't think you want your Fragment layout to hold a list of Fragment layouts (because recursion)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_membership, container, false);
return view;
}

Categories

Resources