how I can solve the error and app crashing when I try to use the code:
Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
I try to show a recyclerview in a fragment but when I use the code below got an error and app crash.
Can anyone help me to solve=
public class dashboard_device extends Fragment{
RecyclerView mRecicleView1;
RecyclerView.LayoutManager mLayoutManager1;
RecyclerView.Adapter mAdapter1;
ArrayList<String> lista_show;
String preadd;
public dashboard_device() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> lista_show = new ArrayList<String> ();
dashboard_DB db1 = new dashboard_DB (getContext ());
//recupero datbase DB
db1.open();
Cursor c = db1.ottieniTuttidati();
if (c.moveToFirst()) {
do {
lista_show.add (c.getString(2));
} while (c.moveToNext());
}
db1.close();
//fine recupero dati da db
// Inflate the layout for this fragment
mRecicleView1=container.findViewById (R.id.Reclycler_dashboard);
mRecicleView1.setHasFixedSize (true);
mLayoutManager1 = new GridLayoutManager (getContext (),3);
mAdapter1 = new adapter_dash (lista_show,getContext ());
mRecicleView1.setLayoutManager (mLayoutManager1);
mRecicleView1.setAdapter (mAdapter1);
runanimation1(mRecicleView1,0);
Log.d("tag", String.valueOf (lista_show));
return inflater.inflate (R.layout.dashboard_device_layout, container, false);
}
private void runanimation1(RecyclerView mRecicleView, int type) {
Context context=mRecicleView.getContext ();
LayoutAnimationController controller = null;
if(type==0)
controller = AnimationUtils.loadLayoutAnimation (context,R.anim.layout_animation);
mRecicleView.setLayoutAnimation (controller);
mRecicleView.getAdapter ().notifyDataSetChanged ();
mRecicleView.scheduleLayoutAnimation ();
}
}
You are trying to access view elements before it's being created.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate (R.layout.dashboard_device_layout, container, false);
ArrayList<String> lista_show = new ArrayList<String> ();
dashboard_DB db1 = new dashboard_DB (getContext ());
//recupero datbase DB
db1.open();
Cursor c = db1.ottieniTuttidati();
if (c.moveToFirst()) {
do {
lista_show.add (c.getString(2));
} while (c.moveToNext());
}
db1.close();
//fine recupero dati da db
// Inflate the layout for this fragment
mRecicleView1=fragmentView.findViewById (R.id.Reclycler_dashboard);
mRecicleView1.setHasFixedSize (true);
mLayoutManager1 = new GridLayoutManager (getContext (),3);
mAdapter1 = new adapter_dash (lista_show,getContext ());
mRecicleView1.setLayoutManager (mLayoutManager1);
mRecicleView1.setAdapter (mAdapter1);
runanimation1(mRecicleView1,0);
Log.d("tag", String.valueOf (lista_show));
return fragmentView;
}
More over you should not do db operation in OnCreateView as its creates blanks screen effect as you will be returning view after querying the db.
Related
I want to pass data from Activity to Fragment using Bundle (I used Bundle to passing data between 2 Fragment, and that's worked).
In my Activity I have a ListView, in the OnItemClickListener I want to open a new Fragment, and the Item, which clicked pass through the Activity to this Fragment. But the Item is null, so basically nothing is send to the Fragment.
Here is my Activity:
public class Jegyek extends AppCompatActivity {
View v;
DB mydb;
ListView listView;
private String teszt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jegyek);
listView = (ListView)findViewById(R.id.jegyekLista);
mydb = new DB(this);
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(this, "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
bundle.putString("Tantárgy neve", teszt);
Toast.makeText(Jegyek.this, teszt, Toast.LENGTH_SHORT).show();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, jegyekAllando);
ListView listaNezet = (ListView) findViewById(R.id.jegyekLista);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
);
}
}
public String getTanNev () {
System.out.println("WARNING: "+ teszt);
return teszt;
}
}
And my Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = new Bundle();
String tanNev = bundle.getStrin
g("Tantárgy neve");
Jegyek jegyAct = new Jegyek();
String tanNevv = jegyAct.getTanNev();
mydb = new DB(getActivity());
String jegyAtlag =String.valueOf(mydb.JegyekAtlaga(tanNev));
String jegyDarab =String.valueOf(mydb.JegyekDarabszama(tanNev));
return rootView;
}
}
When I realized, that the bundle is null, I try to pass that List Item through getter, so I changed my Fragment code for that:
Jegyek jegyek = new Jegyek();
String jegy = jegyek.getTanNev();
But that's not solved my problem, so I back to the Bundle, which also have some problem, but I can't find it. Intresting, that in the OnItemClickListener when I Toast the Item it's correct and works, but when I want to display in the console or pass to the Fragment, the value's is null.
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Hope this helps
Please follow this example:
In your activity, Pass data like
Bundle bundle = new Bundle();
bundle.putString("test", "Test Data");
// set in your testFragment Arguments
TestFragment testFragment = new TestFragment();
testFragment.setArguments(bundle);
And Receive Data from your TestFragment Like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String text = getArguments().getString("test");
return inflater.inflate(R.layout.fragment, container, false);
}
In fragment "jegyekAllando" you must get your string from onCreate() with Bundle data = getArguments(), but you create new bundle.
I have 3 ListViews in one layout but in 3 different fragments. I want, when i scroll down, to first load the first listview and the other two listviews to scroll background at same the time when 1 change fragment same position
display at 2nd and 3rd fragment i loaded listview from database.
Pic of 1st fragment
//first fragment code
public class Quran extends Fragment {
ListView quranlst;
Parcelable state;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_quran, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
quranlst = (ListView) getActivity().findViewById(R.id.quranlist);
DatabaseAccess db = DatabaseAccess.getInstance(getActivity().getApplicationContext());
Intent it = getActivity().getIntent();
int p = it.getIntExtra("paya", 0);
int i = it.getIntExtra("saya", 0);
if (i != 0) {
List<String> lstsa;
db.open();
lstsa = db.getsaya(i);
db.close();
MyCustomAdapter adapter = new MyCustomAdapter(lstsa, Quran.this.getActivity());
quranlst.setAdapter(adapter);
} else if (p != 0) {
List<String> lstpa;
db.open();
lstpa = db.getpaya(p);
db.close();
MyCustomAdapter adapter = new MyCustomAdapter(lstpa, Quran.this.getActivity());
//handle listview and assign adapter
quranlst.setAdapter(adapter);
}
}
}
pic of Second fragment
that is my 2nd fragment code
public class englisht extends Fragment {
ListView el;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_englisht, container, false);}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
el = (ListView) view.findViewById(R.id.englishlst);
DatabaseAccess db = DatabaseAccess.getInstance(getActivity().getApplicationContext());
Intent it = getActivity().getIntent();
int i = it.getIntExtra("saya", 0);
int p = it.getIntExtra("paya", 0);
if (i != 0) {
List<String> lstenglishsurah;
db.open();
lstenglishsurah = db.geteaya(i);
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.mytextview, lstenglishsurah);
el.setAdapter(adapter);
} else if (p != 0) {
List<String> lstenglishparah;
db.open();
lstenglishparah = db.paraheng(p);
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.mytextview, lstenglishparah);
el.setAdapter(adapter);
}
}
}
**that is my third fragment code**
public class urdut extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.activity_urdut, container, false);}
ListView urdulst;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
urdulst = (ListView) view.findViewById(R.id.urdulst);
DatabaseAccess db = DatabaseAccess.getInstance(getActivity().getApplicationContext());
Intent it = getActivity().getIntent();
//SurahAyat
int i = it.getIntExtra("saya", 0);
int p = it.getIntExtra("paya", 0);
if (i!=0) {
List<String> lsturdusurah;
db.open();
lsturdusurah = db.getuaya(i);
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.mytextview, lsturdusurah);
urdulst.setAdapter(adapter);
}
else if (p!=0) {
List<String> lsturduparah;
db.open();
lsturduparah = db.parahurdu(p);
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.mytextview, lsturduparah);
urdulst.setAdapter(adapter);
}
}
}
First get scroll position of the list view using this code
View c = listview.getChildAt(0);
int no= -c.getTop() + listview.getFirstVisiblePosition() * c.getHeight();
and then set listview scroll position to other fragment
getListView().setSelection(no);
no is : like 1,2,3....
You can use the methods smoothScrollToPosition and smoothScrollToPositionFromTop to scroll list(other lists) with respect to first list to which you are scrolling
I have a function in a fragment (Frag_Lista) that changes its cardView dynamically using the output of a query.
The first time i call it from that fragment and it works. The second time i would call it from the main activity, but i can't set correctly the second parameter, the view.
Frag_Lista
public void function_in_fragment() {
//some code
Context context = getActivity();
DBhelper database = ((MainActivity)getActivity()).getDatabase();
Cursor cursor=database.ottieni_tutto();
genera_lista(cursor,getView());
}
public void genera_lista(Cursor cursor, View v) {
list.clear();
if(cursor!=null) {
if(cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
//Log.d(TAG,cursor.getString(cursor.getColumnIndex(DBhelper.COL_NOME)));
String nome = cursor.getString(cursor.getColumnIndex(DBhelper.COL_NOME));
String tipo = cursor.getString(cursor.getColumnIndex(DBhelper.COL_TIPO));
String difficolta = cursor.getString(cursor.getColumnIndex(DBhelper.COL_DIFFICOLTA));
String immagine = cursor.getString(cursor.getColumnIndex(DBhelper.COL_IMMAGINE));
Food_Card food_card = new Food_Card(immagine, nome, tipo, difficolta);
list.add(food_card);
cursor.moveToNext();
}
cursor.close();
}
else Log.d(TAG,"Cursor vuoto");
}
else Log.d(TAG,"Cursor nullo");
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter=new food_adapter(getActivity(),list);
recyclerView.setAdapter(adapter);
}
MainActivity
public void function_in_mainActivity(String[] parametri) {
Cursor cursor=database.query_filtri(parametri);
Frag_Lista nothing=new Frag_Lista();
View v= ?
nothing.genera_lista(cursor,v);
}
How can i pass correctly the current view?
Frag_Lista
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_lista, container, false);
setHasOptionsMenu(true);
return(v);
}
Change your onCreateView like this
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_lista, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
setHasOptionsMenu(true);
return(v);
}
Crate a field inside your Fragment for recyclerView.
Now you always have a reference to the RecyclerView and don't need to pass it as a argument to the method.
public void genera_lista(Cursor cursor)
I'm trying to display data from SQLite and display it in the listview in fragment.This is my code and when I run it, it closes automatically. This code is inside my main activity
public static class ListDoctorFragment extends Fragment {
ListView list;
DataDB data = new DataDB();
ArrayAdapter<String> listAdapter;
public ListDoctorFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.listdoctor, container, false);
ArrayList<String> names = new ArrayList<String>();
try {
names = data.getDoctorlistDB(getActivity());
} catch (SQLException e) {
e.printStackTrace();
}
listAdapter = new ArrayAdapter<String>(getActivity(), R.layout.support_simple_spinner_dropdown_item, names);
// set the adapter
list.setAdapter(listAdapter);
return view;
}
}
Your 'ListView list' is not initialized. It must be something like:
list = (ListView) view.findViewById(R.id.listview);
I am working on an appication that will show a gridView table that will be generated from a SQLite query on an ActionBar tab. I am very close to getting it, however am stuck on configuring the adapter. I would appreciate suggestions regarding this. TIA.
public class DataTable extends Fragment {
SQLiteDatabase db;
private DataTable adapter;
private int columnWidth;//added 3/25
ArrayList<String> surveyData = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
DBAdapter msdb= new DBAdapter(getActivity().getApplicationContext(),"adfg", null);
//db=msdb.getWritableDatabase();
View view = inflater.inflate(R.layout.datatable, container, false);
Cursor c = db.rawQuery("SELECT * FROM surveyDB",null);
c.moveToFirst();
while(!c.isAfterLast()){
String path = c.getString(c.getColumnIndex("P_path"));
surveyData.add(path);
c.moveToNext();
}
db.close();
GridView gridView = (GridView) view.findViewById(R.id.grid);
/*problem adapter = new DataTable(DataTable.this, surveyData, columnWidth);
gridView.setAdapter(adapter); */
return view;
}
This works.
public class DataTable extends Fragment {
SQLiteDatabase db;
ArrayList<String> arrCursor = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.datatable, container, false);
GridView gridView = (GridView) view.findViewById(R.id.grid);
DBAdapter msdb= new DBAdapter(getActivity().getApplicationContext(),"adfg", null);
db=msdb.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM surveyDB",null);
c.moveToFirst();
arrCursor.clear();
while(!c.isAfterLast()){
String _id = c.getString(c.getColumnIndex("_id"));
arrCursor.add(_id);
String species = c.getString(c.getColumnIndex("species"));
arrCursor.add(species);
String area = c.getString(c.getColumnIndex("area"));
arrCursor.add(area);
String sampler = c.getString(c.getColumnIndex("sampler"));
arrCursor.add(sampler);
c.moveToNext();
}
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, arrCursor);
gridView.setAdapter(arrayAdapter);
return view;
}
}