I have a question about using Android asynctask.

Asked 2 years ago, Updated 2 years ago, 85 views

I am making an example of importing mysqldb contents in a list format through Android and php communication.

During the execution of the activity, the following Async Tasks are rotated to obtain data through php communication and displayed in the list view.

private void getDatas(){
    class getTask extends AsyncTask<String,Void,String>{

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(MainActivity.this, "get Datas", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(String... params) {
            try{

                URL url1 = new URL("http://rkdanswns.esy.es/wju/answers.php");
                URL url = new URL("http://rkdanswns.esy.es/wju/problems.php");

                HttpURLConnection mUrlConnection = (HttpURLConnection) url.openConnection();
                HttpURLConnection mUrlConnection1 = (HttpURLConnection) url1.openConnection();

                mUrlConnection.setDoInput(true);
                mUrlConnection1.setDoInput(true);

                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("UTF-8")));
                while(true){
                    final String line = reader.readLine();
                    if(line==null){
                        break;
                    }else{
                        word = line.split("<br>");
                        Log.e("ee",line);
                    }

                    if(isCancelled()){
                        break;
                    }
                }

                BufferedReader reader1 = new BufferedReader(new InputStreamReader(url1.openStream(), Charset.forName("UTF-8")));
                while(true){
                    final String line = reader1.readLine();
                    if(line==null){
                        break;
                    }else{
                        answer = line.split("<br>");
                    }

                    if(isCancelled()){
                        break;
                    }
                }

                cancel(true);
            } } catch (MalformedURLException e) {
                e.printStackTrace();
            } } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    getTask get = new getTask();
    get.execute();

}

public void show(){
    class dataToList extends AsyncTask<String,Void,String>{

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            data = new ArrayList<>();
            for(int i=0; i<word.length; i++){
                ListViewItem item = new ListViewItem(word[i],answer[i]);
                data.add(item);
            }
            adapter = new ListViewAdapter(MainActivity.this,R.layout.listview_item,data);
            wordList.setAdapter(adapter);

        }

        @Override
        protected String doInBackground(String... params) {
            return null;
        }
    }
    dataToList list = new dataToList();
    list.execute();
}

I made an add button to add db as follows, and I made a button called refresh to reload the list view after adding data.

Button refresh;
Button add;



        add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,addingActivity.class);
            startActivityForResult(intent,1);
        }
    });

When you click the add button, you will be moved to the add activity.

In the activity, the value is entered through two editTexts and returned to the main, and the input value is taken and the value is sent to php through AsyncTask as follows to add the data in db.

private void addProblem() {
    class addTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {

                w = URLEncoder.encode(w, "UTF-8");
                a = URLEncoder.encode(a, "UTF-8");

                URL url = new URL("http://rkdanswns.esy.es/wju/addProblem.php?problem=" + w + "&mean=" + a);
                HttpURLConnection mUrlConnection = (HttpURLConnection) url.openConnection();
                mUrlConnection.setDoInput(true);

                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();
                InputStream is = new BufferedInputStream(mUrlConnection.getInputStream());

                String line;
                while (true) {
                    br = new BufferedReader(new InputStreamReader(is));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                        Log.i("request info ", line);
                    }

                    if(isCancelled()) {
                        Toast.makeText(MainActivity.this, "inputted", Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
            } } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } } catch (MalformedURLException e) {
                e.printStackTrace();
            } } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancel(true);
        }
    }
    addTask task = new addTask();
    task.execute();
}

You will add it, and you will press the update and refresh button to display it in the list view as in the added content. Press the refresh button

private void getDatas(){
    class getTask extends AsyncTask<String,Void,String>{

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(MainActivity.this, "get Datas", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(String... params) {
            try{

                URL url1 = new URL("http://rkdanswns.esy.es/wju/answers.php");
                URL url = new URL("http://rkdanswns.esy.es/wju/problems.php");

                HttpURLConnection mUrlConnection = (HttpURLConnection) url.openConnection();
                HttpURLConnection mUrlConnection1 = (HttpURLConnection) url1.openConnection();

                mUrlConnection.setDoInput(true);
                mUrlConnection1.setDoInput(true);

                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("UTF-8")));
                while(true){
                    final String line = reader.readLine();
                    if(line==null){
                        break;
                    }else{
                        word = line.split("<br>");
                        Log.e("ee",line);
                    }

                    if(isCancelled()){
                        break;
                    }
                }

                BufferedReader reader1 = new BufferedReader(new InputStreamReader(url1.openStream(), Charset.forName("UTF-8")));
                while(true){
                    final String line = reader1.readLine();
                    if(line==null){
                        break;
                    }else{
                        answer = line.split("<br>");
                    }

                    if(isCancelled()){
                        break;
                    }
                }

                cancel(true);
            } } catch (MalformedURLException e) {
                e.printStackTrace();
            } } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    getTask get = new getTask();
    get.execute();

}

public void reShow(){
    class dataToList extends AsyncTask<String,Void,String>{

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            data = new ArrayList<>();
            for(int i=0; i<word.length; i++){
                ListViewItem item = new ListViewItem(word[i],answer[i]);
                data.add(item);
            }
            adapter = new ListViewAdapter(MainActivity.this,R.layout.listview_item,data);
            wordList.setAdapter(adapter);

            cancel(true);
        }

        @Override
        protected String doInBackground(String... params) {
            return null;
        }
    }
    dataToList list = new dataToList();
    list.execute();
}

The list view should be updated using the following methods, but the following logs appear and cannot be updated.

12-28 02:48:13.161 10172-10187/com.example.cracking.problemeditor I/art: Background sticky concurrent mark sweep GC freed 3419(5MB) AllocSpace objects, 488(7MB) LOS objects, 29% free, 19MB/27MB, paused 2.950ms total 107.414ms

12-28 02:48:15.441 10172-10187/com.example.cracking.problemeditor W/art: Suspending all threads took: 9.508ms

12-28 02:48:15.441 10172-10187/com.example.cracking.problemeditor I/art: Background sticky concurrent mark sweep GC freed 434(768KB) AllocSpace objects, 62(992KB) LOS objects, 30% free, 18MB/26MB, paused 10.439ms total 18.610ms

If you add data through phpMyadmin and press the refresh button without adding it through the add button, the list view is updated and appears well.

Is there an error because I made a mistake using the thread? And how should I thread to communicate smoothly? Please.

android java thread

2022-09-22 20:13

1 Answers

I think it might have occurred because you didn't release the resources related to the I/O work.

Try closing the Buffered Reader InputStream.


2022-09-22 20:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.