我是Java的初学者,我需要你的帮助,我想在3个从布局返回后加载插页式广告(recipe_detail.xml)
首先我将解释这个源代码的结构:
[文件][1]
[recipe_list.xml][2]
菜谱列表.java :
package com.villagetagh.halawiyatlaid;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.villagetagh.halawiyatlaid.R;
public class RecipesList extends Activity {
private InterstitialAd interstitial;
ImageView imgAbout, imgSearchNav;
Button btnSearch;
EditText edtSearch;
LinearLayout lytSearchForm;
ListView listRecipes;
ProgressBar prgLoading;
TextView txtAlert;
AdView ads;
String RecipeNameKeyword = "";
static DBHelper dbhelper;
ArrayList<ArrayList<Object>> data;
ListAdapter la;
static int[] id;
static String[] RecipeName;
static String[] Preview;
/** This class is used to create custom listview */
static class ListAdapter extends BaseAdapter {
private LayoutInflater inflater;
private Context ctx;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
ctx = context;
}
public int getCount() {
// TODO Auto-generated method stub
return RecipeName.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.txtRecipeName = (TextView) convertView.findViewById(R.id.txtRecipeName);
holder.imgPreview = (ImageView) convertView.findViewById(R.id.imgPreview);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtRecipeName.setText(RecipeName[position]);
int imagePreview = ctx.getResources().getIdentifier(Preview[position], "drawable", ctx.getPackageName());
holder.imgPreview.setImageResource(imagePreview);
return convertView;
}
static class ViewHolder {
TextView txtRecipeName;
ImageView imgPreview;
}
}
**/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipes_list);
// Create the interstitial.
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-7676436769471442/4006302017");
// Create ad request.
AdRequest adRequest2 = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest2);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
displayInterstitial();
}
}, 30000);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice("6EF305EAD8E00C37BCACF9D2505F9CCF").build();
mAdView.loadAd(adRequest);**
dbhelper = new DBHelper(this);
la = new ListAdapter(this);
imgAbout = (ImageView) findViewById(R.id.imgAbout);
imgSearchNav = (ImageView) findViewById(R.id.imgSearchNav);
btnSearch = (Button) findViewById(R.id.btnSearch);
edtSearch = (EditText) findViewById(R.id.edtSearch);
lytSearchForm = (LinearLayout) findViewById(R.id.lytSearchForm);
listRecipes = (ListView) findViewById(R.id.listRecipes);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// ads = (AdView) findViewById(R.id.ads);
//Ads.loadAds(ads);
/**
* when this app's installed at the first time, code below will
* copy database stored in assets to
* /data/data/com.recipes.app/databases/
*/
try {
dbhelper.createDataBase();
}catch(IOException ioe){
throw new Error("Unable to create database");
}
/** then, the database will be open to use */
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
new getDataTask().execute();
listRecipes.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
/**
* when one of item in the list is clicked, this app will access
* RecipeDetail.class. it also send id value to that class
*/
Intent i = new Intent(RecipesList.this, RecipeDetail.class);
i.putExtra("id_for_detail", id[position]);
startActivity(i);
}
});
imgSearchNav.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/** this code is used to hide and show the search form */
if(lytSearchForm.getVisibility() == 8){
lytSearchForm.setVisibility(0);
imgSearchNav.setImageResource(R.drawable.nav_down);
}else{
lytSearchForm.setVisibility(8);
imgSearchNav.setImageResource(R.drawable.nav_up);
}
}
});
btnSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
RecipeNameKeyword = edtSearch.getText().toString();
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
new getDataTask().execute();
}
});
imgAbout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/** when about icon is clicked, it will access AboutApp.class */
Intent i = new Intent(RecipesList.this, AboutApp.class);
startActivity(i);
}
});
}
/** this class is used to handle thread */
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDataFromDatabase(RecipeNameKeyword);
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if(id.length > 0){
listRecipes.setVisibility(0);
listRecipes.setAdapter(la);
}else{
txtAlert.setVisibility(0);
}
dbhelper.close();
}
}
/**
* this code is used to get data from database and store them
* to array attributes
*/
public void getDataFromDatabase(String RecipeNameKeyword){
data = dbhelper.getAllData(RecipeNameKeyword);
id = new int[data.size()];
RecipeName = new String[data.size()];
Preview = new String[data.size()];
for(int i=0;i<data.size();i++){
ArrayList<Object> row = data.get(i);
id[i] = Integer.parseInt(row.get(0).toString());
RecipeName[i] = row.get(1).toString();
Preview[i] = row.get(2).toString().trim();
}
}
@Override
public void onDestroy() {
if (ads != null) {
ads.destroy();
}
super.onDestroy();
}
@Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
//Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
[recipe_Detail.xml][3]
RecipesDetail.java :
package com.villagetagh.halawiyatlaid;
import java.util.ArrayList;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.villagetagh.halawiyatlaid.R;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
public class RecipeDetail extends Activity {
TextView txtRecipeName, txtPrepTime, txtCookTime, txtServes, txtSummary, txtIngredients, txtDirections;
ImageView imgPreviewDetail;
ProgressBar prgLoading;
ScrollView sclDetail;
DBHelper dbhelper;
ArrayList<Object> data;
int id;
String RecipeName, Preview, PrepTime, CookTime, Serves, Summary, Ingredients, Directions;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe_detail);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice("6EF305EAD8E00C37BCACF9D2505F9CCF").build();
mAdView.loadAd(adRequest);
Intent i_get = getIntent();
id = i_get.getIntExtra("id_for_detail", 0);
dbhelper = new DBHelper(this);
txtRecipeName = (TextView) findViewById(R.id.txtRecipeName);
txtPrepTime = (TextView) findViewById(R.id.txtPrepTime);
txtCookTime = (TextView) findViewById(R.id.txtCookTime);
txtServes = (TextView) findViewById(R.id.txtServes);
txtSummary = (TextView) findViewById(R.id.txtSummary);
txtIngredients = (TextView) findViewById(R.id.txtIngredients);
txtDirections = (TextView) findViewById(R.id.txtDirections);
imgPreviewDetail = (ImageView) findViewById(R.id.imgPreviewDetail);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
sclDetail = (ScrollView) findViewById(R.id.sclDetail);
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
new getDetailTask().execute();
}
/** this class is used to handle thread */
public class getDetailTask extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDetailFromDatabase();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
sclDetail.setVisibility(0);
showDetail();
dbhelper.close();
}
}
/**
* this code is used to get data from database and store them
* to attributes
*/
public void getDetailFromDatabase(){
ArrayList<Object> row = dbhelper.getDetail(id);
RecipeName = row.get(0).toString();
Preview = row.get(1).toString();
PrepTime = row.get(2).toString();
CookTime = row.get(3).toString();
Serves = row.get(4).toString();
Summary = row.get(5).toString();
Ingredients = row.get(6).toString();
Directions = row.get(7).toString();
}
/**
* then set those values of attributes to the views
*/
public void showDetail(){
txtRecipeName.setText(RecipeName);
int imagePreview = getResources().getIdentifier(Preview, "drawable", getPackageName());
imgPreviewDetail.setImageResource(imagePreview);
txtPrepTime.setText("Prep time : "+PrepTime);
txtCookTime.setText("Cook time : "+CookTime);
txtServes.setText("Serves : "+Serves);
txtSummary.setText(Html.fromHtml(Summary));
txtIngredients.setText(Html.fromHtml(Ingredients));
txtDirections.setText(Html.fromHtml(Directions));
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
DB_Helper.java :
package com.villagetagh.halawiyatlaid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DBHelper extends SQLiteOpenHelper{
private static String DB_PATH = "/data/data/com.villagetagh.halawiyatlaid/databases/";
private final static String DB_NAME = "db_recipes";
public final static int DB_VERSION = 1;
public static SQLiteDatabase db;
private final Context context;
private final String TABLE_NAME = "tbl_recipes";
private final String ID = "id";
private final String RECIPE_NAME = "recipe_name";
private final String IMAGE_PREVIEW = "image_preview";
private final String PREP_TIME = "prepare_time";
private final String COOK_TIME = "cook_time";
private final String SERVES = "serves";
private final String SUMMARY = "summary";
private final String INGREDIENTS = "ingredients";
private final String DIRECTIONS = "directions";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
SQLiteDatabase db_Read = null;
if(dbExist){
//do nothing - database already exist
deleteDataBase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}else{
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void deleteDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
dbFile.delete();
}
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public void close() {
db.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/** this code is used to get all data from database */
public ArrayList<ArrayList<Object>> getAllData(String RecipeNameKeyword){
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor = null;
if(RecipeNameKeyword.equals("")){
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID, RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()){
do{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}else{
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID, RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
RECIPE_NAME +" LIKE '%"+RecipeNameKeyword+"%'",
null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()){
do{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
return dataArrays;
}
/** this code is used to get data from database base on id value */
public ArrayList<Object> getDetail(long id){
ArrayList<Object> rowArray = new ArrayList<Object>();
Cursor cursor;
try{
cursor = db.query(
TABLE_NAME,
new String[] {RECIPE_NAME, IMAGE_PREVIEW, PREP_TIME, COOK_TIME, SERVES, SUMMARY, INGREDIENTS, DIRECTIONS},
ID + "=" + id,
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()){
do{
rowArray.add(cursor.getString(0));
rowArray.add(cursor.getString(1));
rowArray.add(cursor.getString(2));
rowArray.add(cursor.getString(3));
rowArray.add(cursor.getString(4));
rowArray.add(cursor.getString(5));
rowArray.add(cursor.getString(6));
rowArray.add(cursor.getString(7));
}
while (cursor.moveToNext());
}
cursor.close();
}
catch (SQLException e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
return rowArray;
}
}
[1]: https://i.stack.imgur.com/pYeU0.png
[2]: https://i.stack.imgur.com/ggmBu.png
[3]: https://i.stack.imgur.com/80F5j.png
最简单的方法是将用户转到配方详细信息的次数存储在列表活动的 int 变量中,并在用户每次转到详细信息页面(在 onItemClickListener 中)时递增该次数。
然后,您需要覆盖 RecipeList 页面的 onResume 以检查此值,如果匹配,如果它是您想要的值,则显示广告并将其重置为 0。
@Override
public void onResume() {
if (detailViews >= 3) {
// show ad
detailViews = 0;
}
}