No view found for id in a new activity - java

I have created an activity that I am using for barcode scanning. The onCreate looks like this:
public class GradeScreenScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
public static final int REQUEST_CAMERA = 1;
protected ZXingScannerView scannerView;
protected FirebaseFirestore db;
protected String scanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
db = FirebaseFirestore.getInstance();
}
}
Once I have a result I am then wanting to launch a new fragment like so:
android.app.FragmentManager fragmentManager = getFragmentManager();
ScreenFragment screenFragment = new ScreenFragment();
screenFragment.db = db;
screenFragment.serialNumberScanned = serialNumberScanned;
fragmentManager.beginTransaction()
.addToBackStack("screen")
.replace(R.id.content_frame, screenFragment)
.commit();
But I get the following error that I am not sure how to deal with:
java.lang.IllegalArgumentException: No view found for id 0x7f08005a (uk.wefix:id/content_frame) for fragment ScreenFragment{6262536 #1 id=0x7f08005a}
Just in case, the fragments onCreate looks like this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.grade_screens_layout, container, false);
return myView;
}
Help appreciated.
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_frame"/>
Was missing from the xml in the activity view. My error, well spotted Umair

yes , usually when you get No view found for id or nullPointer i suggest you to check:
1-android:id="#+id/
2- findViewById
3- in the java class the variable declaration
in most cases it works ;)
good luck.

Related

Is there any way to use Fragmentcontainerview inside a ViewPager2?

I have a working "folder explorer" for the internal storage only. But I want to improve that explorer to use internal and external storage. I want something like this:
Bellow is the basic code of my working folder explorer (internal storage only):
select_folders.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
SelectFoldersActiviy.java
public class SelectMusicFolderActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentContainer, FoldersFragment.newInstance(path))
.commit();
}
}
...
}
The following fragment class uses a ListView to list all subfolders for a folder. In the onItemClick() method of the ListView objet I instantiate a new fragment with the current item path as argument. Like so:
FoldersFragment.java
public class FoldersFragment extends Fragment {
...
private static final String RUTA_KEY = "ruta";
private final String PATH = "ruta";
public static FoldersFragment newInstance(String ruta) {
FoldersFragment fragment = new FoldersFragment();
Bundle args = new Bundle();
args.putString(RUTA_KEY, ruta);
fragment.setArguments(args);
return fragment;
}
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
ruta = getArguments().getString(RUTA_KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentContainer,
FoldersFragment.newInstance(currentItemPath))
.addToBackStack(null)
.commit();
}
}
}
With what I can combine the viewpager2 to get the aproach of the image?
I tried with fragmentcontainerview inside viewpager2, but viewpager2 dont support direct childs.
I tried with NavHostFragment too, but that needs a predefined navigation graph, and the number of folders is undetermined.

null object reference of TextView in Fragment

I have two fragments and a main activity. The first fragment, FriendsFragment (extends ListFragment) is displayed on the screen and when the user clicks an item, the main Activity replaces the FriendsFragment with FeedFragment, then calls a method from FeedFragment to update the textView.
I'm getting an error that the textView object in the FeedFragment class is null even though I instantiate using the findViewById method.
I have looked at related questions and have tried the solutions but nothing is working. I've tried doing getView().findViewById(R.id.feed_view), getActivity().findViewById(R.id.feed_view), and I've tried putting these in onActivityCreated() and onCreateView()
The only thing that worked is writing this code in onActivityCreated():
text = getView().findViewById(R.id.feed_view);
text.setText("some string");
but this is not what I want
FeedFragments.java
public class FeedFragment extends Fragment {
private static String TAG = "Feed Fragment";
private TextView text;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "Entered FeedFragment.java onActivityCreated()");
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.i(TAG, "Entered FeedFragment.java onCreateView()");
View v = inflater.inflate(R.layout.fragment_feed, container,false);;
text = v.findViewById(R.id.feed_view);
return v;
}
public void updateDisplay(int position)
{
Log.i(TAG, "FeedFragment.java: updateDisplay()");
text.setText(position);
}
MainActivity.java
// previously declared feedFragment: feedFragment = new FeedFragment();
public void onItemSelected(int position)
{
Log.i(TAG, "Entered onItemSelected(" + position + ")");
fragManager = getFragmentManager();
FragmentTransaction fragTransaction = fragManager.beginTransaction();
fragTransaction.replace(R.id.fragment_container, feedFragment, "feed_fragment");
fragTransaction.addToBackStack(null);
fragTransaction.commit();
feedFragment.updateDisplay(position);
}
fragment_feed.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/feed_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/greeting" />
</ScrollView>
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
onViewcreated() is being called after updateDisplay() because the system doesn't run it right away.
you need to pass a value to the feedFragment on it's creation and store it in a bundle and retrieve it after the fragment internal code is run by the system.
the way you solve it is like this:
when you instantiate feedFragment you do it like this:
feedFragment = FeedFragment.newInstance(position)
and inside FeedFragment class you should have a static code:
private static final String ARG_PARAM1 = "param1";
public static FeedFragment newInstance(int param1) {
FeedFragment fragment = new FeedFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
and non static code:
private int mParam1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.i(TAG, "Entered FeedFragment.java onCreateView()");
View v = inflater.inflate(R.layout.fragment_feed, container,false);;
text = v.findViewById(R.id.feed_view);
text.setText(String.valueOf(mParam1));
return v;
}
I wrapped mParam1 in String.valueOf() because when you pass integer to setText it thinks you try to use a Strings.xml resource instead of the number you chose.
also I used very generic variable names. please change them to something meaningful so that your code makes sense.

onCreateView() method asking for super class call

I have extended fragmentActivity class , as far as I read onCreateView is available in lifecycle of fragmentActivity but its not supposed to be calling super class , but its giving me error in #override asking me to call super class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList<>();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override --> error Here
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_maps,
container, false);
Button button = (Button) view.findViewById(R.id.reportButton);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),"Report Button Works",Toast.LENGTH_SHORT).show();
}
});
return view;
}
#Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
return super.onCreateView(parent, name, context, attrs);
}
Not
#Override --> error Here
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
You need you Fragments;
Step 1 - You need create one Fragment.
public class ExampleFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
//Create the view from XML layout.
final View view = inflater.inflate(R.layout.fragment_example, null);
//Perform additional configuration on layout components here.
return view;
}
}
Step 2 - Create Fragment:
public class Fragment1 extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.YOUR_LAYOUT, container, false);
}}
Step 3 - Create FragmentPagerAdapter
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentList;
private Fragment1 fragment1;
public PagerAdapter(FragmentManager fm) {
super(fm);
this.fragment1 = new Fragment1();
this.fragmentList = new ArrayList<>();
this.fragmentList.add(this.fragment1);
}
#Override
public Fragment getItem(int position) {
//Get fragment in list position
return fragmentList.get(position);
}
#Override
public int getCount() {
//return size of fragments list.
return fragmentList.size();
}}
Step 4 - Add FragmentPagerAdapter in your FragmentActivity:
this._viewPager.setAdapter(new PagerAdapter(this.getSupportFragmentManager()))
FragmentActivity doesn't actually have a method called onCreateView(LayoutInflater, ViewGroup, Bundle), I think you're confusing it with Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) for which the default implementation only returns null in which case you don't actually need to call the super method.
FragmentActivity can act as a host for Fragments provided by the support library (regular Activity can only host android.app.Fragment). In your code you're using the SupportMapFragment which extends Fragment and overrides Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) to provide its view to the hosting Activity.
For an Activity, you'd typically just set your button click listeners in onCreate after calling setContentView.
You should try overriding onCreate and changing it from protected to public.
Plus, either get rid of setContentView(R.layout.activity_maps); or change it to getActivity().setContentView(R.layout.about_main_layout);
setContentView isn't availible only in a fragment Activity's java it must have getActivity(). in front of it.
Also, you need a blank public constructor, it's required, public BlankFragment() {
// Required empty public constructor
}
Finally, to my knowledge onCreateView is fine, it's what's around it, so please consider the above posibilites.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.about_main_layout);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList<>();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); }
FragmentActivity is used to hold a Fragment prior to API 3.0. If you're targeting an app prior to Honeycomb then you should use FragmentActivity but if you're targeting an app after Honeycomb then you should use an Activity. And remember that the FragmentActivity holds a Fragment, which means that you should attach a Fragment and call OnCreateView() and other fragment methods on the Fragment and not on FragmentActivity.
The way to attach a Fragment to FragmentActivity is
android.support.v4.app.FragmentManager fm = myFragmentActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(CONTENT_VIEW_ID, myFragment).commit();
Check out this excellent SO post explaining the difference between FragmentActivity and Fragments
Difference between Fragment And FragmentActivity

NullPointerException using fragment transactions [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm starting with android and just getting crazy with the implements of multiple fragments.
I have two fragments in my MainActivity: QuestionDetail and QuestionListFragment.
When I use a fragment transactions to replace the QuestionDetail fragment when someone click in one of the QuestionListFragment options I get a NullPointerException error.
I have been trying to fix this issue for hours. Any help is greatly appreciated.
QuestionDetail
public class QuestionListFragment extends Fragment{
private RecyclerView recView;
public static QuestionAdapter adapter;
private QuestionListener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_question_list, container, false);
recView = (RecyclerView) v.findViewById(R.id.recView);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recView.setLayoutManager(layoutManager);
adapter = new QuestionAdapter(QuestionCatalog.getQuestionCatalog().getQuestionList().getList());
adapter.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (listener!=null) {
listener.onQuestionListener(adapter.getItem(recView.getChildAdapterPosition(v)));
}
}
});
recView.setAdapter(adapter);
}
public interface QuestionListener {
void onQuestionListener(Question q);
}
public void setQuestionListener(QuestionListener listener) {
this.listener=listener;
}
QuestionDetail
public class QuestionDetail extends Fragment {
// We use an ID to know which Question we're using
private long questionId;
public QuestionDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_question_detail, container, false);
}
#Override
public void onStart() {
super.onStart();
//Fragments don’t include findViewById(). To get a reference to a view, we use getView()
View view = getView();
if (view != null) {
TextView title = (TextView) view.findViewById(R.id.textQuestion);
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
title.setText(question.getName());
TextView kind = (TextView) view.findViewById(R.id.textKind);
kind.setText(question.getKind());
}
}
public void showDetails(String texto) {
TextView txtName = (TextView)getView().findViewById(R.id.textQuestion);
TextView txtKind = (TextView)getView().findViewById(R.id.textKind);
txtName.setText(texto);
txtKind.setText(texto);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements QuestionListFragment.QuestionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuestionListFragment frg =(QuestionListFragment)getFragmentManager().findFragmentById(R.id.listFragment);
frg.setQuestionListener(this);
}
#Override
public void onQuestionListener(Question q) {
Toast.makeText(this, "num: " + q.getName(),
Toast.LENGTH_LONG).show();
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
QuestionDetail f1 = new QuestionDetail();
f1.showDetails(q.getName());
t.replace(R.id.detailFragment,f1);
t.addToBackStack(null);
t.commit();
}
stacktrace
08-04 09:54:11.914 22277-22277/com.hfad.predictandwin E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.hfad.predictandwin.Fragments.QuestionDetail.showDetails(QuestionDetail.java:50)
at com.hfad.predictandwin.MainActivity.onQuestionListener(MainActivity.java:34)
at com.hfad.predictandwin.Fragments.QuestionListFragment$1.onClick(QuestionListFragment.java:55)
at com.hfad.predictandwin.QuestionAdapter.onClick(QuestionAdapter.java:61)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18786)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
First, don't use getView() in onStart() - You shouldn't have a view to get at that point. Second, you shouldn't be calling methods directly on the Fragment instances from elsewhere, in your case f1.showDetails(q.getName());. There, again, the Fragment has no View. Please see Best practice for instantiating a new Android Fragment for how to pass arguments into Fragment before you load it into the FragmentManager.
Next point - you should initialize your views using findViewById inside of onCreateView just like you did for the other Fragment class. For example,
private TextView txtName, txtKind;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_question_detail, container, false);
txtName = (TextView) rootView.findViewById(R.id.textQuestion);
txtKind = (TextView) rootView.findViewById(R.id.textKind);
// TODO: Read the link how to use these
Bundle arguments = getArguments();
Question question = QuestionCatalog.getQuestionCatalog()
.getQuestionList().getList().get((int) questionId);
showQuestion(question);
return view;
}
private void showQuestion(Question q) {
txtName.setText(q.getName());
txtKind.setText(q.getKind());
}
in QuestionListFragment:
We set click listener for recView, not adapter. You should replace adapter.setOnClickListener with
recView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recView, new ClickListener() {
#Override
public void onClick(View view, int position) {
// do something with position.
}
#Override
public void onLongClick(View view, int position) {
}
}));
in QuestionDetail:
questionId wasn't initialized but you have use it in this line:
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
Based on stacktrace and your code (not sure which one is line #50 in your QuestionDetail) ether txtName or txtKind evaluates to null (maybe both), so for whatever reason getView().findViewById(R.id.textQuestion) returns null. Probably because getView() in that call doesn't get you a parent view of the TextView in question

Android - where to put onClick on linearlayout of a fragment

Obviously, I am new to Android - XML programming... So I have a navigation drawer, and once item is selected from the drawer, a corresponding fragment on the right side will display. Inside that fragment, I have linear layouts. I'd like to get redirected to another activity once that linear layout has been tapped. I was able to make it work on activities, by using android:onClick on XML file, but can't make it work on fragment. Somebody help me please.
App interface, refer to this image:
http://i.stack.imgur.com/u6dHi.jpg
Code:
fragment_smart.xml - the display once item's selected. I am trying to use the onClick on xml.
<LinearLayout
android:id="#+id/linearLayoutsmart1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="#+id/smart_title"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:weightSum="1"
android:onClick="smart_recommended_link">
Here's my Java code:
public class FragmentSmart extends Fragment {
public static final String TAG = "stats";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
return myfragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(this, SmartRecommended.class);
startActivity(smartRecommendedIntent);
}
}
The app is crashing when I clicked on the linearlayout using this code. What's the best thing to do here? Thank you!
For fragments you need to add the listener programmatically:
public class MyFragment extends Fragment implements View.OnClickListener {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.my_layout).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Handle click based on v.getId()
}
}
First of all, linear layouts cant trigger onClick events by default.
Check this answer for more information: LinearLayout onClick.
You can get the LinearLayout from the view in your onCreateView() like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
LinearLayout layout = (LinearLayout)myFragment.findViewById(R.id.linearLayoutsmart1);
// here you can set a listener of any type you want to the layout
return myfragment;
}
In fragments, you must use getActivity() method instead of this to reference the activity that the fragment is attached to.
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(getActivity(), SmartRecommended.class);
startActivity(smartRecommendedIntent);
}

Categories