The method findViewById(int) is undefined
I'm new to Android development and I'm trying to code a little app which allows me to grab an external JSON file and parse it. I got this to work, however it wont work if I try to execute it in the background as an AsyncTask
. Eclipse gives me the error
The method findViewById(int) is undefined for the type LongOperation
in this line:
TextView txtView1 = (TextView)findViewById(R.id.TextView01);
Here is my code:
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
}
class LongOperation extends AsyncTask<String, Void, String> {
private final Context LongOperation = null;
@Override
protected String doInBackground(String... params) {
try {
URL json = new URL("http://www.corps-marchia.de/jsontest.php");
URLConnection tc = json.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
JSONObject jo = (JSONObject) ja.get(0);
TextView txtView1 = (TextView)findViewById(R.id.TextView01);
txtView1.setText(jo.getString("text") + " - " + jo.getString("secondtest"));
}
} catch (MalformedURLException e) {
Toast.makeText(this.LongOperation, "Malformed URL Exception: " + e, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.开发者_运维知识库makeText(this.LongOperation, "IO Exception: " + e, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(this.LongOperation, "JSON Exception: " + e, Toast.LENGTH_LONG).show();
}
return null;
}
@Override
protected void onPostExecute(String result) {
}
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
ProgressDialog pd = new ProgressDialog(LongOperation);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
}
}
Any ideas on how to fix this?
Here is what you should do to make it work as you want. Use onPostExecude()
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation(this).execute();
}
}
class LongOperation extends AsyncTask<String, Void, String> {
private Main longOperationContext = null;
public LongOperation(Main context) {
longOperationContext = context;
Log.v("LongOper", "Konstuktor");
}
@Override
protected String doInBackground(String... params) {
Log.v("doInBackground", "inside");
StringBuilder sb = new StringBuilder();
try {
URL json = new URL("http://www.corps-marchia.de/jsontest.php");
URLConnection tc = json.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
JSONObject jo = (JSONObject) ja.get(0);
Log.v("line = ", "jo.getString() ="+jo.getString("text"));
sb.append(jo.getString("text") + " - " + jo.getString("secondtest")).append("\n");
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.v("Error", "URL exc");
} catch (IOException e) {
e.printStackTrace();
Log.v("ERROR", "IOEXECPTOIn");
} catch (JSONException e) {
e.printStackTrace();
Log.v("Error", "JsonException");
}
String result = sb.toString();
return result;
}
@Override
protected void onPostExecute(String result) {
Log.v("onPostExe", "result = "+result);
TextView txtView1 = (TextView)longOperationContext.findViewById(R.id.textView01);
txtView1.setText(result);
}
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
ProgressDialog pd = new ProgressDialog(longOperationContext);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
}
}
The implementation of AsyncTask
in one of the other answers is flawed. The progress dialog is being created every time within publishProgress
, and the reference to the dialog is not visible outside the method. Here is my attempt:
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
class LongOperation extends AsyncTask<String, Void, String> {
ProgressDialog pd = null;
TextView tv = null;
@Override
protected void onPreExecute(){
tv = Main.this.findViewById(R.id.textvewid);
pd = new ProgressDialog(Main.this);
pd.setMessage("Working...");
// setup rest of progress dialog
}
@Override
protected String doInBackground(String... params) {
//perform existing background task
return result;
}
@Override
protected void onPostExecute(String result){
pd.dismiss();
tv.setText(result);
}
}
}
You are trying to do something which won't work. First of all you are inside of a class that extends AsyncTask
so you won't have that method available as it is a method of the class Activity
.
The second problem is that you are trying to do UI stuff in a method that is not synchronized with the UI thread. That is nothing you would want to do.
Process your JSON response in the doInBackground
method and pass the result to the onPostExecute
method where you will be able to handle UI stuff as it is synchronized with the UI thread.
The current setup you have will not make it easier for you to handle what you are trying to do anyway. You could make your LongOperation
class a private class of your Activity
class and define the TextView
as a instance member. Grab it off the layout using findViewById
inside of your OnCreate
and modify (set text or whatever) inside the onPostExecute
method of your AsyncTask
.
I hope it is somewhat clear what I meant.
findViewById is method in Activity class. You should pass instance of your activity to your LongOperation when you create it. Then use that instance to call findViewById.
精彩评论