Nick Winans
Nick Winans

Reputation: 174

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

I am making an app that predicts the winner of a soccer game. I am new to android programming and all recyclerview tutorials are a little confusing, but I need to put all my information from each user prediction into a cardview, so I transfered all my xml code into java, but when I got to this activity, it says Shutting down VM right away, and I do not get any Log messages I put in. All the users data from the predictions are in an SQLite database, which is read for the information. Below are my java and xml files, I would like to eventually not have to use the xml file, if possible.

History Activity Java File:

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 File for History 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>

Any suggestions? Again I am new to Android Development, so it may be something really easy. Thank you in advance.

Upvotes: 0

Views: 138

Answers (2)

Nivaldo Bondan&#231;a
Nivaldo Bondan&#231;a

Reputation: 863

All your view instances should be created in the onCreated() method.

Since your doing

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

The views are being created in the Activity default constructor, when it is not ready to inflate view. Therefore it breaks the application.

So... What should you do?

I suggest you should to move the here referenced code + the call TypedArray imgs = getResources().obtainTypedArray(R.array.images); into the onCreate() method, when the Context of the Activity is ready.

Hope this helps.

Upvotes: 0

Eugen Pechanec
Eugen Pechanec

Reputation: 38223

Keep only declarations of these

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);

and move the assignments (and initialization) at least after super.onCreate().

Upvotes: 1

Related Questions