如何在onPostExecute方法之外使用变量?

时间:2020-07-28 08:20:00

标签: java android

我在Web服务器上有一个MySQL数据库,我在应用程序中从该数据库读取数据,但是在读取变量之后,无法在onPostExecute之外使用“ volt”变量。我尝试使用适配器,但是我不能像适配器一样使用适配器中的数据,只是我可以添加到列表视图中。到目前为止,我还没有找到解决我的问题的方法。 我希望你能帮助我。

 package com.example.wifis;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    ArrayAdapter<String> adapter;
   // int tomb []={};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView=(ListView)findViewById(R.id.list_item);
        adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        listView.setAdapter(adapter);
        new Conection().execute();
    }





    class  Conection extends AsyncTask<String, String, String>{


        @Override
        public String doInBackground(String... strings) {
            String result="";
            String host="http://localhost/store/cars.php";
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(host));
                HttpResponse response =  client.execute(request);
                BufferedReader reader= new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                StringBuffer stringBuffer= new StringBuffer("");

                String line = "";
                while ((line = reader.readLine()) !=null ){
                    stringBuffer.append(line);
                    break;
                }
                reader.close();
                result = stringBuffer.toString();
            }
            catch (Exception e){
                return  new String("There exeption: "+ e.getMessage());
            }


            return result;
        }
        @Override
        public void onPostExecute(String result){
 //           Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
            JSONObject jsonResult = null;
            try {
                jsonResult = new JSONObject(result);
                int success = jsonResult.getInt("success");
                if(success==1){


                        JSONArray cars = jsonResult.getJSONArray("cars");
                        JSONObject car = cars.getJSONObject(0);
                        int id = car.getInt("id");
                        int volt = car.getInt("szam");
                        String line = id + "-" + volt;
                        adapter.add(line);
                      //  tomb[0]=szam;



                }else{
                    Toast.makeText(getApplicationContext(), "NOT OK ", Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }


        }



    }
}

1 个答案:

答案 0 :(得分:0)

正如我试图解释in my post here

您尝试访问的值不是同步的,这意味着您的代码不会自上而下执行。 AsyncTask在某个时候返回值 。我们不知道何时会返回,但是当它返回值时,您将可以在onPostExecute中访问它。这意味着您可以使用在那里接收到的值,并且仅在那里使用,因为这是您实际接收到这些值的唯一地方。

要将此值返回到您的主要活动中,您可以执行以下操作:

创建界面

public interface MyCallback {
    void myResult(YourResultType output); //here, i believe this will be string for your specific case
}

此接口允许我们在收到新类时将收到的值移动到另一个类

下一步

转到您的AsyncTask类,并将接口MyCallback声明为变量:

public class MyAsyncTask extends AsyncTask<String, String, String> {
  public MyCallback callback = null;

    @Override
    protected void onPostExecute(String result) {
      callback.myResult(result);
    }
 }

@Override
    protected void onPostExecute(String result) {
      callback.myResult(result);
    }

现在进行主要活动:

public class MainActivity implements MyCallback {
  MyAsyncTask asyncTask = new MyAsyncTask();

  @Override
  public void onCreate(Bundle savedInstanceState) {

     //set your listener to this class
     asyncTask.callback = this;

     //execute the async task 
     asyncTask.execute();
  }

  //this overrides the implemented method from asyncTask
  @Override
  void myResult(YourResultType output){
     //Here you will receive the result returned from the async task
   }
 }

请注意,async tasks are deprecated

还请注意,我的Java很生锈,我很幸运,这些天只使用了kotlin,如有任何错误,请随时纠正我:)