Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按钮setOnClickListener函数调用出现问题_Java_Android_Firebase_Firebase Realtime Database - Fatal编程技术网

Java 按钮setOnClickListener函数调用出现问题

Java 按钮setOnClickListener函数调用出现问题,java,android,firebase,firebase-realtime-database,Java,Android,Firebase,Firebase Realtime Database,我的代码中的一个按钮的setOnClickListener方法有问题。基本上,我在setOnClickListener方法中调用了一个typeFinder,但是第一次按下按钮时,值不会得到更新。我使用了调试器,根据我的理解,即使调用了该函数,程序实际上也不会执行该函数,直到setOnClickListener之后,这意味着当我第二次按下按钮时,它具有上一次按下按钮时显示的正确值。我也尝试过使用TypesTask(如页面底部的注释部分所示),但这样做的结果是相同的。 下面是该类的代码: impor

我的代码中的一个按钮的setOnClickListener方法有问题。基本上,我在setOnClickListener方法中调用了一个typeFinder,但是第一次按下按钮时,值不会得到更新。我使用了调试器,根据我的理解,即使调用了该函数,程序实际上也不会执行该函数,直到setOnClickListener之后,这意味着当我第二次按下按钮时,它具有上一次按下按钮时显示的正确值。我也尝试过使用TypesTask(如页面底部的注释部分所示),但这样做的结果是相同的。 下面是该类的代码:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private DatabaseReference myRef;
    private ArrayList<String> recipesList = new ArrayList<String>();
    private String[] types = {"pizza", "ice cream", "sandwich", "salad", "steak"};
    private void typeFinder(String type) {
        myRef.orderByChild("type").equalTo(type).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                String word = "";
                boolean wordAdded = false;
                String value = dataSnapshot.getValue().toString();
                for (int i = 0; i < value.length(); i++) {
                    if (wordAdded == false) {
                        if (value.charAt(i) == '=') {
                            recipesList.add(word);
                            wordAdded = true;
                            word = "";
                        } else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
                            if (word.length() == 0 && value.charAt(i) == ' ') {
                            } else {
                                word = word + value.charAt(i);
                            }
                        }
                    }
                    if (value.charAt(i) == '}')
                        if (i + 2 == value.length()) {
                            wordAdded = false;
                            break;
                        } else
                            wordAdded = false;
                }
            }
            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        myRef = FirebaseDatabase.getInstance().getReference();
        Button saladsB = (Button) findViewById(R.id.saladButton);
        Button pizzaB = (Button) findViewById(R.id.pizzaButton);
        Button iceCreamB = (Button) findViewById(R.id.iceCreamButton);
        Button steakB = (Button) findViewById(R.id.steakButton);
        Button sandwichB = (Button) findViewById(R.id.sandwichButton);
        final TextView testTextView = (TextView) findViewById(R.id.test_text_view);
        testTextView.setText(Integer.toString(recipesList.size()));
        super.onCreate(savedInstanceState);
        saladsB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // recipesList.clear();
             //   t.typeFinder("salad")
                  typeFinder("salad");
           //     new TypesTask().execute("salad");
                String recipes = "";
                for (int i = 0; i < recipesList.size(); i++) {
                    recipes = recipes + recipesList.get(i) + "\n";
                }
                testTextView.setText(recipes);
              //  Intent intent = new Intent(MainActivity.this, ListviewActivity.class);
              //  intent.putStringArrayListExtra("FOOD_LIST", recipesList);
              //  startActivity(intent);
            }
        });
    }
    /*
    public class TypesTask extends AsyncTask<String, Void, Void> {
        @Override
        protected void onPreExecute() {
            myRef = FirebaseDatabase.getInstance().getReference();
        }
        @Override
        protected Void doInBackground(String... params) {
            typeFinder(params[0]);
            return null;
        }
    }
    */
}
导入android.os.AsyncTask;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.TextView;
导入com.google.firebase.database.DataSnapshot;
导入com.google.firebase.database.DatabaseError;
导入com.google.firebase.database.DatabaseReference;
导入com.google.firebase.database.FirebaseDatabase;
导入com.google.firebase.database.ValueEventListener;
导入java.util.ArrayList;
公共类MainActivity扩展了AppCompatActivity{
私有静态最终字符串TAG=“MainActivity”;
私有数据库参考myRef;
私有ArrayList recipesList=新ArrayList();
私有字符串[]类型={“比萨饼”、“冰淇淋”、“三明治”、“沙拉”、“牛排”};
私有void类型查找器(字符串类型){
myRef.orderByChild(“类型”).equalTo(类型).addValueEventListener(新的ValueEventListener(){
@凌驾
公共void onDataChange(DataSnapshot DataSnapshot){
//使用初始值调用此方法一次,然后再次调用
//每当更新此位置的数据时。
字串=”;
boolean-wordAdded=false;
字符串值=dataSnapshot.getValue().toString();
对于(int i=0;i
这是页面的xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.thevash.recipes.MainActivity">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="810dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="458dp"
        android:orientation="horizontal"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1">


        <TextView
            android:id="@+id/test_text_view"
            android:layout_width="585dp"
            android:layout_height="248dp"
            android:layout_weight="1"
            android:text="TextView"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="-377dp" />
    </LinearLayout>

    <Button
        android:id="@+id/saladButton"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:text="Salads"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="5dp"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/pizzaButton"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:text="Pizzas"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="52dp"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/iceCreamButton"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:text="ice cream"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        app:layout_constraintRight_toRightOf="@+id/pizzaButton"
        app:layout_constraintTop_toBottomOf="@+id/pizzaButton"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="@+id/pizzaButton" />

    <Button
        android:id="@+id/steakButton"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:text="steaks"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        app:layout_constraintRight_toRightOf="@+id/iceCreamButton"
        app:layout_constraintTop_toBottomOf="@+id/iceCreamButton"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="@+id/iceCreamButton" />

    <Button
        android:id="@+id/sandwichButton"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:text="sandwiches"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        app:layout_constraintRight_toRightOf="@+id/steakButton"
        app:layout_constraintTop_toBottomOf="@+id/steakButton"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="@+id/steakButton" />
</android.support.constraint.ConstraintLayout>

您可以使用TypesTask完成此操作,但需要修改TypesTask类,如下所示

public class TypesTask extends AsyncTask<String, Void, Void> {
    @Override
    protected void onPreExecute() {
        myRef = FirebaseDatabase.getInstance().getReference();
    }
    @Override
    protected Void doInBackground(String... params) {
        typeFinder(params[0]);
        return null;
    }
   @Override
   onPostExecute(Void result){
      String recipes = "";
      for (int i = 0; i < recipesList.size(); i++) {
                recipes = recipes + recipesList.get(i) + "\n";
      }
      testTextView.setText(recipes);
   }
}

构建reciepeList的方法是异步调用。在调用EventListener的OnSuccess()之后,需要更新对Ui的更改。将Ui更新代码重新定位到OnDataChange,请参见下面的代码:

private void typeFinder(String type) {
    myRef.orderByChild("type").equalTo(type).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String word = "";
            boolean wordAdded = false;
            String value = dataSnapshot.getValue().toString();
            for (int i = 0; i < value.length(); i++) {
                if (wordAdded == false) {
                    if (value.charAt(i) == '=') {
                        recipesList.add(word);
                        wordAdded = true;
                        word = "";
                    } else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
                        if (word.length() == 0 && value.charAt(i) == ' ') {
                        } else {
                            word = word + value.charAt(i);
                        }
                    }
                }
                if (value.charAt(i) == '}')
                    if (i + 2 == value.length()) {
                        wordAdded = false;
                        break;
                    } else
                        wordAdded = false;
            }

         // Update the Ui Here
           String recipes = "";
            for (int i = 0; i < recipesList.size(); i++) {
                recipes = recipes + recipesList.get(i) + "\n";
            }
            this.testTextView.setText(recipes);
        }
        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
}
private void类型查找器(字符串类型){
myRef.orderByChild(“类型”).equalTo(类型).addValueEventListener(新的ValueEventListener(){
@凌驾
公共void onDataChange(DataSnapshot DataSnapshot){
//使用初始值调用此方法一次,然后再次调用
//每当更新此位置的数据时。
字串=”;
boolean-wordAdded=false;
字符串值=dataSnapshot.getValue().toString();
private void typeFinder(String type) {
    myRef.orderByChild("type").equalTo(type).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String word = "";
            boolean wordAdded = false;
            String value = dataSnapshot.getValue().toString();
            for (int i = 0; i < value.length(); i++) {
                if (wordAdded == false) {
                    if (value.charAt(i) == '=') {
                        recipesList.add(word);
                        wordAdded = true;
                        word = "";
                    } else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
                        if (word.length() == 0 && value.charAt(i) == ' ') {
                        } else {
                            word = word + value.charAt(i);
                        }
                    }
                }
                if (value.charAt(i) == '}')
                    if (i + 2 == value.length()) {
                        wordAdded = false;
                        break;
                    } else
                        wordAdded = false;
            }

         // Update the Ui Here
           String recipes = "";
            for (int i = 0; i < recipesList.size(); i++) {
                recipes = recipes + recipesList.get(i) + "\n";
            }
            this.testTextView.setText(recipes);
        }
        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
}