Web service in Android using asynctask

I have a class called "DataBase" extends "AsyncTask" for the use of remote database

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);


 }
}

When I run my project in the line of code "dataBase.Execute ();" in the"MainActivity" class, does not execute the code block "doInBackground" immediately, but runs after finishes executing all lines of code that are in the "MainActivity", and for this reason in the line of code "myArray = dataBase.getArrayList ();" it returns null.

I want to know how to make the "dataBase.Execute ();" run immediately and do not continue with the other lines of the "MainActivity" code, until it run the "doInBackground", and then the line of code" myArray = dataBase.getArrayList (); "no return null

Upvotes: 0

Views: 692

Answers (2)

diogojme
diogojme

Reputation: 2359

The problem is because your code runs in a background thread, and you have to add this line myArray = dataBase.getArrayList(); inside the doInBackground of DataBase.

I modified your code adding it the right way

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;
    }
}

Upvotes: 0

Larry Schiefer
Larry Schiefer

Reputation: 15775

This will not work as it would block your main thread. You need to make your Activity respond to asynchronous events. This is the entire reason for using an AsyncTask or manually managed Thread. Network operations are blocking operations which can take a long time (e.g. slow network.) If you block on your main thread the system will declare ANR on your process and kill it.

Here's an article on AsyncTask which will help explain how it works: http://po.st/Cei3m2

Upvotes: 1

Related Questions