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();
}
}
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);
}
}
new Calcs().execute(editTextString);
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.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.