textview giving null pointer - java

I hate errors like this. I'm getting a null pointer. I know what it means. I just don't understand how i'm getting it since i know that the item it should be pointing to does exist. I'm creating a textview that will be updated by the opengl renderer. The textview provides a score. I've created the textview in XML and given it a 'id', then i reference it in my program and update it through the renderer. Icreate TextView variables globally then I initialize them in the onCreate() method. Then I created a method to set the text. Which is called inside of my renderer class.
Here is my java code
View r1;
TextView score3, score4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set app to full screen and keep screen on
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(Main.layout);//R.layout.gl_triallayout;
r1 = findViewById(Main.id);////R.id.gl_triallayout;
score3 = (TextView) findViewById(R.id.threeScore);
score4 = (TextView) findViewById(R.id.fourScore);
......
}
public int get3(int i){
score3.setText("Score" + String.valueOf(i));
((RelativeLayout) r1).bringChildToFront(findViewById(R.id.threeScore));
Log.i("i", String.valueOf(i));
return i;
}
XML code
<TextView
android:id="#+id/threeScore"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:textSize="30dp"
android:textColor="#ffff00"/>
Update
Main class
public void Trial(View v) {
layout = R.layout.gl_triallayout;
id = R.id.glTrialLayout;
gameType = 0;
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
}
public void PlayGame(View v) {
layout = R.layout.gl_layout;
id = R.id.glLayout;
gameType = 1;
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
}
I hate the idea of clutter stackoverflow with the same question so if the answer is immensely simple could you give it to me in the comments. then i could delete this.

Your
setContentView(Main.layout)
should be
setContentView(R.layout.filename)
In the above code, you should change your layout file name based on your need like R.layout.activity_main.
Same applies to,
r1 = findViewById(Main.id);////R.id.gl_triallayout;
What is r1?
If it's a button, it should be
r1 = (Button) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout;
If it's a Editext,
r1 = (EditText) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout
If it's a TextView,
r1 = (TextView) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout
Also, In your XML layout, where's the view for score4 and r1?
I think you should start learning the basics of Android first.

Related

Adding button in runtime using button onclick event

I'm making a game in where the platform will add new button in each level the user has cleared. but I cant add new xml tag in the project on runtime. I'm a little lost of what to use or how to implement.
run = (Button)findViewById(R.id.btnRunChallengeMode);
run.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newForm = new Intent(Form2.this,Form2.class);
buttonPanel = (LinearLayout)findViewById(R.id.LinearButtonPanel);
Button newButton = new Button(null);
newButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newButton.setId(a);
newButton.setText("Button " + a);
buttonPanel.addView(newButton);
a++;
startActivity(newForm);
}
});
below is the xml code
<HorizontalScrollView
android:id="#+id/buttonPanelChallengeMode"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_below="#+id/IDE"
android:layout_marginBottom="3dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:background="#color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_editor_absoluteX="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/LinearButtonPanel">
</LinearLayout>
</HorizontalScrollView>
This is because after adding the button to the layout you are starting the new Activity no matter it's the same activity. Whenever activity is created it will always use the initial xml format. I think you are under the impression that adding new button will persist and becomes a part of XML. That's not true, if you want to start the new activity. Set new Button value in Bundle, then in onCreate check the existence of bundle. If exist's then add a new button.
int buttonId = -1;
protected void onCreate(Bundle b){
//set the layout related stuff first
Bundle b = getIntent().getExtras();
if(b!= null && (b.getInt(NEW_BUTTON_KEY, -1)!=-1)){
buttonPanel = (LinearLayout)findViewById(R.id.LinearButtonPanel);
for(int i = 0; i< b.getInt(NEW_BUTTON_KEY, -1); i++)
Button newButton = new Button(this);
newButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newButton.setId(i);
newButton.setText("Button " + i);
buttonPanel.addView(newButton);
}
}
By the way why are you making new activity? Just add the button in the same activity, otherwise your activity stack will become massic with every level.
Button newButton = new Button(null);
You give to the context null, i suggest you to give proper context. Also you can set tag for button with newButton.setTag(value)
Your Code is not true
you create a button and add to a LinearLayout and after that you call startActivity for load an Activity. So You reset the LinearLayout and buttons clear from that.
you should :
run = (Button)findViewById(R.id.btnRunChallengeMode);
run.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newForm = new Intent(Form2.this,Form2.class);
newForm.putExtra("a", a);
startActivity(newForm);
}
});
and in the create , get Extras :
String a = getIntent().getIntExtra("a");
now you can create the button.

Adding textviews on button click android?

I've got a button that inserts user information into a database.
On top of this, I would like it to display the users entered details below in a list,
#Override
public void onClick(View v) {
insertuser();
LinearLayout createworkout = (LinearLayout)findViewById(R.id.createworkout);
TextView x = new TextView(getApplicationContext());
x.setText(editTextExercise.toString());
createworkout.addView(x);
}
This is what I have so far. When clicking the button the information is inserted, but I can not see a visible Textview. No errors are thrown either, I don't know what I have done wrong here.
All help appreciated
Thank you
Have your LinearLayout orientation property set?
try to add:
android:orientation="vertical"
or:
android:orientation="horizontal"
Try to change it as...
#Override
public void onClick(View v) {
insertuser();
LinearLayout createworkout = (LinearLayout)findViewById(R.id.createworkout);
TextView x = new TextView(YourActivity.this);
x.setText(editTextExercise.toString());
LayoutParams lp = new LayoutParams ( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
createworkout.addView(x,lp);
}

Cannot resolve method setText(java.lang.String)

I've looked at other questions similar to the error I'm getting, but I can't seem to figure out the issue here. All I'm trying to do is click a button and change a TextView's text.
My code is as follows:
public class FindBeerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
}
//call when the user clicks the button
public void onClickFindBeer(View view) {
//Get a reference to the TextView
View brands = (TextView) findViewById(R.id.brands);
//Get a reference to the Spinner
Spinner color = (Spinner) findViewById(R.id.color);
//Get the selected item in the Spinner
String beerType = String.valueOf(color.getSelectedItem());
//Display the beers. This is where the error is
brands.setText(beerType);
}
}
and the XML
<TextView
android:id="#+id/brands"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/find_beer"
android:layout_alignStart="#id/find_beer"
android:layout_below="#id/find_beer"
android:layout_marginTop="18dp"
android:text="#string/brands" />
When I build I get: "error: cannot find symbol method setText(String)
I'm following a tutorial to the letter and I can't see where I've made a mistake, so I'd appreciate it if you guys could help me out! Thanks!
You can either change
View brands = (TextView) findViewById(R.id.brands);
to
TextView brands = (TextView) findViewById(R.id.brands);
OR change
brands.setText(beerType);
to
((TextView)brands).setText(beerType);
In either ways, you need to call the setText method on a TextView reference.
You are trying setText() method on a view object. You need to call it on a TextView object.so either change the declaration of brands to TextView or just wrap ur brands object to TextView before calling setText() over it.
Change
View brands = (TextView) findViewById(R.id.brands);
To
TextView brands = (TextView) findViewById(R.id.brands);

Adding button click event crashes app at launch

I have the following Java code for my button event. This code doesn't generate any error at compile-time, but the app crashes during launch.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b0 = (Button) findViewById(R.id.button0);
b0.setOnClickListener(this);
}
String t = "";
TextView inp = (TextView) findViewById(R.id.input);
public void onClick(View v)
{
if (v == findViewById(R.id.button0))
{
t = "0";
inp.setText(inp.getText()+t);
}
}
The Xml Code is :
<Button
android:id="#+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/dbtn"
android:layout_alignBottom="#+id/dbtn"
android:layout_toLeftOf="#+id/button3"
android:text="0" />
What am I doing wrong?
TextView inp = (TextView) findViewById(R.id.input);
Put the above line inside onCreate() method after you call setContentView() and change you TextView variable scope from local to global.
This should fix the issue. If you still having trouble, let me know.

Updating TextView within Fragment for Consistency

I am trying to build a quiz app that keeps score as the user answers questions. I'm also using Google's ViewPager for screen slides which employs Fragments to keep different individual pages (code: http://developer.android.com/training/animation/screen-slide.html). I have a TextView (#id/txtvw_score) that is designed to keep score across the entire quiz session. This txtvw_score is placed within fragment_screen_slide_page.xml.
The problem I'm having is that, in order to access said TextView, I have to do it in ScreenSlidePageFragment's onCreateView() method. But, because Android calls this onCreateView() method twice for every new Fragment, it makes it so that the TextView's score is completely outdated. For example, page 1 would display the current score, then page 2 would display page 0 (uninitialized score), then page 3 would display page 1's score, etc.
I'm using SharedPreferences to keep the actual score updated. I've been able to keep track of the score perfectly fine when I use the ActionBar. This is only for confirmation purposes though, as I don't actually want to use the ActionBar.
Further complicating the problem is that I can't update the TextView within the Fragment's onCreate() method. I've also tried calling the TextView and changing it from ScreenSlideActivity (source: How to change fragment's textView's text from activity), but that ended up as NullPointerException no matter what I did.
So, long story short, how can I keep a TextView's content consistent across all Fragments? (This is a significant point for me, because, in the future, I want to use a TextView as a display for a timer as well, and that definitely needs to stay consistent).
EDIT (added simplified code):
fragment_screen_slide_page.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:id="#+id/scrlvw_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="15dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp" >
<TextView
android:id="#+id/txtvw_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
ScreenSlidePageFragment.java
public class ScreenSlidePageFragment extends Fragment
{
//The argument key for the page number this fragment represents.
public static final String ARG_PAGE = "page";
ArrayList<String> argAnswerList = new ArrayList<String>();
//The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
private int mPageNumber;
//preferences
SharedPreferences sharedPrefs;
SharedPreferences preferences;
SharedPreferences.Editor editor;
final int DEFAULT = 0;
final int CHOSEN1 = 1;
final int CHOSEN2 = 2;
final int CHOSEN3 = 3;
final int CHOSEN4 = 4;
TextView txtvwScore;
int questionsTotal;
int numChosenCorrect, numChosenTotal, ratio;
//Factory method for this fragment class. Constructs a new fragment for the given page number.
public static ScreenSlidePageFragment create(int pageNumber)
{
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getActivity().getActionBar().show();
fillArgAnswerList();
//fillAnswerList();
mPageNumber = getArguments().getInt(ARG_PAGE);
getPrefs();
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
editor = preferences.edit();
numChosenCorrect = sharedPrefs.getInt("numChosenCorrect", DEFAULT);
numChosenTotal = sharedPrefs.getInt("numChosenTotal", DEFAULT);
ratio = sharedPrefs.getInt("ratio", DEFAULT);
getActivity().getActionBar().setTitle("Score: " + numChosenCorrect + "/" + numChosenTotal + " (" + ratio + "%)");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
//setting the score
txtvwScore = (TextView) rootView.findViewById(R.id.txtvw_score);
setButtonOnClickListener();
return rootView;
}
private void setButtonOnClickListener()
{
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
numChosenCorrect = sharedPrefs.getInt("numChosenCorrect", DEFAULT);
numChosenTotal = sharedPrefs.getInt("numChosenTotal", DEFAULT);
ratio = sharedPrefs.getInt("ratio", DEFAULT);
String answer = button.getText().toString();
if(answer.equals(correct))
{
numChosenCorrect++;
numChosenTotal++;
}
else
numChosenTotal++;
//update the actionBar score
ratio = Math.round(((float) numChosenCorrect)/((float) numChosenTotal)*100);
//setting the score
getActivity().getActionBar().setTitle("Score: " + numChosenCorrect + "/" + numChosenTotal + " (" + ratio + "%)");
editor.putInt("numChosenCorrect", numChosenCorrect);
editor.putInt("numChosenTotal", numChosenTotal);
editor.putInt("ratio", ratio);
editor.commit();
}
});
}
/**
* Get the preferences saved.
*/
private void getPrefs()
{
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber()
{
return mPageNumber;
}
}
All codes have been simplified to show what the question revolves around. All removed code has been tested and they work up until this point.

Categories