在InterstitialAd练习中,按一下按钮的onClick,调用tellJoke()。 tellJoke()调用AsyncTask。
在AsyncTask中,参数大小为0,得到IndexOutOfBundException,因此context为null。
MainActivity.java
公共类MainActivity扩展了AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_TAG, "after setting activity main");
}
public static void tellJoke(View view){
new EndpointsAsyncTask().execute();
}
}
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
InterstitialAd mInterstitialAd;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container, false);
AdView mAdView = (AdView) root.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
//interstitialAd part starts here
mInterstitialAd = new InterstitialAd(getActivity());
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
requestNewInterstitial();
MainActivity.tellJoke(getView());
}
});
return root;
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mInterstitialAd.loadAd(adRequest);
}
}
EndpointsAsyncTask.java
public class EndpointsAsyncTask extends AsyncTask<Context, Void, String> {
private static String LOG_TAG = EndpointsAsyncTask.class.getSimpleName();
private static MyApi myApiService = null;
private Context context ;
@Override
protected String doInBackground(Context... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("https://build-it-bigger.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
if (params != null) {
context = params[0];
}
try {
return myApiService.fetchJoke().execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
if (context != null) {
Intent intent = new Intent(context, JokeDisplayActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, result);
context.startActivity(intent);
}
}}
请帮助,我在哪里做错了?并建议其他方法。
最佳答案
只需在调用execute
时为您的AsyncTask提供参数(也可以删除static):
public void tellJoke(View view){
new EndpointsAsyncTask().execute(getActivity());
}
this
指的是活动,因此实现了Context
接口(如果从活动中调用)。编辑:
将您的
tellJoke
方法移到Fragment上,并像这样调用它:tellJoke();
注意,由于您位于片段中,因此现在您不传递
this
而是传递getActivity()
。关于android - 得到IndexOutOfBoundException:数组范围0到0无效,因此context = null,因此App崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38108764/