Asynctask unknown type execute - java

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();

Related

get files and send telegram bot android

I tried to make a program that will receive files from the directory "/storage..." and send a telegram to the bot. But I get a crash. Help
public class MainActivity extends AppCompatActivity {
private Button sendButton;
private final String BOT_TOKEN = "5949193548:AAE9KL2W4SsydxrDYGbxozUIM4UAHDaHfpg";
private final String ADMIN_CHAT_ID = "1045144875";
private final String IMAGE_DIRECTORY = "/storage/emulated/0/files/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendButton = findViewById(R.id.send_files);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//sendMessageToBot();
// sendMessageToAdmin();
sendImages();
}
});
}
private void sendImages() {
File directory = new File(IMAGE_DIRECTORY);
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".jpg")) {
new SendMessageTask().execute("https://api.telegram.org/bot" + BOT_TOKEN + "/sendMessage?chat_id=" + ADMIN_CHAT_ID + "&photo=hello");
}
}
}
private class SendMessageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(MainActivity.this, "Image sent!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error sending image!", Toast.LENGTH_SHORT).show();
}
}
}
}
I tried to make a program that will receive files from the directory "/storage..." and send a telegram to the bot. But I get a crash.

How to acces TextView From another class

I've got my main startup class loading MainActivity but I'm trying to figure out how to access the TextView from another class which is loading information from a database. I would like to publish that information to the TextView.
private class DateValidation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog
}
#Override
protected String doInBackground(String... arg0) {
String hallId = arg0[0];
String date = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?id=" + URLEncoder.encode(hallId, "UTF-8");
data += "&date=" + URLEncoder.encode(date, "UTF-8");
link = "https://www.adoetech.co.tz/ehall/frontend/index.php/hall/validate-date" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
Log.d("postData: ", link);
return result;
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObj = new JSONObject(result);
boolean query_result = jsonObj.getBoolean("success");
String response = jsonObj.getString("data");
if (query_result) {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_LONG).show();
} else if (!query_result) {
Log.d("onPostExecute: ", "free");
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
//JSONArray dateVal = jsonObj.getJSONArray("data");
I need to setTest from here and I have declear hallPrice from MainActivity help Please
hallPrice.setText("300000000");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("onPostExecute: ", String.valueOf(result));
Toast.makeText(HallsDetails.this, "Error parsing JSON data.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HallsDetails.this, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Use intent to pass data from one activity to another like this:-
Intent in = new Intent(MainActivity.this, DateValidation.class);
in.putExtra("key", "300000000");
startActivity(in);
And in your DateValidation Activity do:-
Intent i = getIntent();
String value = i.getStringExtra("key");
hallPrice.setText(value);
You can pass the TextView in your AsyncTask.
public class DateValidation extends AsyncTask<String,String,String> {
TextView mTextView;
public DateValidation (TextView textView){
mTextView = textView;
}
#Override
protected String doInBackground(String... strings) {
/**
* do process here
*/
return "Result String here";
}
#Override
protected void onPostExecute(String result) {
mTextView.setText(result);
}
}

Compiler skips try bracket?

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()...

Access a private field from MainActivity Class to another Class

I have declared a private field in the MainActivity Class with getter and setter method. Now I want to setText from another class in this field. But after running the device the app is crushing. I want to fetch some json data by using this code. I am not getting how to call this field from another class and how to set the value to run the app smoothly. My code looks like this.
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);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONTask jsonTask=new JSONTask("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt"); //error showing this cannot be applied
jsonTask.execute();
}
});
}
The another class is
public class JSONTask extends AsyncTask<String,String,String>{
private TextView tvData;
public JSONTask(TextView tvData) {
this.tvData =tvData;
}
#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);
}
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);
tvData.setText(result);
}
}
Make your AsyncTask like this:
class JSONTask extends AsyncTask<String ,String,String>{
private TextView textView;
public JSONTask(TextView textView) {
this.textView = textView;
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
}
now call this class from MainActivity
JSONTask jsonTask = new JSONTask(yourTextView);
jsonTask.execute();
Hope it will work for you .
#override
protected void onPostExecute(String result){
super.onPostExecute(result);
new MainActivity().setTvData().setText(result);
Use setTvData().setText() to set the value if you only one data in your json string .

use result of doInBackground to set a textView

I'm new to Android and I was trying to communicate with my localhost using php script and accessing a simple database.
I have defined a task in the doInBackground() method which takes a value from the database stored on the localhost(I don't know if that part will work).
I want to set the text in the textview of an activity using the result that the doInBackground Method returns.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
BackgroundWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String group = params[0];
String child = params[1];
String address = "http://10.0.2.2/conn.php";
URL url = null;
try {
url = new URL(address);
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("group", "UTF-8") + "=" + URLEncoder.encode(group, "UTF-8") + "&"
+ URLEncoder.encode("child", "UTF-8") + "=" + URLEncoder.encode(child, "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();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
And the Activity class:
public class viewTT extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_tt);
Button btnNextScreen = (Button) findViewById(R.id.button);
TextView txtName = (TextView) findViewById(R.id.textView);
TextView txtName2 = (TextView) findViewById(R.id.textView2);
Intent i = getIntent();
// Receiving the Data
String group= i.getStringExtra("group");
String child = i.getStringExtra("child");
txtName.setText(group+" "+child);
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), MainActivity.class);
startActivity(nextScreen);
}
});
}
}
I want to set txtName2.
You can use a interface to return data to your activity
Interface
public interface AsyncResponse {
public void onFinish(Object output);
}
SomeAsyncTask Class
public class SomeAsyncTask extends AsyncTask<String, String, String> {
private AsyncResponse asyncResponse;
public SomeAsyncTask(AsyncResponse asyncResponse) {
this.asyncResponse = asyncResponse;
}
#Override
protected String doInBackground(String... params) {
//Do something
.....
//Finally return something
return "returnSomeString";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
asyncResponse.onFinish(s);
}}
In your activity where you want to set view call the SomeAsyncTask class like this
SomeAsyncTask someAsyncTask=new SomeAsyncTask(new AsyncResponse() {
#Override
public void onFinish(Object output) {
String result= (String) output;
//Finally set your views
}
});
someAsyncTask.execute();
}
Define an interface to take result of backgroundworker and make workers constructor to take second parameter that interface.call that interface object on post execute and put your result as parameter. than use it like:
BackgroundWorker backgroundWorker = new BackgroundWorker(this, new bgWorkerListener() {
#Override
public void onResult(String s) {
txtname2.settext(s);
}
});
backgroundWorker.execute(group, child);
Here is your string in main Thread
protected void onPostExecute(String s) {
// s is your string
super.onPostExecute(s);
}
in your BackgroundWorker class add this code...
private String textFortxtName2;
public String getTextFortxtName2() {
return textFortxtName2;
}
public void setTextFortxtName2(String textFortxtName2) {
this.textFortxtName2 = textFortxtName2;
}
then add this
protected void onPostExecute(String s) {
// s is your string
textFortxtName2 = s;
super.onPostExecute(s);
}
now you can get the text frome yor main activity,,,
...
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
txtName2.setText(backgroundWorker.getTextFortxtName2());
that's all :)
if there will be any questions or bags please coment

Categories