简体   繁体   English

如何在方法外部访问String

[英]How to access String outside method

I'm trying to access a string outside the parse query, it's not working outside query but it works inside the query. 我正在尝试在解析查询外部访问一个字符串,它在查询外部无效,但在查询内部有效。 I declared the global variable and and tried to access it but it's still not working, instead of string it returns null. 我声明了全局变量并尝试访问它,但是它仍然不起作用,它不是字符串而是返回null。

I'm new to Java and Android so please forgive me if it's stupid question. 我是Java和Android的新手,所以如果这是个愚蠢的问题,请原谅我。

Any help would be appreciated. 任何帮助,将不胜感激。

public class ActivityQuiz extends AppCompatActivity {

ArrayList<String> answerList = new ArrayList<>();

int c=0;

String Answer = "correct";
String selectedOption;
public static String  checkAns;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);


    ParseQuery<ParseObject> query = ParseQuery.getQuery("Question");
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> questions, ParseException e) {
            if (e == null) {
                for (ParseObject question : questions) {                        
                    answerList.add(question.getString(Answer));
                     checkAns = getanswerList.get(c);
                     Log.d("String check",""+checkAns); //here it's working
                }

            } else {
                e.printStackTrace();
            }
        }

    });

    try{

    String checkanswer = checkAns ; // here returns null instead of string
    Log.d("String checkans",""+checkanswer);}
    catch (Exception e)
    {
        e.printStackTrace();
        Log.d("Error", "Error, Not Working");
    }
    }

There is very simple problem. 有一个非常简单的问题。 In first instance you are getting the value of checkAns from the data after hitting the API (in background). 首先,您在点击API后(在后台)从数据中获取checkAns的值。 So if data come from API it will be non-null. 因此,如果数据来自API,则它将为非null。

In later part, since the API response takes time, try-catch block will be executed before it sets value in checkAns So checkAns is equal to initialised value which is null . 在后面的部分中,由于API响应需要时间,因此try-catch块将在执行checkAns设置值之前执行,因此checkAns等于初始化值null

Ideally, you should use the value of checkAns only inside done() method. 理想情况下,应仅在done()方法内使用checkAns的值。

add your try-catch code inside ParseQuery like this: 像下面这样在ParseQuery中添加try-catch代码:

ParseQuery<ParseObject> query = ParseQuery.getQuery("Question");
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> questions, ParseException e) {
                if (e == null) {
                    for (ParseObject question : questions) {                        
                        answerList.add(question.getString(Answer));
                         checkAns = getanswerList.get(c);
                         Log.d("String check",""+checkAns); //here it's working

                         // ....Add your try catch code.....
                         try{
                              String checkanswer = checkAns ; // also working well
                              Log.d("String checkans",""+checkanswer);}
                              catch (Exception e)
                              {
                                  e.printStackTrace();
                                  Log.d("Error", "Error, Not Working");
                              }
                           }

                } else {
                    e.printStackTrace();
                }
            }

        });

That is normal behavior for asynchronous functions. 这是异步功能的正常行为。

By the time your try/catch block is executed checkanswer is still null because your query takes time to execute. 到您的try / catch块执行时,checkanswer仍然为null,因为查询需要花费一些时间来执行。 Once done() is executed you'll have your string. 一旦执行done(),您将拥有您的字符串。

If you must have your value in that block, you can sleep a second or two and check if checkanswer is no longer null. 如果您必须在那个区块中拥有自己的价值,则可以睡一两秒钟,然后检查checkanswer是否不再为null。 Be careful with sleeps as they will hang your program if you do use them in your main thread 注意睡眠,因为如果您在主线程中使用它们,它们将挂起您的程序

The Problem is that your try catch block will execute befor your query is done means the overriden done method will call and set the checkAns after you execute the try catch block. 问题是您的try catch块将在查询完成后执行,这意味着重写的done方法将在您执行try catch块后调用并设置checkAns。
If you will use the findInBackground method than make a method in your done method in which you will do all your stuff like: 如果您要使用findInBackground方法,而不是在done方法中创建一个方法,那么您将在其中进行所有操作,例如:

query.findInBackground(new FindCallback<ParseObject>() {
    @Override
    public void done(List<ParseObject> questions, ParseException e) {
      if (e == null) {
        successful(questions);

      } else {
        e.printStackTrace();
      }
    }

  });

  private void successful(List<ParseObject> questions){
    for (ParseObject question : questions) {
      answerList.add(question.getString(Answer));
      Log.d("String checkans",""+checkanswer);
    }
    String checkanswer = getanswerList.get(c);
  }

else you can use the find() method: 否则,您可以使用find()方法:

List<ParseObject> questions = query.find();

    for (ParseObject question : questions) {
      answerList.add(question.getString(Answer));
      Log.d("String checkans",""+checkanswer);
    }
    String checkanswer = getanswerList.get(c);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM