简体   繁体   English

Android:应用程序从一个活动跳到第二个活动,而对第一个活动没有任何操作

[英]Android: App jumping from one activity to second without any action on first activity

I have created a basic feedback app in which the main activity ( MainActivity.java ) records the name of the customer and the rating (1-5) in the form of imageViews and sends the data to firebase.我创建了一个基本的反馈应用程序,其中主要活动( MainActivity.java )以 imageViews 的形式记录客户的姓名和评分(1-5),并将数据发送到 firebase。

My second activity ( Score.java ) simply aggregates the ratings from all the customers in firebase.我的第二个活动( Score.java )只是汇总了 firebase 中所有客户的评分。

My issue is the app on startup directly jumps to Score.java without collecting the feedback from the customer.我的问题是应用程序在启动时直接跳转到Score.java没有收集客户的反馈。 Ps I am using Intent to jump between the activities. Ps 我正在使用Intent在活动之间跳转。

Here is the code:这是代码:

MainActivity-主要活动-

package com.example.feedback;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;    
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import static android.os.SystemClock.sleep;

public class MainActivity extends AppCompatActivity {

    EditText name;
    ImageView oneStar, twoStar, threeStar, fourStar, fiveStar;
    Intent intent;
    FirebaseDatabase rootNode;
    DatabaseReference reference;

    public void displayScore() {
        intent = new Intent(getApplicationContext(), Score.class);
        startActivity(intent);
    }
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
        getSupportActionBar().hide(); // hide the title bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
        setContentView(R.layout.activity_main);
        name =  findViewById(R.id.editTextPersonName);
        oneStar =  findViewById(R.id.imageView1);
        twoStar =  findViewById(R.id.imageView2);
        threeStar = findViewById(R.id.imageView3);
        fourStar =  findViewById(R.id.imageView4);
        fiveStar =  findViewById(R.id.imageView5);
        oneStar.setTag(1);
        twoStar.setTag(2);
        threeStar.setTag(3);
        fourStar.setTag(4);
        fiveStar.setTag(5);

        oneStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.length() == 0){
                    name.setError("Please enter your full name.");
                }
                else {
                    name.setError(null);
                    rootNode = FirebaseDatabase.getInstance();
                    reference = rootNode.getReference().child("Users");
                    //Fetch all values
                    String username = name.getText().toString();
                    String value = view.getTag().toString();
                    int rating = Integer.parseInt(value);
                    UserHelper helper = new UserHelper(username,rating);
                    reference.child(username).setValue(helper);
                    Toast.makeText(MainActivity.this, "Feedback submitted successfully!", Toast.LENGTH_SHORT).show();
                    sleep(200);
                    displayScore();
                }
            }
        });

        twoStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.length() == 0){
                    name.setError("Please enter your full name.");
                }
                else {
                    name.setError(null);
                    rootNode = FirebaseDatabase.getInstance();
                    reference = rootNode.getReference().child("Users");
                    //Fetch all values
                    String username = name.getText().toString();
                    String value = view.getTag().toString();
                    int rating = Integer.parseInt(value);
                    UserHelper helper = new UserHelper(username,rating);
                    reference.child(username).setValue(helper);
                    Toast.makeText(MainActivity.this, "Feedback submitted successfully!", Toast.LENGTH_SHORT).show();
                    displayScore();
                }
            }
        });

        threeStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.length() == 0){
                    name.setError("Please enter your full name.");
                }
                else {
                    name.setError(null);
                    rootNode = FirebaseDatabase.getInstance();
                    reference = rootNode.getReference().child("Users");
                    //Fetch all values
                    String username = name.getText().toString();
                    String value = view.getTag().toString();
                    int rating = Integer.parseInt(value);
                    UserHelper helper = new UserHelper(username,rating);
                    reference.child(username).setValue(helper);
                    Toast.makeText(MainActivity.this, "Feedback submitted successfully!", Toast.LENGTH_SHORT).show();
                    displayScore();
                }
            }
        });

        fourStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.length() == 0){
                    name.setError("Please enter your full name.");
                }
                else {
                    name.setError(null);
                    rootNode = FirebaseDatabase.getInstance();
                    reference = rootNode.getReference().child("Users");
                    //Fetch all values
                    String username = name.getText().toString();
                    String value = view.getTag().toString();
                    int rating = Integer.parseInt(value);
                    UserHelper helper = new UserHelper(username,rating);
                    reference.child(username).setValue(helper);
                    Toast.makeText(MainActivity.this, "Feedback submitted successfully!", Toast.LENGTH_SHORT).show();
                    displayScore();
                }
            }
        });

        fiveStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.length() == 0){
                    name.setError("Please enter your full name.");
                }
                else {
                    name.setError(null);
                    rootNode = FirebaseDatabase.getInstance();
                    reference = rootNode.getReference().child("Users");
                    //Fetch all values
                    String username = name.getText().toString();
                    String value = view.getTag().toString();
                    int rating = Integer.parseInt(value);
                    UserHelper helper = new UserHelper(username,rating);
                    reference.child(username).setValue(helper);
                    Toast.makeText(MainActivity.this, "Feedback submitted successfully!", Toast.LENGTH_SHORT).show();
                    displayScore();
                }
            }
        });
    }
}

Score.java -分数.java -

package com.example.feedback;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class Score extends AppCompatActivity {

    TextView avgScore;
    DatabaseReference dbRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
        getSupportActionBar().hide(); // hide the title bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
        setContentView(R.layout.score);
        avgScore = findViewById(R.id.textView2);
        dbRef = FirebaseDatabase.getInstance().getReference().child("Users");

        scoreRealTime();
    }

    public void scoreRealTime() {
        dbRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                double total = 0;
                for (DataSnapshot ds : snapshot.getChildren()){
                    double values = Double.parseDouble(ds.child("rating").getValue().toString());
                    total = total + values;
                }
                double average = (double) total / snapshot.getChildrenCount();
                avgScore.setText(String.format("%.2f", average));
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }
}

AndroidManifest.xml - AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.feedback">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="landscape">
        </activity>
        <activity
            android:name=".Score"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I'm assuming there is something very simple, wrong with displayScore() but can't seem to figure it out.我假设displayScore()有一些非常简单的错误,但似乎无法弄清楚。 Thanks in advance.提前致谢。

You have kept Score Activity as launcher activity.您已将Score活动保留为启动器活动。 So use MainActivity as Launcher activity like this所以像这样使用MainActivity作为 Launcher 活动

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".Score"
        android:screenOrientation="landscape">
    </activity>
    <activity
        android:name=".MainActivity"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And one more suggestion there is a lot of code duplication you can make a function to upload rating and call it in else block of onClickListner还有一个建议是有很多代码重复,你可以制作一个 function 来上传评级并在onClickListner的 else 块中调用它

You have kept the second activity as the launcher activity, that is why android overlooks your MainActivity.java您将第二个活动保留为启动器活动,这就是 android 忽略您的 MainActivity.java 的原因

You should change your Manifest as您应该将清单更改为

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".Score"
        android:screenOrientation="landscape">
    </activity>
    <activity
        android:name=".MainActivity"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

and there can be one more improvement in your app, you can add recyclerView instead of 5 buttons, That will make your code shorter.并且您的应用程序可以再进行一项改进,您可以添加 recyclerView 而不是 5 个按钮,这将使您的代码更短。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将操作栏添加到第二个活动而不是第一个活动 - How to add action bar to second activity but not to first one 将数据从第二个活动移到第一个活动 - Move Data from Second Activity to first Activity 在Android中向“第二个活动”添加了一个“返回至第一个”按钮。 现在,导航到第二个活动时应用程序崩溃 - Added A Button To Second Activity In Android To Return To First. Now App Crashes When Navigating To Second Activity 将数据从第二个活动发送到第一个活动不适用于Android - Sending data from a second activity to the first one doesn't work Android 从Android应用程序的操作栏中选择菜单选项时,将数据从一个活动传递到另一个活动 - Passing data from one activity to another when choosing a menu option from action bar in Android app 从第二个活动开始第一个活动的“第二个”选项卡片段 - Starting Second tab fragment of first activity from second activity 来自第二个活动的Android Asynctask - Android Asynctask from second activity ActionBar出现在第一个活动中,但没有出现在第二个活动中 - ActionBar is appearing in the first activity but not appearing the second one Android 应用程序仍然保持活动状态,没有任何活动 - Android App still remain active without any activity 启动Second Activity而不是First android - Start Second Activity instead of First android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM