按钮setOnClickListener函数调用问题

时间:2017-11-23 01:41:02

标签: java android firebase firebase-realtime-database

我的代码中的一个按钮的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;
        }
    }
    */
}

这是页面的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>

3 个答案:

答案 0 :(得分:1)

您可以使用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);
   }
}

你的onClick应该是这样的

saladsB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          new TypesTask().execute("salad");

        }
    });

答案 1 :(得分:0)

构建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());
        }
    });
}

答案 2 :(得分:0)

正如评论中提到的,两个答案都提供了工作。我要么必须将UI更新添加到typeFinder函数本身,要么使用AsyncTask来更新onPostExecute方法中的UI。对于后者,我必须在行typeFinder(params [0])之后让程序进入休眠状态一秒钟,以便给它足够的时间来更新变量。