This question already has answers here:
I get the error "Unreachable statement" return in android
(3 answers)
Closed 3 years ago.
I have this code, which integrates a RecyclerView within a Fragment, but this line:
mRecyclerView = (RecyclerView) mRecyclerView.findViewById(R.id.list_data);
Gives me an error, it tells me that:
Unreachable statement
And I don't know why, any idea?
Here's the code I'm using:
public class KecamatanFragment extends Fragment {
private static final String data_url = "http://xxxxxxxxxx/daftar/get_kecamatan.php"; // kasih link prosesnya
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mManager;
ProgressDialog pd;
ArrayList<ModelData> mItems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_kecamatan, container, false);
mRecyclerView = (RecyclerView) mRecyclerView.findViewById(R.id.list_data); <-- Unreachable statement
mItems = new ArrayList<>();
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
mAdapter = new AdapterProcess(KecamatanFragment.this, mItems);
mRecyclerView.setAdapter(mAdapter);
loadjson();
}
enter code here
//proses mengambil data
private void loadjson(){
pd.setMessage("Mengambil Data");
pd.setCancelable(false);
pd.show();
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, data_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pd.cancel();
Log.d("volley", "response : " + response.toString());
for (int i=0; i < response.length(); i++){
try {
JSONObject data = response.getJSONObject(i);
ModelData md = new ModelData();
md.setKecamatan(data.getString("kecamatan")); // memanggil nama array yang kita buat
mItems.add(md);
} catch (JSONException e) {
e.printStackTrace();
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Log.d("volley", "error : " + error.getMessage());
}
});
Controller.getInstance().addToRequestQueue(arrayRequest);
}
}
Unreachable statement
That's expected error, because you're stopping the onCreateView method after you're giving it a return statement:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// You've already close the method when you're giving a return
return inflater.inflate(R.layout.fragment_kecamatan, container, false);
// so this won't be reachable, hence the unreachable error raised.
mRecyclerView = (RecyclerView) mRecyclerView.findViewById(R.id.list_data);
...
}
So, you either need to inflate the Layout first and bind the view then return the inflated view or move the view binding after the return statement to another method.
As mentioned by ישו אוהב אותך, You're returning the inflated view immediately. keep a reference to the inflated view and return it at the end. Also, you probably want to use findViewById on the inflated view and not on mRecyclerView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_kecamatan, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.list_data);
mItems = new ArrayList<>();
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
mAdapter = new AdapterProcess(KecamatanFragment.this, mItems);
mRecyclerView.setAdapter(mAdapter);
loadjson();
return view;
}
Related
I'm trying to add recyclerview in my fragment but I'm getting error when I click on navigation drawer item.
Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.myapplication.fragment.Books.onCreate(Books.java:45)
How to resolve error or suggest tutorial to load json data in fragment using recyclerview. with click event on recyclerview. on click item open new fragment with data.
This is my code
public class Books extends Fragment {
private BooksModel booksViewModel;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<BooksModel> bookLists;
// Context context;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recyclerView = (RecyclerView) getView().findViewById(R.id.recyclerViewBook); //Line 45 Error
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
bookLists = new ArrayList<>();
for(int i=0; i<=10; i++){
BooksModel bookList = new BooksModel(
"",
"Title " + (i + 1),
"This is Auther"
);
bookLists.add(bookList);
adapter = new BooksAdapter(bookLists,this);
recyclerView.setAdapter(adapter);
}
}
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
booksViewModel =
new ViewModelProvider(this).get(BooksModel.class);
View root = inflater.inflate(R.layout.fragment_books, container, false);
final TextView textView = root.findViewById(R.id.text_book );
booksViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
onCreate() runs before onCreateView(). You should move all of that code to onViewCreated(), which passes you the View directly (meaning you don't have to call getView() at all).
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.
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 have a problem with my RecyclerView. I m trying to populate it with a list of friends names, however when i launch my fragment friends are not loaded. On the other side friends are loaded if i m entering debug mode.
My code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mKinveyClient = KinveyUtils.getClient(getContext());
mFriends = getUserFriends();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_friend_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
mRecyclerView = (RecyclerView) view;
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mRecyclerView.setAdapter(new FriendRecyclerViewAdapter(mFriends));
}
return view;
}
private ArrayList<ArrayMap> getUserFriends() {
return (ArrayList<ArrayMap>) mKinveyClient.user().get(KinveyConstants.FRIENDS);
}
I feel like the friends are loading too slow, but all the needed data should be already in app by this time. Any idea how to fix it?
I am getting some news data from my CMS,and want to display them in a RecyclerView.The problem is that I am getting a null pointer exception in the line where I using the LinearLayoutManager. Here is the logcat output.
Caused by: java.lang.NullPointerException
at testing.theo.manchesterunitedapp.newsandfeatures.FeaturesFragment.onCreateView(FeaturesFragment.java:65)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
at android.app.Activity.performStart(Activity.java:5241)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
The Fragment where I am doing the webservice part is quite simple. I use to callback methods. The onCreateView where I am initialising the ArrayList and the RecyclerView,and secondly the onActivityCreate where I am running the webservice.
public class FeaturesFragment extends Fragment {
public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "xxxxxxxxxxxx/xxxx/features_images/" ;
private List<FeaturesObject> listItemsList;
private RecyclerView mRecyclerView;
private FeaturesAdapter adapter;
public FeaturesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.features_row, container, false);
// Inflate the layout for this fragment
listItemsList = new ArrayList<>();
mRecyclerView = (RecyclerView)v.findViewById(R.id.features_recycler_view);
//mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateFeaturesList();
}
public void updateFeaturesList() {
//declare the adapter and attach it to the recyclerview
adapter = new FeaturesAdapter(getActivity(), listItemsList);
mRecyclerView.setAdapter(adapter);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Request a string response from the provided URL.
JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FEATURES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
//hidePD();
// Parse json data.
// Declare the json objects that we need and then for loop through the children array.
// Do the json parse in a try catch block to catch the exceptions
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = response.getJSONObject(i);
FeaturesObject item = new FeaturesObject();
item.setTitle(post.getString("title"));
item.setImage(IMAGE_URL + post.getString("features_image"));
item.setArticle(post.getString("article"));
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Update list by notifying the adapter of changes
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//hidePD();
}
});
jsObjRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
queue.add(jsObjRequest);
}
}
This part of the code causes the problem.
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
This is strange,as I am using the same techiques to obtain data in another fragment of my app.
Any ideas?
Thanks.
Your RecyclerView is null. Are you sure you're looking for the correct id in the correct layout file? My guess is either you are inflating the incorrect layout file, or you're looking for the incorrect view id for the RecyclerView.
Probably this is not the case but... As a general rule all initialization that need instance of the activity must be in onActivityCreated() (or the next methods in the Fragment lifecycle). Inside onCreateView() getActivity() is not guaranteed to return non-null value. In some scenarios it returns null.
Seems like the id that you are trying to find it's not on features_row that's why you get NullPointerException on that line :
mRecyclerView = (RecyclerView)v.findViewById(R.id.features_recycler_view);
If you keep getting error you could try this :
final FragmentActivity c = getActivity();
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(c);
mRecyclerView.setLayoutManager(linearLayoutManager );