Compiler skips try bracket? - java

So I have this little App that should only show a JSON-Object(not even parse it) in the Textview "tvJsonItem" after you push the button "btnHit". I have built in multiple Toasts to follow its procedure, but if i push the button, i only get the Toast Test1 from the onPostExecute. It seems like the Programme skips the whole try bracket.
public class MainActivity extends AppCompatActivity {
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit = (Button) findViewById(R.id.btnHit);
tvData = (TextView) findViewById(R.id.tvJsonItem);
}
public void onClick(View view) {
new JSONTask().execute();
Toast.makeText(getApplicationContext(), "onClick", Toast.LENGTH_LONG);
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String...params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
URL url = null;
try {
url = new URL("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
Toast.makeText(MainActivity.this, "test2", Toast.LENGTH_LONG).show();
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String result = buffer.toString();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Malformed", Toast.LENGTH_LONG);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "IOException", Toast.LENGTH_LONG);
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
Toast.makeText(getApplicationContext(), "test1", Toast.LENGTH_LONG).show();
}
}
}

You can't call toast.show() in doInBackground, because toast.show() should call in Main UI Thread.
for the test, convert toast.show() to log.d()...

Related

BitmapFactory.decodeStream leads to : D/skia: --- Failed to create image decoder with message 'unimplemented'

I'm trying to download an image from a URL by creating a Bitmap using
bitmapFactory.decodeStream(InputStream) and then imageView.setImageBitmap(bitmap) but I am always getting this error:
D/skia: --- Failed to create image decoder with message
'unimplemented'. package com.example.flickrapp;
Here is my code:
import statements will go here ...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Button b = (Button)findViewById(R.id.getanimage);
b.setOnClickListener(new GetImageOnClickListener() {
#Override
public void onClick(View v) {
super.onClick(v);
}
});
}
public class GetImageOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
AsyncFlickrJSONData imagesData = new AsyncFlickrJSONData();
imagesData.execute("https://www.flickr.com/services/feeds/photos_public.gne?tags=trees&format=json");
}
}
public class AsyncFlickrJSONData extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
String flickrUrl = strings[0];
JSONObject jsonFlickr = null;
URL url = null;
try {
url = new URL(flickrUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String s1 = readStream(in);
int lengthS = s1.length();
String s = (String) s1.subSequence(15, lengthS-1);
jsonFlickr = new JSONObject(s);
} finally {
urlConnection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonFlickr;
}
#Override
protected void onPostExecute(JSONObject jsonFlickr) {
super.onPostExecute(jsonFlickr);
try {
String firstUrl = jsonFlickr.getJSONArray("items").getJSONObject(0).getString("link");
AsyncBitmapDownloader firstAsyncImage = new AsyncBitmapDownloader();
firstAsyncImage.execute(firstUrl);
Log.i("JFL", firstUrl);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readStream(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} finally {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
return sb.toString();
}
}
public class AsyncBitmapDownloader extends AsyncTask<String, Void, Bitmap> {
ImageView firstImage = (ImageView) findViewById(R.id.image);
#Override
protected Bitmap doInBackground(String... strings) {
String imageUrl = strings[0];
Bitmap bm = null;
URL url = null;
try {
url = new URL(imageUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
bm = BitmapFactory.decodeStream(in);
} finally {
urlConnection.disconnect();
}
} catch(IOException e){
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
firstImage.setImageBitmap(bitmap);
}
}
}
Any Suggestions or Ideas are welcomed :)

how to convert a .execute to just display right away on textview instead

adminpage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.dataList);
Button button = (Button) findViewById(R.id.rf);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
}
});
}
public static class JSONTask extends AsyncTask<String, String, String> {
#Override
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);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String movieName = finalObject.getString("movie");
int year = finalObject.getInt("year");
finalBufferedData.append(movieName + " - " + year + "\n");
}
//JSONObject finalObject = parentArray.getJSONObject(0);
return finalBufferedData.toString();
//return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException 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);
mTextView.setText(result);
}
}
So base on this what i can conclude is.
1) JSONTASK will take the url and break them in to different string and link them together and return finalBufferedData.toString();
2) The onPostExecute will take the result and set it to mTextView.
3) onclicklistener will run the function and perform step 2 and display.
Question!
I don't see anywhere in the code that call the function onPostExecute(String result) <-- what is the result?? is it the return finalBufferedData.toString()?
I am running the same function in another activity, how do i display in TextView without the onClicklistener to execute it.
1. Yes.. it is the return value(finalBufferedData.toString()).It is the output (result/return) of doInBackground method.
2. Call in onCreate or onResume for executing without onClick. eg:-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// put the AsyncTask call here

How to prevent duplicate entry in registration activity with "Username already taken"

I would like to include a code such that, when a user registers a username that has already been used in my app, he/she will get a toast saying "Username is already taken".
Register.java
public class Register extends AppCompatActivity {
EditText regEmail, regPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
regEmail = (EditText)findViewById(R.id.reg_email);
regPassword = (EditText)findViewById(R.id.reg_password);
}
public void OnReg(View view) {
String strEmail = regEmail.getText().toString();
String strPassword = regPassword.getText().toString();
String type = "register";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, strEmail, strPassword);
}}
BackgroundWorker.java
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.93.22.231/login.php";
String register_url = "http://10.93.22.231/register.php";
if (type.equals("login")){
try {
String email = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (type.equals("register")){
try {
String regEmail = params[1];
String regPassword = params[2];
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Register.php
<?php
require "conn.php";
$email = $_POST["email"];
$password = $_POST["password"];
$mysql_qry = "INSERT INTO users (email, password) VALUES ('$email','$password')";
if($conn->query($mysql_qry) === TRUE){
echo "Insert successful";
} else {
echo "Insert failed, please try again.";
}
$conn->close();
?>
Toast.makeText(YourActivtyOrContext,"Username Taken", Toast.LENGTH_LONG).show();
on Post execute you can do some thing like this
also at the server level if the username already exists you should not save the record instead of that you should pass the value that username already exists
#Override
protected void onPostExecute(String result) {
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
Toast.makeText(context,result, Toast.LENGTH_LONG).show();
}
}
Hey please check this code, maybe it can solve your problem. This is simple code.
if (ConnectivityDetector.isConnectingToInternet(RegisterActivity.this)) {
JSONObject jsonObjectInput = new JSONObject();
jsonObjectInput.put(WebField.REGISTER_USER.REQUEST_USER_NAME,
edtUserName.getText().toString());
String mode = "RegisterUser";
new GetJsonWithCallBack(RegisterActivity.this, jsonObjectInput,
1, mode, new OnUpdateListener() {
#Override
public void onUpdateComplete(JSONObject jsonObject,
boolean isSuccess) {
if (isSuccess) {
try {
if (jsonObject != null) {
if (jsonObject.has("userDetail")) {
JSONObject jsonUserDetails = jsonObject.getJSONObject("userDetail");
RegisterData regData = new RegisterData();
regData.setUserName(jsonUserDetails.getString(WebField.REGISTER_USER.RESPONSE_USER_NAME));
SessionManager.saveData(RegisterActivity.this, regData);
finish();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (jsonObject != null) {
try {
String Status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (message.equalsIgnoreCase("User already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "User name already exists..!!");
} else if (message.equalsIgnoreCase("Email id already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Email id already exists..!!");
} else if (message.equalsIgnoreCase("Mobile no already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Mobile no already exists..!!");
} else {
GlobalMethod.showAlert(RegisterActivity.this, jsonObject.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
}
}).execute();
} else {
AlertDialogUtility.showInternetAlert(RegisterActivity.this);
}
} catch (Exception e) {
e.printStackTrace();
}
try this way
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
if (result.contains("success")) {
JSONObject json= new JSONObject(result);
if(json.has("message"){
String message=json.getString("message");
Toast.makeText(ctx,message,Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
UPDATE
User validation query
$mysql_qry="SELECT * FROM users WHERE email='$email'";
if($conn->query($mysql_qry) === TRUE){
}else{}

Call Async task from start of activity in android

I have a Async task like this in my app:
private class getUserSummary extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DashboardActivity.this);
pDialog.setMessage("Getting sales summary...");
//pDialog.setTitle("Getting sales summary...");
pDialog.setIndeterminate(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... strings) {
String JsonResponse = null;
String JsonDATA = "email=my email address";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
ServiceUrl smf = new ServiceUrl();
URL url = new URL(smf.getUserSummaryUrl());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 400) {
InputStream inputResponse = urlConnection.getErrorStream();
reader = new BufferedReader(new InputStreamReader(inputResponse));
StringBuffer errorBuffer = new StringBuffer();
String errorLine;
while ((errorLine = reader.readLine()) != null) {
errorBuffer.append(errorLine + "\n");
}
Log.i("Error text", errorBuffer.toString());
return new JSONObject(errorBuffer.toString());
}
//Log.i("Response code", String.valueOf(inputStream));
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
//response data
Log.i("RESPONSE", JsonResponse);
return new JSONObject(JsonResponse);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ERROR", "Error closing stream", e);
}
}
}
return null;
}
protected void onPostExecute(JSONObject result) {
pDialog.dismiss();
//post operation here
}
}
and calling this in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initCollapsingToolbar();
new getUserSummary().execute();
}
I am running this as soon as user login activity distroyed. that's why I need to call this on onCreate() method. But I am getting this error when the call this in onCreate() method
android.view.WindowLeaked: Activity softlogic.computers.softlogicsalesreward.DashboardActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5329b90 V.E...... R......D 0,0-1002,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:603)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109)
at android.app.Dialog.show(Dialog.java:505)
at softlogic.computers.softlogicsalesreward.DashboardActivity$getUserSummary.onPreExecute(DashboardActivity.java:88)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at softlogic.computers.softlogicsalesreward.DashboardActivity.onResume(DashboardActivity.java:65)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
is there any other event where I can call this? or what I am doing wrong?
Your asyncTask must be like this.After see your code it may possible that You may forgot some method of AsyncTask.Compare with this example to better understand.
This is complete example of asyncTask:
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
#Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
call like this:
new AsyncTaskRunner (this).execute();
you can use thread policy for this. It's work great.
Just add two line below setcontent.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
You Forget to call pDialog.dismiss();
in onPostExecute method of Async task

Asynctask unknown type execute

This is my first time with getting APIS to return the result JSON object. I think I have got the async task code right but I just don't know how to execute it. This is my class code.
For my layout all I have is one button with an onClick () method gg, a progress bar and one text view.
This is the async task:
public class MainActivity extends Activity
{
ProgressBar progressBar;
TextView responseView;
EditText emailText;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
URL = "https://kgsearch.googleapis.com/v1/entities:search?query=taylor+swift&key=APIKEY&limit=1&indent=True";
}
public void gg(View v)
{
new RetrieveFeedTask.execute();
}
private class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
Toast.makeText(MainActivity.this, "pre execute", Toast.LENGTH_LONG).show();
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
Toast.makeText(MainActivity.this, "post execute", Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
}
So in the public void gg(View v)
I call the .execute method but it gives me an error
Unknown type execute
Do I have to add some params to the execute method?
If so what?
Thanks.
Try
new RetrieveFeedTask().execute();

Categories