I have an Async Task getting me some data from the web. Async Task works fine and I want a Progress Dialog Spinner to be displayed while the data is being procured from the web.The Progress Dialog Spinner never shows up. Here is my code:
public class JsonHttpParsingActivity extends ListActivity{
private String jsonResult;
private ArrayList nameArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpConnection task = new HttpConnection(this);
AsyncTask<String,Void,String> taskResult = task.execute("Some URL...");
try {
jsonResult = taskResult.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.
.
More Code.....
}
}
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
setActivity(activity);
}
public void setActivity(Activity activity) {
m_activity = activity;
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress((int) ((values[0] / (float) values[1]) * 100));
};
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Thanks!
Instead of write a separate method setActivity(activity) (Non UI Thread scope)
for starting ProgressDialog put the code in onPreExecute() (UI Thread) of AsyncTask, Because you are trying to show it in non UI thread.
Try this,
protected HttpConnection(Activity activity) {
m_activity = activity;
}
Override
protected void onPreExecute(String result){
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
Call progress bar from onPreExecute() function
The following code is working fine and tested:
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Try calling the AsyncTask from another method in the activity. My guess is that right now, you call it in the onCreate method of the activity. Since the activity is still building, this can give you exceptions. A thing I once tried when I had this issue, is starting the asynchronous task from the onPostCreate method of the activity.
Related
I want to parse JSON from the Openweather API but after many iterations and debugging, my JSON string is not updating, I do not think that there is any problem still the temperatures( minTemperature and maxTemperature) and the name of the place(mPlace) is not set, also I logged the maxtemperature but the console is showing nothing please look into my code.
public class MainActivity extends AppCompatActivity {
private EditText placeText;
private Button enterPlaceButton;
private TextView minTemperature;
private TextView maxTemperature;
private TextView mPlace;
private static final String AppID ="56a5e01eba3af36a7a9b7b210a437d09";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Weather");
placeText = findViewById(R.id.myPlaceEditText);
enterPlaceButton = findViewById(R.id.enterPlace);
minTemperature = findViewById(R.id.minTemperature);
maxTemperature = findViewById(R.id.maxTemperature);
mPlace = findViewById(R.id.mPlace);
}
#Override
protected void onResume() {
final URL[] url = {null};
enterPlaceButton.setOnClickListener(v -> {
url[0] = makeUrl(placeText.getText().toString());
placeText.setText("");
});
if (url[0] != null) {
MyAsync myAsync = new MyAsync();
myAsync.execute(url[0]);
}
super.onResume();
}
public URL makeUrl(String place) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("http");
uriBuilder.authority("api.openweathermap.org/");
uriBuilder.appendPath("data");
uriBuilder.appendPath("2.5");
uriBuilder.appendPath("weather");
uriBuilder.appendQueryParameter("q",place);
uriBuilder.appendQueryParameter("appid",AppID);
try {
return new URL(uriBuilder.build().toString());
} catch (MalformedURLException e) {
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
public class MyAsync extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... urls) {
StringBuilder jsonResponseBuilder = new StringBuilder();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) urls[0].openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
jsonResponseBuilder.append(line);
line = bufferedReader.readLine();
}
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
Log.d(MyAsync.class.getName(),jsonResponseBuilder.toString());
return jsonResponseBuilder.toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
setDataFromJSON(s);
super.onPostExecute(s);
}
public void setDataFromJSON(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject getMainObject = jsonObject.getJSONObject("main");
String maxTemp = getMainObject.getString("temp_max");
Log.i(MainActivity.class.getName(), maxTemp);
maxTemperature.setText(maxTemp);
String minTemp = getMainObject.getString("temp_min");
minTemperature.setText(minTemp);
mPlace.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
}
}
}
This is my main activity which gets a json array from a URL. My problem is that when I try and Unit test what should be in the textview it gives me a null pointer exeption.
public class MainActivity extends AppCompatActivity {
TextView txtJson;
ProgressDialog pd;
public static TextView testString;
String jsonString = null;
List<Location> locations;`enter code here`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
testString = (TextView) findViewById(R.id.test_for_string);
new JsonTask().execute("https://wsu-dining-service.s3.amazonaws.com/current-menu.json");
}
protected void postCreate()
{
mapStrinToClass();
testString.setText(locations.get(0).getName());
}
private void mapStrinToClass()
{
ObjectMapper objectMapper = new ObjectMapper();
JsonFactory jsonFactory = objectMapper.getFactory();
try {
JsonParser jsonParser = jsonFactory.createParser(jsonString);
locations = objectMapper.readValue(jsonString,
new TypeReference<List<Location>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
jsonString = result;
postCreate();
}
}
}
My unit test
* When I run the app the textview is populated with "Tim & Jeanne's Dining Commons" but the test fails and says the testString.getText().toString(); is null
#Test
public void isMenuCorrect() {
String menuTxt = MainActivity.testString.getText().toString();
assert(menuTxt == "Tim & Jeanne's Dining Commons");
}
First of all, you should use Espresso to run UI tests, under the androidTest folder. Example:
onView(allOf(withId(R.id.tvJsonItem), withText("Tim & Jeanne's Dining Commons")).check(matches(isDisplayed()));
Basically what we're doing here is checking if a view with id R.id.tvJsonItem and with a text "Tim & Jeanne's Dining Commons" is displayed on the screen. Now how to run Espresso tests is not in this question's scope.
Second, your production code should never know what's going on in the tests, like you have created a TextView just to be used in your unit tests.
Finally, never have static references to your views since you can't guarantee your activity has been created by the time you try to access them. In fact, a view should only be seen by its parent. In your case, the reference TextView should be private in your activity.
I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?
Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}
You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}
#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}
first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions
private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Android AsyncTask Progress bar
Am using login process,during tat time am getting the data from server is delay.so i want set a progress bar for tat delay.how to set progress bar till get a response from server.any know the answer please help me.
private class LongOperation extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
progressDialog = new ProgressDialog(activity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(String... params)
{
try
{
//Getting data from server
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
Intent n = new Intent(firstactivity.this, secondactivity.class);
startActivity(n);
}
}
How to call this
ProgressDialog progressDialog;
LongOperation mytask = null;
mytask = new LongOperation();
mytask.execute();
Use AsyncTask in your code and put your code in doInBackground(....) process.
Show your progress dialog in onPreExecute and dismiss it in onPostExecute(...) .
Add an infinite progressbar view to your layout and make it invisible first.
Create an AyncTask to do the server communication.
In onPreExecute() make the progressbar visible.
In onPostExecute() hide the progressbar again.
You can use the onProcessupdate method of an AsyncTask
private class GetLogin extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show("Downloading...");
}
#Override
protected String doInBackground(String... params) {
for (String myUrl : params) {
try {
URL url = new URL(myUrl);
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
//error
} catch (IOException e) {
//error
}
}
return "All Done!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setMessage("Downloading... (" + values[0] + "%)");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
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.