spinner1 cannot be resolved or is not a field - java

I am not able to understand why i am getting an error here.The error is spinner1 cannot be resolved.Plz help me out fast.I am new to java and android development so explain accordingly.
This is my java code
package com.example.dailyexpenses;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class GamesFragment extends Fragment {
String[] Languages = { "Select a Language", "C# Language", "HTML Language",
"XML Language", "PHP Language" };
// Declaring the Integer Array with resourse Id's of Images for the Spinners
Integer[] images = { 0, R.drawable.icon, R.drawable.petrol,
R.drawable.books, R.drawable.recharge};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_games, container, false);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
return rootView;
}
}
This is fragment_games.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="choose from the categories below"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:drawSelectorOnTop="true"
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="#string/select">
</Spinner>
</RelativeLayout>

You need to call
rootView.findViewById
since android does not yet to know where to search.
For more explanation:
Probably (not to judge ofc) you are familiar to call findViewById in the method onCreate of an Activity, but before that you did call setContentView. After setting the content by setContentView android knows where to search for the id when you call findViewById. That is for the case when you are using activity. On the other hand, with fragments it is a different case. You won't be setting the content by setContentView, instead you have to prepare a view and return it on onCreateView and let the android set the content as it wishes. Be careful, on lines you are calling findViewById above there, you haven't return the view yet, so android does not know where to search as you call findViewById. So you have to make your searches not on not-set-yet-content, but on the rootView you are just about to return. So above the code is the solution to this well described problem.

Related

How to change multiple fragments by clicking on a single button in android?

Greeting!
I’m practicing on fragments topic. My main issue is how to change multiple fragments by clicking a single button “NEXT” or “PREVIOUS” as you may know some apps or books change pages by clicking on the next or previous buttons. If there are only two are four fragments then no issue to add buttons but what if there are multiple fragments like 50 or 100? First I try to find solutions from Google and YouTube but I find that we can change pictures through this method. Is it possible that we can change fragments through this method or not if possible so please some articles with the same solutions to share your experience? Or I should need to use images to do this. My main activity java code and XML code are below and the first fragment and code other three fragments are also the same.
// Main_Activity.java
package com.test.fragment_practice;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.test.fragment_practice.Fragments.FirstFragment;
import com.test.fragment_practice.Fragments.ForthFragment;
import com.test.fragment_practice.Fragments.SecondFragment;
import com.test.fragment_practice.Fragments.ThirdFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
LinearLayout layout;
Button btn1,btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.linearLayout2);
btn1 = (Button) findViewById(R.id.btnpre);
btn2 = (Button) findViewById(R.id.btnnxt);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirstFragment fragment = new FirstFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.linearLayout2, fragment);
fragmentTransaction.commit();
}
});
btn2.setOnClickListener((view) ->{
SecondFragment fragment2 = new SecondFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.linearLayout2, fragment2);
fragmentTransaction.commit();
});
}
}
//activity_main.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF3700B3"
android:orientation="horizontal">
<Button
android:id="#+id/btnpre"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:backgroundTint="#FF0000"
android:text="Previous"
android:textColor="#6900FF"
android:textSize="24sp" />
<Button
android:id="#+id/btnnxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:backgroundTint="#FFFF00"
android:text="Next"
android:textColor="#6900FF"
android:textSize="24sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
</LinearLayout>
// First_Fragment.java
package com.test.fragment_practice.Fragments;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.test.fragment_practice.R;
import com.test.fragment_practice.SecondActivity;
public class FirstFragment extends Fragment {
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_first, container, false);
}
}

Retaining Fragment Data

Following my previous post where I asked about implementing parceable objects, the solution I got was to use setRetainInstance(true); method.
#CommonsWare provided me a sample which I modified as follows:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="387dp"
android:layout_height="103dp"
android:text="New Text"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
RotationFragmentDemo.java
package com.rotationfragment;
import android.app.Activity;
import android.os.Bundle;
public class RotationFragmentDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This check returns 'null' for the first time when there are no fragments
if (getFragmentManager().findFragmentById(android.R.id.content) == null) {
getFragmentManager().beginTransaction().add(android.R.id.content, new RotationFragment()).commit();
}
}
}
RotationFragment.java
package com.rotationfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RotationFragment extends Fragment implements
View.OnClickListener {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
// This should help to retain fragment
setRetainInstance(true);
View result=inflater.inflate(R.layout.activity_main, parent, false);
result.findViewById(R.id.button).setOnClickListener(this);
textView = (TextView)result.findViewById(R.id.textView);
return(result);
}
#Override
public void onClick(View v) {
textView.setText("Hello.");
}
}
Upon rotation the text in TextView is not restored.
I know some of you would suggest using parceable writeString parceable method to fix this simple example but I want to know why is the Fragment not retained here using setRetainInstance(true)?
And I don't need to retain a string but Socket, Thread and Activity as in previous post.
See the answer, "onRetainInstance saves the Fragment object, but I still have to rebuild UI in onCreateView", So you have to restore the state of your views manually

UI-Elements of 2nd View arent referenceable by findViewById (NullReference) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am new to android-dev and experiencing the following problem:
All UI-Elements of the View list_excercises_item, which shows a ListView's item, are not referenceable by findViewById() only in the MainActivity-file.
I do already reference UI-Elements of the list_excercises_item in an own ArrayAdapter.
Context:
I want to fill my spinner with some data using an ArrayAdapter.
Exception:
java.lang.NullPointerException
at example.trackfit.MainActivity.onCreate(MainActivity.java:28)
This instruction throws it: spinBodyCategory.setAdapter(arrayAdapter);
spinBodyCategory is null.
list_excercises_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1" android:layout_marginBottom="10px">
<EditText
android:layout_width="0dp"
android:layout_height="fill_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txt_excercise_name"
android:hint="#string/hint_txt_excercise_name"
android:layout_weight="0.4"
android:inputType="text" />
<EditText
android:layout_width="0dp"
android:layout_height="fill_parent"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/txt_input_weight"
android:paddingLeft="5px"
android:layout_weight="0.20"
android:hint="#string/hint_txt_input_weight" />
<Spinner
android:layout_width="0dp"
android:layout_height="fill_parent"
android1:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/spin_body_category"
android:hint="#string/hint_txt_excercise_name"
android:gravity="right"
android:layout_weight="0.40"
android:inputType="text" />
</LinearLayout>
MainActivity.java:
package example.trackfit;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import java.util.ArrayList;
import example.trackfit.Models.Body;
import example.trackfit.Models.Excercise;
public class MainActivity extends AppCompatActivity {
private Spinner spinBodyCategory = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateExcerciseList();
Body[] bodies = Body.values();
ArrayAdapter<Body> arrayAdapter = new ArrayAdapter<Body>(this, R.layout.list_excercises_item, bodies);
ListView listView = (ListView)findViewById(R.id.list_excercises);
spinBodyCategory = (Spinner)findViewById(R.id.spin_body_category);
spinBodyCategory.setAdapter(arrayAdapter);
}
private void populateExcerciseList() {
ArrayList<Excercise> excercises = Excercise.getExcercises();
CustomExcerciseAdapter adapter = new CustomExcerciseAdapter(this, excercises);
ListView listView = (ListView)findViewById(R.id.list_excercises);
listView.setAdapter(adapter);
}
}
CustomExcerciseAdapter.java:
package example.trackfit;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import java.util.ArrayList;
import example.trackfit.Models.Excercise;
public class CustomExcerciseAdapter extends ArrayAdapter<Excercise> {
public CustomExcerciseAdapter(Context context, ArrayList<Excercise> excercises) {
super(context, 0, excercises);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Excercise excercise = getItem(position);
if (convertView == null)
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_excercises_item, parent, false);
EditText txtExcerciseName = (EditText) convertView.findViewById(R.id.txt_excercise_name);
EditText txtInputWeight = (EditText) convertView.findViewById(R.id.txt_input_weight);
txtExcerciseName.setText(excercise.ExcerciseName);
txtInputWeight.setText(Float.toString(excercise.Weight));
return convertView;
}
}
Edit:
This question is not a duplicate, I ofc know what a NullReferenceException is.
I did not know why this exception was thrown, since - I am new to android-dev and didnt know that I can only access childs of the View I set as my contentView.
Because findViewById is called from MainActivity.java, it is trying to find your spinner from the layout you set: activity_main.xml. Which is why you are getting a null pointer exception.
Since you have a spinner for each item on your list, you will have to set it from getView in your custom adapter.
Try copying and pasting
Body[] bodies = Body.values();
ArrayAdapter<Body> arrayAdapter = new ArrayAdapter<Body>(this, R.layout.list_excercises_item, bodies);
spinBodyCategory = (Spinner)convertView.findViewById(R.id.spin_body_category);
spinBodyCategory.setAdapter(arrayAdapter);
to your getView

Android WebView in Fragment

I know the following is probably simple, but I can't seem to get it to work. It compile and runs, but doesn't load any URL I throw at it. I have Internet set in permisions, even checked to make sure it was running in some other code.
package com.richardmather.autoaccidentattorney;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
public class FindHospitalFragment extends Fragment {
public FindHospitalFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_hospital, container, false);
final WebView webView = (WebView) rootView.findViewById(R.id.webView);
String searchURL = "http://www.stackoverflow.com";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("searchURL");
return rootView;
}
}
Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</LinearLayout>
I know it's something simple I'm missing.
EDIT: Took out the quotation marks, now it's loading the URL in Google Chrome....
The problem probably is the line webView.loadURL("searchURL");.
By doing that it actually tries to load the URL searchURL and not the URL http://www.stackoverflow.com you saved in the variable searchURL.
So just remove the "s:
webView.loadURL(searchURL); // searchURL = "http://www.stackoverflow.com"
Edit:
To not launch chrome, simply add the following line:
webview.setWebViewClient(new WebViewClient());
Also see this question for details.

Unable to replace/navigate fragments

I am trying to navigate from one fragment to another. These two fragments are 100% different, there is no ViewPager or something like that to connect them. Here is the code.
fragment_view1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/firstView">
<TextView
android:id="#+id/viewOneText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="182dp"
android:text="First View"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/viewOneBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/viewOneText"
android:layout_below="#+id/viewOneText"
android:layout_marginTop="17dp"
android:text="Click Here" />
<include layout = "#layout/drop_down"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_alignParentBottom="true"/>
<FrameLayout
android:id="#+id/fragment_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/customFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="174dp"
android:text="Custom Fragment"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
FirstView.java (uses fragment_view1.xml)
package com.example.fragmenttest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FirstView extends DropDownMenu
{
private TextView firstText;
private Button btn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_view1,container,false);
firstText = (TextView)view.findViewById(R.id.viewOneText);
btn = (Button)view.findViewById(R.id.viewOneBtn);
btn.setOnClickListener(new ButtonEvent());
return view;
}
private class ButtonEvent implements OnClickListener
{
#Override
public void onClick(View v)
{
// Create new fragment and transaction
Fragment newFragment = new CustomView();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_view, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
CustomView.java (uses custom_view.xml)
package com.example.fragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class CustomView extends Fragment
{
private TextView secondText;
private Button secondViewBtn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.custom_view,container,false);
return view;
}
}
In FirstView.java, when I click on the button, I need to move to the Fragment CustomView. But instead moving, it simply replaces everything in CustomView on top of FirstView. Below images will explain it better.
FirstView alone
CustomView alone
When the button is FirstView clicked
Why it is happening like this?
You are trying to replace firstView with the new fragment, but firstView is not a fragment, its' a RelativeLayout.
You cannot replace a fragment defined statically in the layout file. You can only replace fragments that you added dynamically via a FragmentTransaction.
None of your Layout contains fragment in layout.
<fragment
android:id="#+id/fragment1"
android:layout_width="march_parent"
android:layout_height="match_parent"></fragment>
A new Fragment will replace an existing Fragment that was previously added to the container.
Take look on this.
If you need to replace one fragment with another then fallow undermentioned :
TalkDetail fragment = new TalkDetail();
// TalkDetail is name of fragment which you need to put while replacing older one.
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("cat", m_ArrayList.get(arg2).cat);
bundle.putString("header_title", "Talk");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle); ((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
Here's your BaseContainerFragment.java class that will manage a lot of stuff for you.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import app.drugs.talksooner.R;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
For more specific details find my complete post over here ..
Dynamically changing the fragments inside a fragment tab host?

Categories