D
D
Dmitry Laptev2015-04-12 16:46:43
Android
Dmitry Laptev, 2015-04-12 16:46:43

AsyncTasks how to figure it out?

I am writing again, because I didn't quite understand last time. I did tasks in the UI thread, I was sent to read about AsyncTask. I read it, but it still doesn’t work, At startup, a window just flies out, unfortunately the application has stopped, I’ll quote the code

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.*;
import android.view.MenuItem;
import android.widget.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.*;


public class MainActivity extends ActionBarActivity {

    EditText comp;
    TextView res;
    Button calc;

    String fin;


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

        //Связь с лэйаутом
        comp = (EditText) findViewById(R.id.comp);
        res = (TextView) findViewById(R.id.res);
        calc = (Button) findViewById(R.id.calc);
        calc.setOnClickListener((View.OnClickListener) this);

    }
//Само задание
public class Calcs extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        String str = null;

        try {

            LineNumberReader lnr = new LineNumberReader(new BufferedReader(
                    new FileReader("http://picpost.w.pw/elements.txt")));
            res.setText("Insert Compound");
            String inp = comp.getText().toString();
            Pattern p1 = Pattern.compile(inp + " = (\\w+).*");
            while (((str = lnr.readLine()) != null)) {
                Matcher m = p1.matcher(str);
                if (m.find()) {
                    fin = m.group(1);
                    res.setText(fin);
                }
            }
            lnr.close();
        } catch (IOException e) {
            res.setText("I/O Exception!");
        }
        return null;
    }
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public void onclick(View v) {
    Calcs task = new Calcs();
        task.execute();
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Chernysh, 2015-04-12
@i_am_mrld

You cannot access the UI from the doInBackground method, and you have a call to TextView
and EditText
. You can access the UI from the onPreExecute and onPostExecute methods of the AsyncTask class. For example,

public class Calcs extends AsyncTask<Void, Void, String> {
    @Override
     protected void onPreExecute() {
            super.onPreExecute();

            res.setText("Insert Compound");
     }

    @Override
    protected String doInBackground(Void... voids) {
       String str = null;
        .........
        ...............
       //после всех действий возвращаете результат, в вашем случае строку результата, которую нужно отобразить в TextView
        return str; 
    }

    @Override
    protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //result - это то, что возвращает метод doInBackground            

            //обновляете UI
             res.setText(result);
    }
    
}

A string from an EditText can be passed to the doInBackground input:
More details with an example in the AsyncTask doc

A
anyd3v, 2015-04-12
@anyd3v

doInBackground is not running on the UI thread, so there will be no UI update. To do this, you need to overload another method
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
Following
Not surprisingly, you can’t do it, you can’t even read the standard help for working with AsyncTask or find it in Google. developer.android.com/reference/android/os/AsyncTa...
Why are you crashing, do you think everyone will rush to copy and compile your class?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question