0

I know that this is question had been asked several time, but I saw that the answer always change in relation to the code.

So, I have GameActivity that retrieve informations from a database in the global "info" variable, that is a String[].

Next I need to replace the current fragment with another fragment in relation to the button pressed (see methods "trueAnswer" and "falseAnswer"), and set two TextViews of that new fragment with the informations retrieved in the "info" string array.

The problem is that I'm able to set the informations the first time, in the first fragment in the method onStart() when the activity is created, but then seems like the "info" array is empty, because the "if" in the methods "trueAnswer" and "falseAnswer" doesn't works, and when I try to set the TextViews in the new fragment with the method "changeText(String, String)", the app crashes and return a NullPointerExeption.

I can't really see where is the error in the code, so I post here my methods and the logCat, hoping that may help you too.

GameActivity:

import java.io.IOException;

import android.content.SharedPreferences;
import android.database.SQLException;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GameActivity extends ActionBarActivity {

public long n = 0;
public String[] info = new String[3];

DataBase myDbHelper = new DataBase(this);

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

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, new PlaceholderFragment()).commit();
    }
}

public void randomize(){

    n = Math.round((Math.random()*3)+1);

}

public String[] getDatabaseInfo(){

    myDbHelper.refresh();

    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
    throw new Error("NON HO CARICATO IL DATABASE TI PREGO SCUSAMI");
    }

    try {
        myDbHelper.openDataBase();
    }catch(SQLException sqle){
        throw sqle;
    }

    return info = myDbHelper.getQuestion(n);

}

@Override
public void onStart(){
    super.onStart();

    randomize();

    getDatabaseInfo();

    TextView d = (TextView)findViewById(R.id.question);
    d.setText(info[1]);

}

@Override
public void onResume(){
    super.onResume();

    // Controlla qual e il colore di sfondo nei settings e lo applica
    FrameLayout ll = (FrameLayout)findViewById(R.id.container);

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    int bgc = Color.parseColor(sharedPref.getString("background_color", "#000000"));

    if(bgc == Color.BLACK){
        TextView myTextView = (TextView)findViewById(R.id.question);
        TextView r = (TextView)findViewById(R.id.answer);
        myTextView.setTextColor(Color.WHITE);
        r.setTextColor(Color.GRAY);
    }

    ll.setBackgroundColor(bgc);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.game, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


public void trueAnswer(View view){

    if(info[2] == "1"){

        // Create new fragment and transaction
        FragmentCorrect newFragment = new FragmentCorrect();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.container, newFragment);

        // Commit the transaction
        transaction.commit();

        newFragment.changeText(info[1], info[0]);

    }else{

        // Create new fragment and transaction
        FragmentWrong newFragment = new FragmentWrong();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.container, newFragment);

        // Commit the transaction
        transaction.commit();

        newFragment.changeText(info[1], info[0]);
    }

}

public void falseAnswer(View view){

    if(info[2] == "1"){

        // Create new fragment and transaction
        FragmentCorrect newFragment = new FragmentCorrect();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.container, newFragment);

        // Commit the transaction
        transaction.commit();

        newFragment.changeText(info[1], info[0]);

    }else{

        // Create new fragment and transaction
        FragmentWrong newFragment = new FragmentWrong();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.container, newFragment);

        // Commit the transaction
        transaction.commit();

        newFragment.changeText(info[1], info[0]);
    }

}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_game, container,
                false);
        return rootView;
    }
}

}

FragmentCorrect:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentCorrect extends Fragment {

TextView questionTv, answerTv;

public FragmentCorrect() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_corretto, container,
            false);

    questionTv = (TextView)rootView.findViewById(R.id.question);
    answerTv = (TextView)rootView.findViewById(R.id.answer);

    return rootView;
}

public void changeText(String question, String answer){
    questionTv.setText(question);
    answerTv.setText(answer);
}

}

FragmentWrong:(same code as FragmentCorrect, but with a different fragment layout).

LogCat:

05-19 12:13:04.278: E/AndroidRuntime(16694): FATAL EXCEPTION: main
05-19 12:13:04.278: E/AndroidRuntime(16694): java.lang.IllegalStateException: Could not execute method of the activity
05-19 12:13:04.278: E/AndroidRuntime(16694):    at android.view.View$1.onClick(View.java:3704)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at android.view.View.performClick(View.java:4232)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at android.view.View$PerformClick.run(View.java:17298)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at android.os.Handler.handleCallback(Handler.java:615)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at android.os.Looper.loop(Looper.java:137)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at android.app.ActivityThread.main(ActivityThread.java:4921)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at java.lang.reflect.Method.invokeNative(Native Method)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at java.lang.reflect.Method.invoke(Method.java:511)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at dalvik.system.NativeStart.main(Native Method)
05-19 12:13:04.278: E/AndroidRuntime(16694): Caused by: java.lang.reflect.InvocationTargetException
05-19 12:13:04.278: E/AndroidRuntime(16694):    at java.lang.reflect.Method.invokeNative(Native Method)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at java.lang.reflect.Method.invoke(Method.java:511)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at   android.view.View$1.onClick(View.java:3699)
05-19 12:13:04.278: E/AndroidRuntime(16694):    ... 11 more
05-19 12:13:04.278: E/AndroidRuntime(16694): Caused by: java.lang.NullPointerException
05-19 12:13:04.278: E/AndroidRuntime(16694):    at    com.example.quizone_2.FragmentWrong.changeText(FragmentWrong.java:29)
05-19 12:13:04.278: E/AndroidRuntime(16694):    at com.example.quizone_2.GameActivity.trueAnswer(GameActivity.java:151)
05-19 12:13:04.278: E/AndroidRuntime(16694):    ... 14 more
05-19 12:13:06.403: I/Process(16694): Sending signal. PID: 16694 SIG: 9

Thank you very much in advance

Knorf
  • 101
  • 1
  • 11
  • post `FragmentWrong.java` line 29. use `.equals` to compare strings instead of `==` . `info[2].equals("1"))` – Raghunandan May 19 '14 at 10:17
  • possible your Textviews are null, wrong Ids bij findViewById, or your text (question / answer) can be null, this is not allowed, check both: textviews + string values. Something is null – Francesco verheye May 19 '14 at 10:19

2 Answers2

2

You're creating a new fragment and immediately calling changeText() on it. The fragment transaction that creates the fragment view, calling the lifecycle callbacks such as onCreateView(), has not yet been run.

Consider passing arguments to your fragmens using a bundle and not call fragment methods directly outside fragment lifecycle.

laalto
  • 150,114
  • 66
  • 286
  • 303
1

You are calling

newFragment.changeText(info[1], info[0]);

too soon. You need to wait till the Fragment is attached to the Activity. Your views are null.

Also use .equalsto compare strings instead of == .

if(info[2].equals("1")) 

Get to know Fragment lifecycle

http://developer.android.com/guide/components/fragments.html

Adding further to what laalto posted

Send data from activity to fragment in android

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256