使用asynctask的Android中的Web服务

时间:2016-07-13 18:38:59

标签: android android-asynctask android-webservice

我有一个名为" DataBase"的课程。延伸" AsyncTask"用于远程数据库

public class DataBase extends AsyncTask<String, Void, String>{   

ArrayList<String> arrayList = new ArrayList<>();
String nameJson;

public DataBase(String nameJson) {
    this.nameJson = nameJson;        
}

protected String doInBackground(String... params) {

    String jsonPhp = params[1];

        try {
            String line = null;
            URL url = new URL(jsonPhp);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();

            if(bufferedReader != null){
                while((line = bufferedReader.readLine()) != null){
                    stringBuffer.append(line+" 'n");
                }
            }else{
                return null;
            }

            return stringBuffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    return null;
}

protected void onPostExecute(String s) {
   arrayData(s);
}

public void arrayData(String buffer){
    try {
        JSONArray jsonArray = new JSONArray(buffer);
        JSONObject jsonObject = null;
        arrayList.clear();

        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            String dataList = jsonObject.getString(nameJson.toString());
            arrayList.add(dataList);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

public ArrayList<String> getArrayList() {
    return arrayList;
  }

 }

MainActivity

public class MainActivity {

String adress = "http//....../.php"; //Here is the address of the file containing the json
ListView listView;
ArrayAdapter myArray;

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

    listView = (ListView) findViewById(R.id.my_list);
    final DataBase dataBase = new DataBase("names");
    dataBase.execute(address); //This line of code is executed as if it were the last line of code, as if it were placed under the setAdapter.      
    myArray = dataBase.getArrayList(); // and for that reason this line return null

    ArrayAdapter arrayAdapter;
    arrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_expandable_list_item_1,myArray);
    listView.setAdapter(arrayAdapter);


 }
}

当我在代码行中运行我的项目&#34; dataBase.Execute();&#34;在&#34; MainActivity&#34; class,不执行代码块&#34; doInBackground&#34;立即,但在完成执行&#34; MainActivity&#34;中的所有代码行后运行,因此在代码行&#34; myArray = dataBase.getArrayList();&#34;它返回null。

我想知道如何制作&#34; dataBase.Execute();&#34;立即运行,不要继续使用&#34; MainActivity&#34;代码,直到它运行&#34; doInBackground&#34;,然后代码行&#34; myArray = dataBase.getArrayList(); &#34;不返回null

2 个答案:

答案 0 :(得分:1)

这不会起作用,因为它会阻止你的主线程。您需要使Activity响应异步事件。这是使用AsyncTask或手动管理Thread的完整原因。网络操作是阻止操作,这可能需要很长时间(例如网络速度慢)。如果阻塞主线程,系统将在您的进程上声明ANR并将其终止。

以下是关于AsyncTask的文章,有助于解释其工作原理:http://po.st/Cei3m2

答案 1 :(得分:0)

问题是因为您的代码在后台线程中运行, 并且您必须在DataBase的myArray = dataBase.getArrayList();内添加此行doInBackground

我修改了你的代码,并以正确的方式添加

public class DataBase extends AsyncTask{
    ArrayList<String> arrayList = new ArrayList<>();
    String nameJson;

    public DataBase(String nameJson) {
        this.nameJson = nameJson;
    }

    protected String doInBackground(String... params) {

        String jsonPhp = params[1];

        try {
            String line = null;
            URL url = new URL(jsonPhp);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();

            if(bufferedReader != null){
                while((line = bufferedReader.readLine()) != null){
                    stringBuffer.append(line+" 'n");
                }
            }else{
                return null;
            }

            return stringBuffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String s) {
        arrayData(s);

        // you have to add the code after get the data because this task runs in another trhead
        //now it will not be null
        ArrayAdapter arrayAdapter;
        arrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_expandable_list_item_1,myArray);
        listView.setAdapter(arrayAdapter);
    }

    public void arrayData(String buffer){
        try {
            JSONArray jsonArray = new JSONArray(buffer);
            JSONObject jsonObject = null;
            arrayList.clear();

            for(int i=0;i<jsonArray.length();i++){
                jsonObject = jsonArray.getJSONObject(i);
                String dataList = jsonObject.getString(nameJson.toString());
                arrayList.add(dataList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public ArrayList<String> getArrayList() {
        return arrayList;
    }
}