Why Is Accessing Textview of a Fragment Inside Activity Throwing an Error

Why is accessing TextView of a Fragment inside Activity throwing an error

Because fo hasn't been initialized in the following code snippet:

FragOne fo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

fo.setTextViewText("This is added from Activity");
...
}

fo.setTextViewText() reasonably throws NPE.

Cannot access Textview inside fragment

I figured it out myself. The problem was here:

CourseFragment fragment = new CourseFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.course1, fragment);
fragment.setTitle();
ft.addToBackStack(null);
ft.commit();

The problem was that I was calling setTitle() on fragment which did not have its view created. when instead I did the following the problem was solved:

CourseFragment fragment = new CourseFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.course1, fragment);
ft.addToBackStack(null);
ft.commit();

CourseFragment frag = fm.findFragmentById(R.id.course1);
frag.setTitle();

I eventually changed a lot of my code but I hope this helps someone. thanks for the answers everyone

Android: Can't update textview in Fragment from Activity. NullPointerException

Use below callback:

Fragment Class:

public class FragmentOne extends Fragment {

private ViewCallback mCallback;

public FragmentOne(ViewCallback mCallback) {
this.mCallback = mCallback;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
mCallback.updateTextView((TextView) view.findViewById(R.id.fragmentTextView));
return view;
}

public interface ViewCallback {
void updateTextView(TextView view);
}
}

Below is the Activity class:

public class MainCallbackActivity extends Activity implements CallbackFragment.ViewCallback {

public TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callback);

FragmentOne fragment = new FragmentOne(this);
getFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();

}

@Override
protected void onResume() {
super.onResume();
if (textView != null)
textView.setText("Updating Fragment TextView in Activity..!!");
}

@Override
public void updateTextView(TextView view) {
this.textView = view;
}
}

Implment that call back in your activity class..then update the textview.

when i tried to get the textview value in Fragment from mainactivity, my app is not working

To pass strings such as names/emails etc it's quite easy to use a custom sharedPreferences class. Say you want to pass a string name from Fragment A to Activity B, and also access name in fragments B and C, you could do all this using a local sharedPreferences class. I'll post example code for you below.

The custom SharedPreferences class (call it UserDetails or something):

public class UserDetails{
static final String SharedPrefUserName = ""; //default value can go in between " ".
static final String SharedPrefUserOtherData = "";

//the bit below gets the shared preferences
public static SharedPreferences getSharedPreferences(Context ctx)
{
return PreferenceManager.getDefaultSharedPreferences(ctx);
}

//This sets a string value
public static void setLoggedInUserName(Context ctx, String name)
{
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putString(SharedPrefUserName, name);
editor.commit();
}

//this retrieves a string value
public static String getLoggedInUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(SharedPrefUserName, "");
}

}

To set the credentials you would use:

username = (EditText) findViewById(R.id.username);

String name = username.getText().toString();

// If you called your shared prefs 'UserDetails', storing the name would look like this:

UserDetails.setLoggedInUserName(getApplicationContext(), name);

Then to retrieve the stored data, and set a textView (lets call it 'userNameTextView') we do this:

Textview usernameTextView = (TextView) findViewById(R.id.yourTextViewId);

String userStoredName = UserDetails.getLoggedInUserName(getActivity());

userNameTextView.setText(userStoredName);

EDIT: You can do this without creating a new class for the SharedPreferences. The code below is the same as yours, just corrected with the SharedPreferences implemented.

To insert a string into shared prefs, using your String.

SharedPreferences preferences = 
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",name);
editor.apply();

This puts your value for 'name' that you got through your EditText (using getText().toString()). Now to access 'name' from your fragment, you can do this:

SharedPreferences preferences = 
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = preferences.getString("Name", "");

Note how "Name" is used here just as with the first bit of code, this is called a 'key', which is part of a 'key-value pair'. You need a key to access the string that is stored in the preferences. This way you can have any number of key-value pairs saved (e.g. name, age, email, DoB, country etc.) AND access them anywhere within the app. Make sure not to save passwords in shared prefs though.

To make this easier for you to understand, I'll rewrite the code you posted to include this, and highlight it with comments.

Your Main Activity (the first one):

public class Home_Foodcourt extends AppCompatActivity implements View.OnClickListener {
EditText username,userpassword;
Button user_login;
TextView user_register;
FoodCourt_UserLoginDatabase foodCourt_userDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home__foodcourt);
foodCourt_userDatabase=new FoodCourt_UserLoginDatabase(this);

username=(EditText)findViewById(R.id.username);
userpassword= (EditText) findViewById(R.id.loginpassword);
user_login=(Button)findViewById(R.id.login_submit);
user_register= (TextView) findViewById(R.id.user_newregister);

user_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(Home_Foodcourt.this,FoodCourt_Register.class);
startActivity(i);
}
});

user_login.setOnClickListener(this);

}

@Override
public void onClick(View view) {

String name=username.getText().toString();

//############ I've added the section below. ###########
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",name);
editor.apply();
//############ SharedPref section complete. ############

String password=userpassword.getText().toString();
String Admin="aDminSN";
String Pass= foodCourt_userDatabase.Login(name);

if(password.equals(Pass)) //
{
Message.message(this,"Log in Successfully");
Intent i=new Intent(Home_Foodcourt.this,Userhome.class);
i.putExtra("Username",name);
startActivity(i);

}else
{
Message.message(this,"Login Failed");
}

}

Now for the fragment:

public class HomeFragment extends Fragment {
private TextView textView;

public HomeFragment() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Bundle bundle=getArguments();
View rootView=inflater.inflate(R.layout.fragment_home,container,false);

// ####### ALWAYS initialise your view components like below ##
TextView welcomeMessage = (TextView) findViewById(R.id.PUT_TEXTVIEW_ID_HERE);

// ###### The section below fetches the 'name' value from the first activity ###
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

String username = preferences.getString("Name", "DEFAULT_STRING");
/*You can change DEFAULT_STRING to be any string you want. If there
isn't any data to pull from SharedPrefs, it will show this string instead!*/
// ###################

textView.welcomeMessage("Welcome to FoodCourt " + username);
return rootView;
}

}

I haven't tested this and have just written it in the browser, but it's very similar to what I use in my current project so I'm confident that it'll work for you. Just comment if it doesn't work, but try to provide error codes and give something for me to work with.

TextView in Fragment Returning Null in Android Studio

tvDescription is in the DetailsFragment layout, you need to do any layout configuration in the code for that Class

i.e.


class DetailsFragment extends Fragment {

...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_details, container, false)
tvDescription = view.findViewById(R.id.tvDescription);
tvDescription.setText("some text");

return view
}

}

Error launching activity from fragment android

add getActivity as context before startActivity()
also add NewTask Flag.

Intent intent = new Intent(getActivity(), activity2.class);
intent.addflags(intent.flag_activity_new_task);
getActivity().startActivity(intent);

i'm trying to send data from activity to fragment but i get this error, any can help please?

You should create your fragment something like this:

 public static ProfileFragment NewInstance(String names, String reg) {
ProfileFragment fragment = new ProfileFragment();

Bundle bundle = new Bundle();
bundle.putString("names", names);
bundle.putString("reg", reg);
fragment.setArguments(bundle);
return fragment;
}

Also be sure that you have constructor like this

 public ProfileFragment() {
// Required empty public constructor
}

Define global variables in this fragment like this:

private String _names;
private String _reg;

Override onCreate method like this:

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
_names= getArguments().getString("names");
_reg= getArguments().getString("reg");
}
}

then in your OnCrateView method set text like this:

profileNames.setText(_names);
ProfileRegNumber.setText(_reg);

And in Activity create fragment like this.

private void replaceFragmentInternal(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_fragment, R.anim.exit_fragment);

fragmentManager.popBackStack();
fragmentTransaction
.addToBackStack(null)
.replace(R.id.frameLayoutHolder, fragment)
.commit();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
replaceFragmentInternal(ProfileFragment.NewInstance(names,reg));
}


Related Topics



Leave a reply



Submit