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

Nick Winans

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.

Nivaldo Bondança

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.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Android Service stops after the app is killed

分類Dev

NativeScript background service stops working after app closes

分類Dev

Java JTextPane auto-scroll stops working after selecting text

分類Dev

Android - AlarmManager is not working after app is closed

分類Dev

Android - AlarmManager is not working after app is closed

分類Dev

Android - AlarmManager is not working after app is closed

分類Dev

Collision detection system not working after porting from Java applet to Android app

分類Dev

Touchpad Problem - shortly after login, it stops working

分類Dev

Laravel Auth not working after moving to remove

分類Dev

Android service stop working after I run another app/game

分類Dev

When I run app in android studio app store in internal memory.after moving also it doesn't move to sd card

分類Dev

Moving adMob ads to the bottom of Relative Layout crashes the app

分類Dev

selenium chrome driver stops working after publish application

分類Dev

Vscode auto format code stops working after few runs

分類Dev

Zurb Foundation Offcanvas Menu stops working after toggling programmatically

分類Dev

Calling VBScript procedure stops working after adding jQuery to HTA

分類Dev

Why Google Pay stops working when my app is installed?

分類Dev

Android Studio AndroidManifest not found after moving project

分類Dev

Creating a table layout with column depends on spinner in Android

分類Dev

Xamarin Forms Android app crashes after creating a class object during event handler

分類Dev

Creating and using annotation in java

分類Dev

Android google maps v2 execute asynctask when user stops moving the camera

分類Dev

android: app stops and then crashes when the screen goes off

分類Dev

Creating a search bar in the permanent layout (app.html.eex)

分類Dev

GridView using Table Layout Android

分類Dev

Node pipe stops working

分類Dev

Program compiles, but then stops working

分類Dev

16.04, Network stops working

分類Dev

Accordion is not working in my android app

Related 関連記事

  1. 1

    Android Service stops after the app is killed

  2. 2

    NativeScript background service stops working after app closes

  3. 3

    Java JTextPane auto-scroll stops working after selecting text

  4. 4

    Android - AlarmManager is not working after app is closed

  5. 5

    Android - AlarmManager is not working after app is closed

  6. 6

    Android - AlarmManager is not working after app is closed

  7. 7

    Collision detection system not working after porting from Java applet to Android app

  8. 8

    Touchpad Problem - shortly after login, it stops working

  9. 9

    Laravel Auth not working after moving to remove

  10. 10

    Android service stop working after I run another app/game

  11. 11

    When I run app in android studio app store in internal memory.after moving also it doesn't move to sd card

  12. 12

    Moving adMob ads to the bottom of Relative Layout crashes the app

  13. 13

    selenium chrome driver stops working after publish application

  14. 14

    Vscode auto format code stops working after few runs

  15. 15

    Zurb Foundation Offcanvas Menu stops working after toggling programmatically

  16. 16

    Calling VBScript procedure stops working after adding jQuery to HTA

  17. 17

    Why Google Pay stops working when my app is installed?

  18. 18

    Android Studio AndroidManifest not found after moving project

  19. 19

    Creating a table layout with column depends on spinner in Android

  20. 20

    Xamarin Forms Android app crashes after creating a class object during event handler

  21. 21

    Creating and using annotation in java

  22. 22

    Android google maps v2 execute asynctask when user stops moving the camera

  23. 23

    android: app stops and then crashes when the screen goes off

  24. 24

    Creating a search bar in the permanent layout (app.html.eex)

  25. 25

    GridView using Table Layout Android

  26. 26

    Node pipe stops working

  27. 27

    Program compiles, but then stops working

  28. 28

    16.04, Network stops working

  29. 29

    Accordion is not working in my android app

ホットタグ

アーカイブ