keep getting null pointer exception in asynctasking - java

Ok so I know I should use interfaces to retrieve information from AsyncTask because they run in separate threads but I have been trying in vain to get this right. Can someone guide me to what is wrong with my code?
First I thought I was getting null pointer exception at callback.onJsonReady(movie) because I was still trying to reach movie that was not processed despite my attempt. So I tried sleeping it for 5000ms before it retrieves but I still get a null pointer exception. please help me.
If you need to look at more of my code, please tell me also.
Below is the method where I set up my interface
protected void onPostExecute(String s) {
super.onPostExecute(s);
processData(getmData());
}
private void processData (String mData){
try {
final String MOVIE_TITLE = "Title";
JSONObject jsonObject = new JSONObject(mData);
Log.v(LOG_TAG, mData);
String title = jsonObject.getString(MOVIE_TITLE);
Movie movie = new Movie(title);
callback.onJsonReady(movie);
Log.v(LOG_TAG, "Title of the movie is " + movie.getTitle());
}catch (JSONException e){
Log.e(LOG_TAG, "Error retrieving JsonData");
e.printStackTrace();
}
}
}
Below is my class where I call the interface
public class ResultsPage extends AppCompatActivity implements ParseJsonData.ParseJsonCallback{
private final String LOG_TAG = getClass().getSimpleName();
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTextViews();
}
private void setTextViews () {
Bundle bundle = getIntent().getExtras();
String movieTitle = bundle.getString("title");
Log.v(LOG_TAG, "title recieved is : " + movieTitle);
ParseJsonData parseJsonData = new ParseJsonData(movieTitle, this);
parseJsonData.execute();
}
#Override
public void onJsonReady(Movie movie) {
title.setText(movie.getTitle());
}
}
My logcat is
03-14 18:03:02.931 30827-30827/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jc.tagyourmovie, PID: 30827
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.jc.tagyourmovie.ResultsPage.onJsonReady(ResultsPage.java:44)
at com.jc.tagyourmovie.ParseJsonData$ParseJsonDataBackground.processData(ParseJsonData.java:83)
at com.jc.tagyourmovie.ParseJsonData$ParseJsonDataBackground.onPostExecute(ParseJsonData.java:69)
at com.jc.tagyourmovie.ParseJsonData$ParseJsonDataBackground.onPostExecute(ParseJsonData.java:53)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Your Textview title is not initialized... that is the reason
you need to do something like:
title = (TextView)findViewById(R.id.<your_tv_id>);

Error is in title.setText line. Logcat says so >
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Seems you haven't initialize your textview named title, initialize it before using it.
Your code declared a textview named title
private TextView title;
you have to initialize this textview in onCreate() like below
title = (TextView)findViewById(R.id.TEXTVIEWID);

You need to move code that changes UI to the onPostExecute part of the AsyncTask.
callback.onJsonReady(movie);
This part can be in the doInBackground, but use a field of the AsynchTask rather than a local var so you can access it in the onPostExecute:
Movie movie = new Movie(title);

private TextView title;
You need to give a value to title, something like this:
title = (TextView) R.findViewById(R.id.textviewid);
And after that you can call setText() on it.
Replace textviewid with your textview's id in xml file.

Related

getActionBar() is null outside the onCreate() method

Situation:
I am making a chat app with Skype like UI. The contacts recycler view is on the left side.
I have the custom ActionBar based theme.
I need to set the title in the ActionBar onClick.
So, basically, the onClick method is in the Adapter. OnClick of the contacts, the method is passed to the Activity with ActionBar and the name of the contact should come in the title.
The getActionBar() runs perfectly and the Title is set in onCreate method. But, app crashes when I do the same in method outside onCreate.
I referred links here and here but I couldn't solve my issue.
Please guide me regarding the same.
Example:
ChatActivity extends Activity {
//..onCreate here
if(getActionBar() != null) {
String title = " Chat: ";
if(userName != null) {
title = title + userName;
}
getActionBar().setTitle(title);
}
// onCreate finishes
// onContactChange
public void onContactChange(int position, ContactsVO addContact) {
userName = addContact.getName().toString();
String url = addContact.getDP();
if(getActionBar() != null) { //App crashes here
String title =" Chat: ";
if(userName != null)
title = title + userTo;
getActionBar().setTitle(title);
}
}
}
Async Task is called, webservice returns the data which is set in the Adapter.
Now,
in Adapter,
ChatActivity c1 = new ChatActivity();
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ContactsVO contactsvo = data.get(position);
holder.tv.setText(contactsvo.getName());
String url = contactsvo.getDP();
Glide.with(getContext())
.load(url)
.crossFade()
.into(holder.img);
holder.row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
c1.onContactChange(position,contactsvo); //method called here.
}
});
}
Stack Trace
E/ACRA: ACRA caught a NullPointerException exception for com.chat
Building report. 11-20 15:51:23.278 12797-12941/? E/ACRA: com.chat
fatal error : Attempt to invoke virtual method 'android.view.View
android.view.Window.getDecorView()' on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.Window.getDecorView()' on a null
object reference
at android.app.Activity.initWindowDecorActionBar(Activity.java:2397)
at android.app.Activity.getActionBar(Activity.java:2339)
at com.chat.activities.ChatActivity.onContactChange(ChatActivity.java:276)
at com.chat.utilities.adapters.ChatCustomAdapter$1.onClick(ChatCustomAdapter.java:74)
at android.view.View.performClick(View.java:5678)
at android.view.View$PerformClick.run(View.java:22667)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6293)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1065)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:926)
Please guide me to solve the solution for the same.
My suggestion is to use setSupportActionBar() for whole activity.
Here in your layout.
<android.support.v7.widget.Toolbar
android:id="#+id/home_activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways" />
//OnCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
toolbar = (Toolbar) findViewById(R.id.home_activity_toolbar);
configureHomeToolBar();
}
private void configureHomeToolBar() {
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setIcon(R.drawable.my_logo);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
Then you will be able to use it by calling getSupportActionBar() anywhere in your activity such as:
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setTitle(titlesArray[someIndex]);

JsonArrayRequest not giving any response [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to fetch an array from a database on a remote server using the Android Volley library. The problem is that the JSONobject is not returning any data in the onResponse method. When I try to show the data in JSONobject, the application crashes and logcat shows a NullPointerException.
Java code is given below:
public class AudioFragmentThree extends Fragment {
View view;
TextView text;
String url = "http://www.muftiattaullahmultani.com/android/get_all_bayan.php";
int count = 0;
int i = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.audio_fragment_three, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
while(count<response.length())
{
JSONObject object= null;
try {
object = response.getJSONObject(count);
String s = object.getString("id") +" "+ object.getString("topic");
text.setText(s);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
text.setText("ERROR");
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(jsonArrayRequest);
}
}
LogCat is given below:
FATAL EXCEPTION: main Process: com.example.mashood.muftiattaullahmultanicom, PID: 22596
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at
com.example.mashood.muftiattaullahmultanicom.AudioFragmentThree$1.onResponse(AudioFragmentThree.java:81)
at com.example.mashood.muftiattaullahmultanicom.AudioFragmentThree$1.onResponse(AudioFragmentThree.java:69)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Below is my PHP code:
<?PHP include 'database.php';
$query = 'SELECT * FROM audio_bayan ORDER BY no DESC';
$result = $conn->query($query);
$response = array();
while($row = $result->fetch_assoc()) {
array_push($response,array("id"=>$row['no'],"topic"=>$row['topic']));
}
echo json_encode($response);
?>
You have to define textview like below:
Textview text;
text = (TextView) view.findViewById(R.id.textid);
You forget the findViewById your text field add :
text = (TextView) view.findViewById(R.id.text_id);
to your onCreateView method
Looks like your TextView is null.
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
It means you are trying to call setText on a null reference. You have to assign a reference of your TextView from xml layout to the TextView, something like this in onCreateView or onActivityCreated:
TextView text =(TextView) view.findViewById(R.id.text_view);
where, text_view is the id of your TextView in xml.

Why does my activity crash when I try to get a number?

I have an activity, called AddItem, which contains a couple fields that the user fills out and I am now trying to pass them to another activity. I was able to get the first two fields by doing this:
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
The above code worked fun, but then I tried to get another value which I then cast to a double like so:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
It's kind of long and complicated but I'm basically doing the same thing with the exception of parsing the String and converting it to a double value. I determined that this is the problem code because when I comment it out the rest of the app runs fine.
Here is my Activity:
public class AddItem extends AppCompatActivity {
EditText inputedTask, inputedDescription, inputedLatitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
inputedTask = (EditText) findViewById(R.id.inputName);
inputedDescription = (EditText) findViewById(R.id.description);
inputedLatitude = (EditText) findViewById(R.id.Latitude);
}
public void onSaveItemButton(View view) {
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
if (messageText.equals(""));
else {
Intent intent = new Intent();
intent.putExtra(Intent_Constant.INTENT_MESSAGE_FIELD, messageText);
setResult(Intent_Constant.INTENT_RESULT_CODE, intent);
finish();
}
}
}
You need to make a public method for the onClick, from the documentation:
Within the Activity that hosts this layout, the following method
handles the click event:
/** Called when the user touches the button */
public void sendMessage(View view) {
// Do something in response to button click
}
The method you declare in the android:onClick attribute must have a
signature exactly as shown above. Specifically, the method must:
Be public
Return void
Define a View as its only parameter (this will
be the View that was clicked)
So you need to change the method to public:
public void onSaveItemButton(View view) {
...
}
UPDATE:
As the error log says:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at cs4720.cs.virginia.edu.duysalahandroidminiproject02.AddItem.onSaveItemButton(AddItem.java:33)
You need to catch for empty string in the following code:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
so, check it first:
String val = ((EditText) findViewById(R.id.Latitude)).getText().toString();
if(!val.equals("") {
double Latitude = Double.parseDouble(val);
}
You are calling onSaveItemButton method from a view that is not initialized. You must initialize btnChangeDate in the onCreate from the activity.
Check this answer

Prefs Error - Android ' Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String'

I was trying to implement prefs and solve a problem that I had previously, yet instead it just caused another problem -- a prefs issue. It seems to have shown it was from the lines I put on the onCreate() method.
Specifically in the log it said the following --
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.your.app/com.your.app.activity}: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:225)
at com.your.app.activity.onCreate(ShopActivity.java:105*At the oncreate shown*)
So I was trying to fix this issue, but I could not find a solution. I was making a game with the code, and managed to create a system of coins, which you can see below, also involving the scrolling of cars using the tag system. The issue is that it seems to show up that error every time I load up that activity.
I did not have this issue earlier and was using a different method. Here is the code. Thanks for all help. The code was also edited while trying to fix the error. --
For the onCreate method --
prefs = this.getSharedPreferences(
"com.this.app", Context.MODE_PRIVATE);
status1 = prefs.getString(savelocked,"Locked");
status2 = prefs.getString(savelocked2,"Locked");
status3 = prefs.getString(savelocked3,"Locked");
status4 = prefs.getString(savelocked4,"Locked");
status5 = prefs.getString(savelocked5,"Locked");
locked = status1;
locked2 = status2;
locked3 = status3;
locked4 = status4;
locked5 = status5;
For the OnDestroy method --
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString(savelocked,status1);
prefsEditor.putString(savelocked2,status2);
prefsEditor.putString(savelocked3,status3);
prefsEditor.putString(savelocked4,status4);
prefsEditor.putString(savelocked5,status5);
prefsEditor.apply();
For the actual code involved with the issue also in the onCreate--
final ImageView buy = (ImageView) findViewById(R.id.imageView26);
final ImageView car = (ImageView) findViewById(R.id.imageView9);
car.setTag("sportscar1");
final ImageView use = (ImageView) findViewById(R.id.imageView5);
buy.setImageResource(R.drawable.bull);
if(car.getTag()=="sportscar1") {
if (locked.equals("Locked")) {
use.setImageResource(R.drawable.bull2);
}
}else{use.setImageResource(R.drawable.use);}
final ImageView right = (ImageView) findViewById(R.id.imageView25);
final ImageView left = (ImageView) findViewById(R.id.imageView24);
buy.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (car.getTag() == "sportscar1") {
if (locked.equals("Locked") && GameView.coinz >= 1) {
status1="Unlocked";
Colors.color1 = "sportscar1";
GameView.coinz = GameView.coinz - 1;
Toast.makeText(context, " - 1 Car Token",
Toast.LENGTH_SHORT).show();
Toast.makeText(context, "You just bought the sports car!",
Toast.LENGTH_LONG).show();
use.setImageResource(R.drawable.use);
buy.setImageResource(R.drawable.bull);
} else {
Toast.makeText(context, " Not enough Car Tokens.",
Toast.LENGTH_SHORT).show();
}
}
});
left.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (car.getTag() == "sportscar1") {
buy.setImageResource(R.drawable.bull);
use.setImageResource(R.drawable.bull2);
car.setTag("sportscar2");
if (locked2.equals("Locked")) {
car.setImageResource(R.drawable.sportscar2_locked);
buy.setImageResource(R.drawable.buy);
use.setImageResource(R.drawable.bull2);
} else if (locked2.equals("Unlocked")) {
car.setImageResource(R.drawable.sportscar2_show);
buy.setImageResource(R.drawable.bull);
use.setImageResource(R.drawable.use);
}
}
});
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (car.getTag() == "sportscar1") {
buy.setImageResource(R.drawable.bull);
use.setImageResource(R.drawable.bull2);
car.setTag("thecar1");
if (locked5.equals("Locked")) {
car.setImageResource(R.drawable.thecar1_locked);
buy.setImageResource(R.drawable.buy);
use.setImageResource(R.drawable.bull2);
} else if (locked5.equals("Unlocked")) {
car.setImageResource(R.drawable.thecar1_show);
buy.setImageResource(R.drawable.bull);
use.setImageResource(R.drawable.use);
}
}
}
});
use.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (car.getTag() == "sportscar2") {
Colors.color1 = "sportscar2";
status2="Unlocked";
Toast.makeText(context, "You just selected the second sports car!",
Toast.LENGTH_LONG).show();
buy.setImageResource(R.drawable.bull);
use.setImageResource(R.drawable.use);
}
}
});
Variables instantiated(At Activity beginning) --
private String savelocked = "Locked or Unlocked";
private String savelocked2 = "Locked or Unlocked";
private String savelocked3 = "Locked or Unlocked";
private String savelocked4 = "Locked or Unlocked";
private String savelocked5 = "Locked or Unlocked";
public String status1 = "Locked";
public String status3 = "Locked";
public String status2 = "Locked";
public String status4 = "Locked";
public String status5 = "Locked";
public String locked;
public String locked2;
public String locked3;
public String locked4;
public String locked5;
private static SharedPreferences prefs;
Thanks for any help. I did not have this problem earlier when I was using ==, and this time I am using .equals(). Sorry for the lengthy code. And please help. All help is appreciated. Thank you for your time.
Edit-- A lot of the code has been cut-off and the code above refers to the general meaning.
Edit 2 -- Variables instantiated also included.
Again Thanks for Your Help.
(sorry to add this as an answer, but I don't have enough rep to add a comment)
There are other lines where you should be using "equals()" too:
In every place where you have:
if (car.getTag()=="sportscar1") { ...
(or "sportscar2", or whatever string) you should be using
if (car.getTag().equals("sportscar1")) { ...
Keep in mind that strings in Java are also objects, thus they cannot be compared like that, because they aren't the exact same instance of the same object. Therefore you should be using .equals()
You're welcome, Game Programmer. The error you were getting means that a preference variable with that name is there but, for some reason, the data type it's finding isn't a string.
Changing the code in your onCreate to:
status1 = prefs.getString("savelocked", "Locked");
and the ones in your onDestroy to:
prefsEditor.putString("savelocked", status1);
just stores and retrieves the same information in a different preference variable. Honestly, from what I can see in your code, I still have no idea why you were getting that error in the first place. But if it works, it works.

- java.lang.NullPointerException - setText on null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
This is what I'm trying to do for several hours:
I've got a MainActivity.java file (listing below) and a fragment_start.xml file with a start button. Tapping the start-button should display the activity_main.xml file with points-/round- and countdown-Textviews. It doesn't work and this is what is happening:
The logcat tells me:
PID: 1240 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
The emulator displays: Unfortunately, GAME has stopped.
Necessary to mention that I'm rather new in programming?
Thanks for any advice!
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener {
private int points;
private int round;
private int countdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showStartFragment();
}
private void newGame () {
points=0;
round=1;
initRound();
}
private void initRound() {
countdown = 10;
update();
}
private void update () {
fillTextView(R.id.points, Integer.toString(points));
fillTextView(R.id.round, Integer.toString(round));
fillTextView(R.id.countdown, Integer.toString(countdown * 1000));
}
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text);
}
private void showStartFragment() {
ViewGroup container = (ViewGroup) findViewById(R.id.container);
container.removeAllViews();
container.addView(
getLayoutInflater().inflate(R.layout.fragment_start, null) );
container.findViewById(R.id.start).setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.start) {
startGame();
}
}
public void startGame() {
newGame();
}
}
The problem is the tv.setText(text). The variable tv is probably null and you call the setText method on that null, which you can't.
My guess that the problem is on the findViewById method, but it's not here, so I can't tell more, without the code.
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null
But from your code, I can't find why this method returns null. Try to track down,
what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method.
From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text);
}
If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById(), and the actual exception is thrown when you try to call a function setText() on null. You should post your XML for R.layout.activity_main, as it's hard to tell where things went wrong just by looking at your code.
More reading on null pointers: What is a NullPointerException, and how do I fix it?

Categories

Resources