Android 应用程序在移动到使用 java 创建布局后停止工作

Android app stops working after moving to using creating the layout with java

我正在开发一款预测足球比赛获胜者的应用。我是 android 编程的新手,所有的 recyclerview 教程都有些混乱,但我需要将每个用户预测的所有信息放入 cardview,所以我将所有 xml 代码转移到 java,但是当我看到这个 activity 时,它说立即关闭虚拟机,我没有收到我输入的任何日志消息。预测中的所有用户数据都在 SQLite 数据库中,它是阅读信息。下面是我的 java 和 xml 文件,如果可能的话,我希望最终不必使用 xml 文件。

历史记录ActivityJava文件:

package com.winansbros.soccerpredictor;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;


public class History extends Activity {

TextView historyTextView;

Context CTX = this;

AdView mAdView;
AdRequest adRequest;

Button clearButton;
Button tipsButton;

StringBuilder sb;
DatabaseOperations DOP;

Integer team1image = 1;
Integer team2image = 1;

AdView adview = new AdView(CTX);
Button clearHistory = new Button(CTX);
Button tips = new Button(CTX);
RelativeLayout mainrl = new RelativeLayout(CTX);

TypedArray imgs = getResources().obtainTypedArray(R.array.images);

public void onCreate(final Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    DOP = new DatabaseOperations(CTX);
    Cursor CR = DOP.getInformation(DOP);
    CR.moveToFirst();

    if( CR != null && CR.moveToFirst() ){

        RelativeLayout.LayoutParams mainrlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mainrl.setLayoutParams(mainrlp);

        String adid = getResources().getString(R.string.banner_ad_unit_id);

        RelativeLayout.LayoutParams adviewlayoutparams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        adviewlayoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        adviewlayoutparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

        RelativeLayout.LayoutParams clearHistoryLP = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        clearHistoryLP.addRule(RelativeLayout.ABOVE, adview.getId());
        clearHistoryLP.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

        RelativeLayout.LayoutParams tipsbuttonlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tipsbuttonlp.addRule(RelativeLayout.ABOVE, adview.getId());
        tipsbuttonlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        adview.setAdSize(AdSize.BANNER);
        adview.setAdUnitId(adid);

        adview.setLayoutParams(adviewlayoutparams);
        clearHistory.setLayoutParams(clearHistoryLP);
        tips.setLayoutParams(tipsbuttonlp);

        clearHistory.setText("Clear History");
        tips.setText("Tips");

        mainrl.addView(adview);
        mainrl.addView(clearHistory);
        mainrl.addView(tips);

        setContentView(mainrl);

        CR.close();

        getHistory();

    } else
    {
        setContentView(R.layout.activity_history);
        clearButton = (Button) findViewById(R.id.clearSQLite);
        tipsButton = (Button) findViewById(R.id.TipsButton);

    }



    mAdView = (AdView) this.findViewById(R.id.adView);
    adRequest = new AdRequest.Builder()
            .addTestDevice("8AC41E108CD62B7703FF28358AEEC8BC")
            .build();
    mAdView.loadAd(adRequest);

    clearButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            DatabaseOperations DOB = new DatabaseOperations(CTX);
            DOB.DeleteInformation(CTX);
            DOB.close();
            finish();
        }
    });

    //sb = new StringBuilder();

    historyTextView = (TextView) findViewById(R.id.historyText);
    historyTextView.setMovementMethod(new ScrollingMovementMethod());


    tipsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), TipsActivity.class);
            startActivity(intent);
        }
    });

    DOP.close();
}

public void getHistory() {
    Log.i("GetHistory", "Initialized");

    Cursor CR = DOP.getInformation(DOP);
    CR.moveToFirst();
    List<String> winners = new ArrayList<>();
    List<String> hometeams = new ArrayList<>();
    List<String> awayteams = new ArrayList<>();
    List<String> scores = new ArrayList<>();

    do {
        winners.add(CR.getString(0));
        hometeams.add(CR.getString(1));
        awayteams.add(CR.getString(2));
        scores.add(CR.getString(3));
        Log.d("Cloud Files", "OBJECT ID SET");

    } while (CR.moveToNext());

    Log.d("GetHistory", "Lists all set");

    setImages(hometeams, awayteams);

    Log.d("GetHistory", "Images set");
    int size = winners.size();
    Log.d("Cloud Files", Integer.toString(size));

    for (int i = 0; i < size; i++) {
        Log.d("GetHistory", "Starting For Loop");
        CardView cv = new CardView(CTX);
        RelativeLayout ll = new RelativeLayout(CTX);
        TextView team1name = new TextView(CTX);
        TextView team2name = new TextView(CTX);
        ImageView team1imageview = new ImageView(CTX);
        ImageView team2imageview = new ImageView(CTX);
        TextView cardscore = new TextView(CTX);

        Log.d("GetHistory", "Views set up");

        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        RelativeLayout.LayoutParams imageview1 = new RelativeLayout.LayoutParams(60, 60);
        imageview1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        imageview1.addRule(RelativeLayout.ALIGN_PARENT_START);
        imageview1.addRule(RelativeLayout.CENTER_VERTICAL);

        RelativeLayout.LayoutParams imageview2 = new RelativeLayout.LayoutParams(60, 60);
        imageview2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imageview2.addRule(RelativeLayout.ALIGN_PARENT_END);
        imageview2.addRule(RelativeLayout.CENTER_VERTICAL);

        RelativeLayout.LayoutParams textview1 = new RelativeLayout.LayoutParams(100, RelativeLayout.LayoutParams.WRAP_CONTENT);
        textview1.addRule(RelativeLayout.CENTER_VERTICAL);
        textview1.addRule(RelativeLayout.RIGHT_OF, team1imageview.getId());
        textview1.addRule(RelativeLayout.END_OF, team1imageview.getId());
        textview1.addRule(RelativeLayout.BELOW, team2name.getId());

        RelativeLayout.LayoutParams textview2 = new RelativeLayout.LayoutParams(100, RelativeLayout.LayoutParams.WRAP_CONTENT);
        textview2.addRule(RelativeLayout.CENTER_VERTICAL);
        textview2.addRule(RelativeLayout.LEFT_OF, team2imageview.getId());
        textview2.addRule(RelativeLayout.START_OF, team2imageview.getId());
        textview2.addRule(RelativeLayout.BELOW, team2name.getId());

        RelativeLayout.LayoutParams textview3 = new RelativeLayout.LayoutParams(20, RelativeLayout.LayoutParams.WRAP_CONTENT);
        textview3.addRule(RelativeLayout.CENTER_VERTICAL);
        textview3.addRule(RelativeLayout.RIGHT_OF, team1name.getId());
        textview3.addRule(RelativeLayout.END_OF, team1name.getId());
        textview3.addRule(RelativeLayout.BELOW, team2name.getId());

        Log.d("GetHistory", "Layout params set");

        team1name.setText(hometeams.get(i));
        team2name.setText(awayteams.get(i));
        team1imageview.setImageResource(imgs.getResourceId(team1image, -1));
        cardscore.setText(scores.get(i));
        team2imageview.setImageResource(imgs.getResourceId(team2image, -1));

        team1imageview.setLayoutParams(imageview1);
        team2imageview.setLayoutParams(imageview2);
        team2name.setLayoutParams(textview1);
        team1name.setLayoutParams(textview2);
        cardscore.setLayoutParams(textview3);

        Log.d("GetHistory", "views set to parents");

        mainrl.addView(cv);
        cv.setLayoutParams(lp);
        ll.setLayoutParams(rlp);
        cv.addView(ll);
        ll.addView(team1imageview);
        ll.addView(team1name);
        ll.addView(team2imageview);
        ll.addView(team2name);
        ll.addView(cardscore);

        Log.d("GetHistory", "views set to objects");

        Log.d("GetHistory", "views values set");

        setContentView(mainrl);

        imgs.recycle();

        /**if (appendSeparator) sb.append("\n");
        appendSeparator = true;

        sb.append(hometeams.get(i));
        sb.append(" ");
        sb.append(scores.get(i));
        sb.append(" ");
        sb.append(awayteams.get(i));
        historyTextView.setText(sb.toString());*/
    }

}

public void setImages(List<String> hometeams, List<String> awayteams)
{
    String[] bplteams = new String[20];
    bplteams[0] = "Arsenal";
    bplteams[1] = "Aston Villa";
    bplteams[2] = "Burnley";
    bplteams[3] = "Chelsea";
    bplteams[4] = "Crystal Palace";
    bplteams[5] = "Everton";
    bplteams[6] = "Hull City";
    bplteams[7] = "Leicester City";
    bplteams[8] = "Liverpool";
    bplteams[9] = "Man City";
    bplteams[10] = "Man United";
    bplteams[11] = "Newcastle";
    bplteams[12] = "QPR";
    bplteams[13] = "Southampton";
    bplteams[14] = "Stoke City";
    bplteams[15] = "Sunderland";
    bplteams[16] = "Swansea City";
    bplteams[17] = "Tottenham";
    bplteams[18] = "West Brom";
    bplteams[19] = "West Ham";

    String[] laligateams = new String[20];

    laligateams[0] = "Almería";
    laligateams[1] = "Athletic Bilbao";
    laligateams[2] = "Athlético Madrid";
    laligateams[3] = "Barcalona";
    laligateams[4] = "Celta Vigo";
    laligateams[5] = "Córdoba";
    laligateams[6] = "Deportivo La Coruña";
    laligateams[7] = "Eibar";
    laligateams[8] = "Elche";
    laligateams[9] = "Espanyol";
    laligateams[10] = "Getafe";
    laligateams[11] = "Granada";
    laligateams[12] = "Levante";
    laligateams[13] = "Málaga";
    laligateams[14] = "Rayo Vallecano";
    laligateams[15] = "Real Madrid";
    laligateams[16] = "Real Sociedad";
    laligateams[17] = "Sevilla";
    laligateams[18] = "Valencia";
    laligateams[19] = "Villarreal";

    for (int i = 0; i < hometeams.size(); i++)
    {
        if (hometeams.get(i) == bplteams[i])
        {
            team1image = i;
        } else if (hometeams.get(i) == laligateams[i])
        {
            team1image = i;
        } else if (awayteams.get(i) == bplteams[i])
        {
            team1image = i;
        } else if (awayteams.get(i) == laligateams[i])
        {
            team2image = i;
        }

    }

}
}    

XML 历史文件 Activity:

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear History"
        android:id="@+id/clearSQLite"
        android:layout_above="@+id/adView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:width="150dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tips"
        android:id="@+id/TipsButton"
        android:width="150dp"
        android:layout_above="@+id/adView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>

    <android.support.v7.widget.CardView
        tools:context="com.winansbros.soccerpredictor.History"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        card_view:cardCornerRadius="4dp"
        card_view:cardElevation="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:id="@+id/team1imageview"
                android:layout_alignParentTop="true"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/team1name"
                android:layout_centerVertical="true"
                android:layout_below="@+id/team2name"
                android:layout_toRightOf="@+id/team1imageview"
                android:layout_toEndOf="@+id/team1imageview"
                android:width="100dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/card1score"
                android:width="20dp"
                android:layout_centerVertical="true"
                android:layout_alignTop="@+id/team1name"
                android:layout_toRightOf="@+id/team1name"
                android:layout_toEndOf="@+id/team1name"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/team2name"
                android:width="100dp"
                android:layout_centerVertical="true"
                android:layout_toLeftOf="@+id/team2imageview"
                android:layout_toStartOf="@+id/team2imageview"/>
            <ImageView
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:id="@+id/team2imageview"
                android:layout_centerVertical="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"/>

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>

有什么建议吗?同样,我是 Android 开发的新手,所以这可能真的很容易。提前谢谢你。

您的所有视图实例都应在 onCreated() 方法中创建。

自从你做了

AdView adview = new AdView(CTX);
Button clearHistory = new Button(CTX);
Button tips = new Button(CTX);
RelativeLayout mainrl = new RelativeLayout(CTX);

视图正在 Activity 默认构造函数中创建,当它还没有准备好膨胀视图时。因此它破坏了应用程序。

所以...你应该怎么做?

我建议您在 ActivityContext 准备就绪时,将此处引用的代码 + 调用 TypedArray imgs = getResources().obtainTypedArray(R.array.images); 移动到 onCreate() 方法中。

希望对您有所帮助。

只保留这些

的声明
AdView adview = new AdView(CTX);
Button clearHistory = new Button(CTX);
Button tips = new Button(CTX);
RelativeLayout mainrl = new RelativeLayout(CTX);

TypedArray imgs = getResources().obtainTypedArray(R.array.images);

并至少在 super.onCreate().

之后移动赋值(和初始化)