我知道这个问题曾被问到好几次,但我看到答案总是会因代码而改变。
所以,我有GameActivity从全局" info"中的数据库中检索信息。变量,即String []。
接下来,我需要将当前片段替换为与按下的按钮相关的另一个片段(请参阅方法" trueAnswer"" falseAnswer"),并设置该新片段的两个TextView使用" info"中检索到的信息;字符串数组。
问题在于我能够在创建活动时在onStart()方法的第一个片段中第一次设置信息,但后来看起来就像" info"数组为空,因为" if"在方法" trueAnswer"和" falseAnswer"不起作用,当我尝试使用方法" changeText(String,String)"在新片段中设置TextView时,应用程序崩溃并返回NullPointerExeption。
我无法真正看到代码中的错误在哪里,所以我在这里发布我的方法和logCat,希望这对你也有所帮助。
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:(与FragmentCorrect相同的代码,但具有不同的片段布局)。
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
非常感谢您提前
答案 0 :(得分:2)
您正在创建一个新片段,并立即在其上调用changeText()
。创建片段视图,调用生命周期回调(如onCreateView()
)的片段事务尚未运行。
考虑使用bundle将参数传递给fragmens,而不是直接在片段生命周期之外调用片段方法。
答案 1 :(得分:1)
您正在致电
newFragment.changeText(info[1], info[0]);
太快了。您需要等到片段附加到Activity
。您的观点为空。
还可以使用.equals
来比较字符串而不是==
。
if(info[2].equals("1"))
了解片段生命周期
http://developer.android.com/guide/components/fragments.html
进一步添加laalto发布的内容