Cannot resolve 'findViewById' method in Fragment RecyclerView - java

I'm new to android studio, I was trying to create RecyclerView on Fragment. I was following a tutorial but I still get message ' Cannot resolve 'findViewById'
I've tried doing:
RecyclerView recyclerView = (RecyclerView)getView().findViewById(R.id.recyclerView);
But ended up receiving error:
Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
Here is the code:
package com.example.app;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Articles extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NewsList[] myListData = new NewsList[] {
new NewsList("Article 1", "Some Author"),
new NewsList("Article2", "Some Author"),
new NewsList("Article3", "Some Author"),
};
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
NewsAdapter adapter = new NewsAdapter(myListData);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_create, container, false);
}
}
How can I resolve this issue?

Add these variables:
View root;
RecyclerView recyclerView;
Change your onCreateView to this:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_profile, container, false);
recyclerView = root.findViewById(R.id.recyclerView);
return root;
}
and lastly - make sure that your recyclerview within your XML file has the following:
android:id="#+id/recyclerView"

Your view is not yet inflated which is the reason it cannot be found. Move your code from onCreate to onViewCreated fragment lifecycle.
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// your view is discoverable here
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
}

For your example, your List (myListDatae) must be inside the NewsAdapter class as a field variable.

Related

controlling a button in a fragment [duplicate]

This question already has answers here:
How to set onclick listener for a button in a fragment in android
(3 answers)
Closed 4 years ago.
I want to control button from fragment xml file in the fragment activity. In other activity we can easily control our button by findviewbyid method and after that we can apply setonclicklistener. But here in fragment how do i access the button and apply onclicklistener method.
My Fragment.java
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.Button;
import android.widget.LinearLayout;
/**
* A simple {#link Fragment} subclass.
*/
public class QuoteTypeFragment extends Fragment {
public QuoteTypeFragment() {
// Required empty public constructor
}
LinearLayout typeOne, typeTwo, typeThree, typeFour;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
return vv;
}
}
My Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#3f525e"
tools:context=".QuoteTypeFragment">
<Button
android:id="#+id/submitbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"/>
</FrameLayout>
So here I want to control the submit button in fragment.java. How can I acces the button by findviewbyid or findfragmentbyid. And in fragment.java where do I use that code to access submitbutton.
in OnCreateView
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.findViewById(R.id.submitbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return vv;
}
In your QuoteTypeFragment.java
1) Cast the widget by using the view. (view.findViewById()).
2) Set the onClickistener.
3) Implement View.OnClickListener and the onClick method.
public class QuoteTypeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
Button mSubmitButton = vv.findViewById(R.id.submitbutton);
mSubmitButton.setonClickListener(this);
return vv;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submitbutton:
// Control the button
break;
}
}
It is very easy to control button from fragment XML file in the fragment activity.
In your onCreateView use these lines,
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.view.findViewById(R.id.submitbutton);
return vv;
}

null point exception when trying to fetch data from openweathermap [duplicate]

This question already has answers here:
getView returning null when fragment has been created from an activity
(6 answers)
Closed 5 years ago.
I am trying to get sunrise and sunset time for my current location from openweathermap api. I am following this tutorial.
I have copied the entire Function.java in the tutorial and trying to use the data to update my ViewPagerAdapter's Fragment.
import android.os.Bundle;
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;
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
TextView cityField = getView().findViewById(R.id.tv_city);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
rv.setNestedScrollingEnabled(true);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
}
});
asyncTask.execute("25.180000", "89.530000"); // asyncTask.execute("Latitude", "Longitude")
rv.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"Hello", "World"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
and I have named my target for the city name as tv_city:
<TextView
android:id="#+id/tv_city"
android:layout_toRightOf ="#+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="40sp"
android:text="Hello World"
android:textSize="30sp"
android:layout_marginBottom="5sp"
android:paddingLeft="5sp"
android:gravity="top" >
</TextView>
The problem is, possibly I am making some mistake to fetch the data, as I am getting nul exception error for this line:
TextView cityField = getView().findViewById(R.id.tv_city);
as:
Process: com.example.phocast, PID: 9820 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.phocast.BlankFragment.<init>(BlankFragment.java:17)
WIth my limited knowledge in java, I am unable to solve it.
Kindly help.
Update
actually, writing oncreateview as:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
rv.setNestedScrollingEnabled(true);
Weather_OWM.placeIdTask asyncTask =new Weather_OWM.placeIdTask(new Weather_OWM.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
TextView cityField = rootView.findViewById(R.id.tv_city);
cityField.setText(weather_city);
}
});
solves my problem, but i dont know if this is proper/good way to use final. I will be really grateful if someone shows me the way before closing it.
Your cityView line of code is just hanging out there, not in a method or anything. The NullPointer is coming from getView(). You can't find the view before onCreateView occurs and the inflater does its thing. Move it to onCreateView, anytime after View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
You need initialize the textView after:
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
After initialize the recyclerView you can write this:
cityField = rootView.findViewById(R.id.tv_city);

spinner or loader while fragment page get completedly loaded

I have created an android application using Android Fragments as described in Dynamically Prevent Rotation On Android Fragment.
The application is working fine but the problem is that say a particular fragment say Photo Gallery might calls several http calls and might certain time for bringing all the images. So when we click the Photo Gallery it seems stuck for sometime.
How can we show some slider or progress bar like something till the fragment view get loaded completely?
An example like is as shown below:
My PhotoGalleryFragment is given below
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PhotoGalleryFragment extends Fragment {
public PhotoGalleryFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
// some http calls to be triggered
return rootView;
}
}
You can use ProgressDialog, for example:
public class PhotoGalleryFragment extends Fragment {
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
// some http calls to be triggered
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mProgressDialog = ProgressDialog.show(activity, "", "Loading...", true, false);
}
}
When you http calls are ended you can dismiss the ProgressDialog with mProgressDialog.dismiss().

Error with fragment

I'm currently learning to work with fragments, so far I have been pretty successful, but have come up with the following error:
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: FATAL EXCEPTION: main
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: Process: com.example.wq.myapp, PID: 21831
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: at com.example.wq.myapp.PhoneMessages.onActivityCreated(PhoneMessages.java:44)
If anyone can explain what I'm doing wrong that would be greatly appreciated :)
Here is my fragment code:
package com.example.wq.myapp;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class PhoneMessages extends Fragment {
ListView lvMsgList;
// Cursor Adapter
SimpleCursorAdapter adapter1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone_messages, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://mms-sms/conversations");
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor a = getActivity().getContentResolver().query(inboxURI, new String[]{"*"}, null, null, "normalized_date desc");
// Attach Cursor with adapter and display in listView
adapter1 = new SimpleCursorAdapter(getActivity().getApplicationContext(), R.layout.row, a,
new String[]{"body", "date", "address", "thread_id"},
new int[]{R.id.lblMsg, R.id.lblDate, R.id.lblNumber, R.id.lblID}, 0);
lvMsgList.setAdapter(adapter1);
//set OnItemClickListener for listView, start ConvListActivity
lvMsgList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TVConvID = (TextView) view.findViewById(R.id.lblID);
String ConvID = TVConvID.getText().toString();
Intent i = new Intent(getActivity(), ConvListActivity.class);
i.putExtra("CID", ConvID);
startActivity(i);
}
});
getActivity().setTitle("Phone Messages");
}
}
You never inflated your listview so you are getting a null pointer. Also its better to do this in onCreateView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_phone_messages, container, false);
lvMsgList = (ListView) rootView.findViewById(R.id./*listview*/);
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://mms-sms/conversations");
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor a = getActivity().getContentResolver().query(inboxURI, new String[]{"*"}, null, null, "normalized_date desc");
// Attach Cursor with adapter and display in listView
adapter1 = new SimpleCursorAdapter(getActivity().getApplicationContext(), R.layout.row, a,
new String[]{"body", "date", "address", "thread_id"},
new int[]{R.id.lblMsg, R.id.lblDate, R.id.lblNumber, R.id.lblID}, 0);
lvMsgList.setAdapter(adapter1);
//set OnItemClickListener for listView, start ConvListActivity
lvMsgList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TVConvID = (TextView) view.findViewById(R.id.lblID);
String ConvID = TVConvID.getText().toString();
Intent i = new Intent(getActivity(), ConvListActivity.class);
i.putExtra("CID", ConvID);
startActivity(i);
}
});
getActivity().setTitle("Phone Messages");
return rootView;
}

Fragment and view

My application is divided into fragments, each with its own layout (.xml file).
When I start visualize the first fragment in the onCreate() method of my activity, I set the appropriate layout with setContentView(fragment_first). How do I change, for example, a TextView contained inside the second fragment (fragment_second)?
Generally speaking, a Fragment, or any Activity or View for that matter, should update its own internal UI controls. It's easier, and it's good design. Other classes/events may update the state of the Fragment's data, but it handles how that state is displayed.
Edit to answer commented question:
This is how to load a content view in a Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.pump_info, container, false);
return view;
}
in your onCreateView() method, you should assign all of the views you will need to access later to fields in your fragment class, like this,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
view = inflater.inflate(R.layout.xxx, container, false);
this.aTextView = (TextView)view.findViewById(R.id.a_text_view);
this.anImageView = (ImageView)view.findViewById(R.id.an_image_view);
...
}
you can then use aTextView, etc. at other places in the execution of your fragment.
It seems you set the xml file you intended for your first fragment in your activity.
What you should do in short is create a completely new class and have it extend android.support.v4.app.Fragment, also have your activity extend FragmentActivity instead of just Activity.
Then in your android.support.v4.app.Fragment class (which I shall call your fragment from now on) you should override the onCreateView(LayoutInflater inflate, ViewGroup container, Bundle savedInstanceState){} method and in this method you should put a line like this:
View view = inflater.inflate(R.layout.the_xml_layout_for_this_fragment, container, false); which inflates the layout of the fragment and plants it in the proper place in your activity's layout.
After this your need to return view;, but before you return this view you can do view.findViewById(R.id.id_of_a_view_from_the_xml_layout_file); in order to find an element and manipulate it.
You should create such a fragment class for each fragment you need in your app and have it inflate it's own xml layout file.
For more detailed instructions you can see http://www.youtube.com/watch?v=4BKlST82Dtg or other videos or written tutorials.
EDIT: here is a basic fragment class:
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.TextView;
public class MyFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the view:
View view = inflater.inflate(R.layout.myfrag_layout, container, false);
// manipulate widgets, for example:
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText("read me!!!");
// return the view:
return view;
}
}
and it's parenting activity:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class MyFragmentActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// notice that there is a different layout file for the activity and for
// the fragment!
setContentView(R.layout.xml_layout_for_the_activity);
// to start the fragment and stick it into your activity (not needed if
// you use ViewPager)
FragmentManager fragMan = getSupportFragmentManager();
fragMan.beginTransaction()
.add(R.id.the_visual_element_that_will_contain_your_fragments_layout, fragMan)
.commit();
}
}

Categories