I always get NullPointerException whenever I call:
getApplicationContext().getResources().getStringArray(R.array.days);
I called it from DialogFragment in my Activity. I also tried using getActivity(), but that didn't work for me too. Does anybody have any idea about this problem?
Try this:
If you write this in a fragment:
String[] days = getActivity().getResources().getStringArray(R.array.days);
If you write this in an activity:
String[] days = this.getResources().getStringArray(R.array.days);
It´s just an assumption, but mostly if somebody gets this error, they make a mistake where the code is placed or when they call it. For example, if you call it before onCreate():
public class YourActivity extends Activity {
private String foo = "foo";
private String[] yourArray = getResources().getStringArray(R.array.yourArray);
public void onCreate(Bundle savedInstanceState){
...
}
}
This will result in a NullPointerException. Instead you have to call it like this:
public class YourActivity extends Activity {
private String foo = "foo";
private String[] yourArray;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.yourLayout);
yourArray = getResources().getStringArray(R.array.yourArray);
}
}
Try this.
public class YourActivity extends Activity{
Context mContext;
public void onCreate(Bundle savedInstanceState){
setContentView(R.layout.yourLayout);
mContext = this;
}
class DialogFragment{
String[] days = mContext.getResources().getStringArray(R.array.days);
...............
}
}
I hope it helps!
Related
I decided to try and make my code more object oriented and avoid repetitive code in another class.
Source code for Activities :
public class EasyMode extends MainActivity {
GameActivityPVP game = new GameActivityPVP();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
game.initializeButtons();
}
}
public class GameActivityPVP extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
The second the program gets to the line where I try to call a method using game.methodName(); the program crashes. No compiling errors or anything.
I am new to programming in general so please take it easy on me and I tried to simplify my code as much as possible.
Android Monitor/logcat :
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
and
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
You can use another class's method by creating object of parent class.
See below example;
Here you want to use method from 'GameActivityPVP' class. So you need to create one object in this class only.
public class GameActivityPVP extends MainActivity {
public static GameActivityPVP mGameActivity;
public GameActivityPVP getInstance(){
return mGameActivity; // assign value in onCreate() method.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
mGameActivity = this; // Do not forget this, otherwise you'll get Exception here.
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
Now use this Object in another class 'EasyMode' like this;
if(GameActivityPVP.getInstance()!=null){
GameActivityPVP.getInstance().initializeButtons();
}
Try This:
Make one Class Utils:
In Utils:
public class Utils{
private Activity context;
Button button;
public Utils(Activity context) {
this.context=context;
}
public void inititializeButton(Activity context){
button[0]= (Button) context.findViewById(R.id.button_flasher);
}
}
And in your Class use:
public class EasyMode extends MainActivity {
Utils utils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
utils=new Utils(this);
utils.initializeButtons();
}
}
As already stated, you shouldn't use nested activities, they are not supposed to interact like this. If you want two activities to interact you have to do it through an intent. Regarding the duplicated code, you have few solution presented but my personal opinion is that the OOP rules are not followed. If I had to write that logic, I would create a BaseActivity to hold the common logic of the other two activities and use inheritance to extend them.
public class BaseActivity extends Activity {
protected List<Button> buttons = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
protected void initializeButtons() {
buttons.add((Button) findViewById(R.id.button1));
}
}
public class EasyMode extends BaseActivity {
// Add here logic that is used only in EasyMode activity
}
public class GameActivityPVP extends BaseActivity {
// Add here logic that is used only in GameActivityPVP activity
}
Note that in this way you don't have to override onCreate again to initialise the buttons and so on. Also, I saw that you used the same layout for both activities, but if you want to use different layouts you can do it as usual and then call initializeButtons.
Im interested if i can to set some common listeners inside main activity class? For my project i use FirebaseAuth, so i would like to init it in MainActivity onCreate(), setup needed listeners in onStart() and onStop(), and then inherit that class in every other activity class.
Some code to please you :]
MainActivity class [parent]:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
protected FirebaseAuthentication firebaseAuthentication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firebaseAuthentication = new FirebaseAuthentication(FirebaseAuth.getInstance(), FirebaseDatabase.getInstance());
}
#Override
protected void onStart() {
super.onStart();
firebaseAuthentication.addAuthStateListener();
}
#Override
public void onStop() {
super.onStop();
firebaseAuthentication.removeAuthStateListener();
}
}
AuthActivity class [child]:
public class AuthActivity extends MainActivity implements FirebaseAuthentication.OnUserAuthListener {
#BindView(R.id.viewPager) LockableViewPager viewPager;
private String userUID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_market);
ButterKnife.bind(this);
firebaseAuthentication.setOnUserAuthListener(this);
firebaseAuthentication.isSingedIn(); // check if user is singed in
}
#Override
// response for firebaseAuthentication.isSingedIn() above
public void onAuthSuccess(String userUID) {
this.userUID = userUID;
}
#Override
// response for firebaseAuthentication.isSingedIn() above
public void onAuthFailure(String message) {
snackbar(message);
Intent intent = new Intent(this, AuthActivity.class);
startActivity(intent);
finish(); // TODO mb should to delete it
}
}
Can this implementations bring me errors (maybe NullPointerExeption or what unexpectedly in future)?
Would be great if you provide me some sources to read/watch.
Thank you.
Perfect example of abstraction, but not really a question.
You will not get any nullpointers or other errors by implementing it like this.
i'm trying to send data from activity to fragment
here is the activity code :
Bundle args=new Bundle();
args.putString("username", username);
ViewEmpAttend fragobj=new ViewEmpAttend();
fragobj.setArguments(args);
here is the fragment code :
username=this.getArguments().getString("username");
but this code gives me an error said "null object reference" in the onCreateView method in (Fragment Class) .
please help :)
Try to retrieve arguments from onCreate of Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String username = this.getArguments().getString("username");
}
In activity define one method.
public class MainActivity extends AppCompatActivity {
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//your code
}
//define this method
public String getName(){
this.name = username;
}}
In fragment use following code.
String userName = ((activityName) getActivity()).getName();//you will get name here.
For something simple like that, i will just create a constructor method in the fragment to pass in a string.
for example
public class MyFragment extends Fragment{
private String myString;
public MyFragment (){
// Recommended Empty Constructor
}
public MyFragment (String yourString){
this.myString = yourString;
}
}
On your Activity class you can pass in the string direct to your fragment constructor
public MyClass extends Activity{
#override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openFragment();
}
public void openFragment(){
MyFragment fragment = new Fragment("yourString");
// Here begin the fragment transaction
}
}
i have problem in this simple code, I declare a String , and want change it inside onCreate but AFTER onCreate i have "VariableDeclaratorId expected after this token" Error !!
And if i put item=222 inside onCreate i get "111null333" when Toast display
here is my code
public class MainActivity extends Activity {
static String item;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), mStrings[0], Toast.LENGTH_SHORT).show();
}
item="222";
private String[] mStrings={
"111"+item+"333",
"test"
};
}
Can you please spend some time and format your question correctly ? i do not see clearly if the item = "222"; is inside a method or not.
But if your formatting is "correct" then your problem is that the assignation of a value to the item variable can not be done outside of a method or the static{} block of code. And so if you use the item variable in another object or class variable before assigning it a value it will be the default value (null for objects and 0 or false for the primitive values).
Hope this helps.
UPDATE:
public class MainActivity extends Activity {
static String item;
private String[] mStrings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = "222";
mStrings = new String[2];
mStrings[0] = "111" + item + "333";
mStrings[1] = "test";
Toast.makeText(getApplicationContext(), mStrings[0], Toast.LENGTH_SHORT).show();
}
}
I have an activity that roughly follows this structure:
public class myActivity extends Activity implements myCallback{
//Code
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
new myAsyncTask(myActivity.this).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(context,"Hello",Toast.LENGTH_SHORT).show();
}
}
And myAsyncTask has the myCallback() interface defined and it calls it eventually. No matter what I do, whatever UI element I try to show, be it a Toast or a ProgressDialog, it won't show. Nor do I get any exceptions. The rest of the callback code gets perfectly executed. Why is this?
Try using:
public class myActivity extends Activity implements myCallback{
//Code
Context mContext;
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
mContext = this;
new myAsyncTask(getApplicationContext()).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(mContext,"Hello",Toast.LENGTH_SHORT).show();
}
}
Instead of using context , use getApplicationContext... i hope it will show toast... like this
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();