Activity Instance does not exist- null object reference - java

I am trying to develop an Android application. For my use case I want to use a custom typeface and I wrote a that gathers all available TextViews in a View, so that I can set the typeface easily by a loop. I thought I should source out the text manipulation things to an own class named TextManager.class . But now when I am executing the app I am getting an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
It occurs when I am trying to set Typeface in TextMangaer.class . I did a bit of research and found out that it is because the activity instance does not exist at this point. But I don't get it why, cause when I am trying to do this in Start.class there is no problem.
//Start.class
public class Start extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // set fullscreen
//Initialize shared preferences
prefs = getSharedPreferences("User", Context.MODE_PRIVATE);
editor=prefs.edit();
setContentView(R.layout.start_screen);
TextManager textManager= new TextManager();
textManager.setTypeface(getTextViews((ViewGroup) findViewById(R.id.root_menu)));
}
}
and my TextManager.class:
public class TextManager extends Start{
public TextManager(){
super();
}
public void setTypeface(List<Integer> idsOfTextViews){
Typeface typeFaceIkarosLight= Typeface.createFromAsset(getAssets(), "font/ikaros_light.otf");
for(int i=0; i < idsOfTextViews.size();i++){
((TextView)findViewById(idsOfTextViews.get(i))).setTypeface(typeFaceIkarosLight);
}
}
}
So how could I fix this or how should I write this? If anybody could help me figure it out that would be great. Thanks in advance.

Problem is context is null for getting assets.
Use getContext() or getApplicationContext() in case of being used in an activity but if it is being used in a fragment then use getActivity().getContext()
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "font/ikaros_light.otf");
Instead of
Typeface typeFaceIkarosLight= Typeface.createFromAsset(getAssets(), "font/ikaros_light.otf");

Its better to make method which return typeface instead passing textview ids as an argument. you can do it like this :
public Typeface getTypeFace(Context context){
Typeface typeFaceIkarosLight = Typeface.createFromAsset(context.getAssets(), "font/ikaros_light.otf");
return typeFaceIkarosLight;
}

If you want to use custom fonts then you can take this example
This tutorial will show you how to set custom font on TextView, EditText and on Button.
http://androiderstack.com/index.php/2017/08/14/use-custom-font-in-textview-edittext-and-button-in-android/
This will surely help you

Related

How do I reference an image from another layout?

to replace the image in the layout programmatically, in my case, i need to refer to the image from another layout of the other class. There is: the first class, which is extended by the second class, each class has its own layout. I need to refer from the first class to the image in the mockup of the second class.
How do I do this based on the image replacement code below?
ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);
pass some value to 2nd activity before starting using putextra based on the value set image there .
if it is from second to first that use startactivityforresult and setresult
You can use the image anywhere you want
public class Activity2 extends Activity1 {
ImageView changeImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int image1 = R.id.imageView1;
int image2 = R.id.imageView2;
changeImage = (ImageView)findViewById(R.id.imageView1);
changeImage.setImageResource(**you can add your image1/image2 **);
}
}
Think this will solve your problem
NOTE: Parent to child calling is not recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.
However.. you can achieve this by following method in FirstClass :
void udpate(SecondClass s) {
if(s instanceof SecondClass) ((SecondClass)s).updateImageView(String url);
}
where updateImageView would be method inside your SecondClass for updating required imageView.
Hope it helps.

How to use global variable in onCreate method of Android

I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.
Here's my code:
public class MyActivity extends AppCompatActivity
{
public static int num_i=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
TextView tv = findViewById(R.id.textView);
tv.setText(num_i);
num_i++;
}
}
Please help me in this.
setText(CharSequence text)
Sets the text to be displayed. it takes String as a parameter not a number
Sample : tv.setText("PREM");
setText(int resid)
Sets the text to be displayed using a string resource identifier.
Sample : tv.setText(R.string.app_name);
first you have to convert your int value in to a String
Try this use
tv.setText(String.valueOf(num_i));
or
tv.setText(num_i+"");
instead of this
tv.setText(num_i);
Don't use tv.setText() with a number as parameter. Try using String.valueOf(num_i).
So in your case:
tv.setText(String.valueOf(num_i)) or tv.setText(num_i + "");

What to pass into LinearLayout constructor

Hi guys :) I am storing products for my android app in a Parse database and trying to load them up at run-time.
I want to create a LinearLayout in the 'done' method below but I am not sure how to pass the Context in the LinearLayout constructor. What do I put in the contructor's parameter?
Thank you!
public class BrowseActivity extends Activity {
//do stuff here
#Override
protected void onCreate(Bundle savedInstanceState) {
/*Get all services and packages from parse database*/
ParseQuery<ParseObject> query = ParseQuery.getQuery("InAppProducts");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e)
{
if(e == null)
{
/*Add products to page*/
//What do I put where "this" is?
LinearLayout layout = new LinearLayout(this);
}
else{
}
}
});
}
Try using getApplicationContext() or BrowseActivity.this
You could use BrowseActivity.this or getBaseContext() here. But please don't use getApplicationContext() as other answers suggests. View's should be created with Activity context, then only it will get destroyed and garbage collected along with Activity.
Krishnabhadra is correct, passing an application context won't let the view garbage collected even if the activity gets destroyed. So use instead BrowseActivity.this or getBaseContext() to get Activity context.

Why won't showSoftInput display the virtual keyboard?

Essentially I am trying to show the virtual keyboard and gather input without the use of a visible EditText or TextView. I realize that toggleSoftInput can be used to do this however I need to use showSoftInput because I want to use a TextWatcher for manipulating the input. Also, the engine I am using is c++ so I am trying to do as little java-only code as possible so I am avoiding the .xml files. So here goes...
public class GameActivity extends Activity {
protected GameView view = null;
protected EditText editText;
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
view = new GameView(this);
setContentView(view);
editText = new EditText(this);
editText.setCursorVisible(false);
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
}
public boolean showKeyboard()
{
JniApp.log("showKeyboard() in Java invoked!!!");
editText.requestFocus();
editText.requestFocusFromTouch();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
Where showKeyboard() is my c++ call into java. I have checked to make sure that editText is receiving focus and it is. However, showSoftInput returns false. Any help would be greatly appreciated.
UPDATE: After some debugging it looks as if requestFocus returns true but the activity still says view is the current focus.
Maybe try it with .SHOW_IMPLICIT instead of .SHOW_FORCED ?
Have you tried it on other emulators / devices with maybe other Android versions?

Android; Declaring edittext in class body (Out of any method)

I have experience with programming languages but am a bit new to android programming.
I have a program with some fields that function as labels(textview), buttons, and data entry(edittext).
Whenever i declare them at the beginning of the program out of any methods(but in the class of course), when I start my application it crashes and simulation gives a "unfortunately, your program has stopped" alert.
Eclipse doesn't give any errors for the declaration and i did use the same way for defining regular variables with no issue. It also gives the same error when i declare a mediaplayer object in the class body.
Does anyone know why it gives error?
And is there another way to declare global objects like edittext, viewtext, etc... Declaring them over and over again in methods sounds weird to me.
Thank you!!
public class TrainerActivity extends Activity {
Button stopTimer = (Button)findViewById(R.id.StopTimer);
Button startTimer = (Button)findViewById(R.id.StartTimer);
EditText totalTime = (EditText)findViewById(R.id.TotalTime);
EditText enterMin = (EditText)findViewById(R.id.EnterMin);
EditText enterSec = (EditText)findViewById(R.id.EnterSec);
private boolean breaker = false;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StartTimer();
}
});
stopTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StopTimer();
}
});
}
Without seeing example code of what you're trying it's impossible to say for definite (we don't do mind-reading here). But let me guess, you're doing something like this?...
public class MyActivity extends Activity {
TextView tv1; // This is fine.
  TextView tv2 = (TextView) findViewById(R.id.textview2); // Don't do this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.textview1); // This is fine
tv1.setText("Some text"); // This works
tv2.setText("Some text"); // NullPointerException here
}
}
The tv2.setText(...) will fail because you used findViewById(...) BEFORE you call setContenetView(...) and as a result, tv2 will be null.
It's quite acceptable to declare your widgets as instance members in your Activity but don't try to use findViewById(...) until AFTER you have set your content view.
try declaring the widget objects names only outside the onCreate() method
Button stopTimer;
Button startTimer;
EditText totalTime;
EditText enterMin;
EditText enterSec;
then initialise them after setContentView() inside onCreate()
setContentView(R.layout.main);
stopTimer = (Button)findViewById(R.id.StopTimer);
startTimer = (Button)findViewById(R.id.StartTimer);
totalTime = (EditText)findViewById(R.id.TotalTime);
enterMin = (EditText)findViewById(R.id.EnterMin);
enterSec = (EditText)findViewById(R.id.EnterSec);
Can you post a bit of sample code that illustrates the issue? It is fine to declare a member variable that is an EditText or TextView in the class.
logcat(in DDMS) should be give you some info about the error as well. If you are using eclipse there is a tab for DDMS, if not you can just run DDMS from a command line look at the logcat tab and launch your app (with your phone plugged in via usb, of course.) You should be able to see the actual error being reported.
You can declare these variables inside the Class body or inside the method body. In the former case, the variables are global and thus can be accessed within the whole class; in the latter case, they are local and thus can be only accessed within that method. Both of them could be commonly seen in proramming.
In Android, the typical application is that you declare the variables in the Class body and instantiate them in the onCreate() method. Something like this:
public Class MyClass extends Activity{
TextView label;// so this variable can be accessed within any methods in this Class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(Bundle savedInstanceState);
setContentView(R.layout.main) // load the layout of the activity
label=(TextView)findViewById(R.id.<the TextView id defined in the layout file>); //this variable get instantiated. From now on you can manipulate it anywhere inside the class.
Button submit=(Button)findViewById(R.id.<the Button id defined in the layout file>);//you declared and instantiated it, but it could only be used within this method since you declared it here.
}
}
If you just declare a variable in the Class body,in most caeses, you can't use it until you instantiate it, because they are null before the instantiation. I think this is why you have problems. Please post the logcat so we can specify the real problem.

Categories