Android - Problem with executing AsyncTask thread - java

I'm trying to write an app that sends a POST request on asynchronous task. My AsyncTask does not seem to execute since my progress bar doesn't show up. I don't really know what is wrong here, since I followed many solutions/tutorials.
Here's my code:
register.java
public class register extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
final Activity thisActivity = this;
final EditText userNameEditText = findViewById(R.id.registerUsername);
final EditText emailEditText = findViewById(R.id.registerEmail);
final EditText passwordEditText = findViewById(R.id.registerPassword);
final ProgressBar progressBar = findViewById(R.id.progressBar);
Button btnRegisterDB = findViewById(R.id.btnRegistrationDB);
final TextView respondText = findViewById(R.id.responseRegister);
btnRegisterDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = String.valueOf(userNameEditText.getText());
String email = String.valueOf(emailEditText.getText());
String password = String.valueOf(passwordEditText.getText());
//execute asynchronous task in background and wait for response
RegisterParams params = new RegisterParams(username, email, password);
registrationDB async = new registrationDB();
async.setProgressBar(progressBar);
async.setRespondText(respondText);
async.getParentActivity(thisActivity);
async.execute(params);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
return true;
}
public static class RegisterParams {
public String username;
public String email;
public String password;
RegisterParams(String username, String email, String password){
this.username = username;
this.email = email;
this.password = password;
}
}
}
and here is registrationDB.java
public class registrationDB extends AsyncTask<register.RegisterParams, Void, String> {
openHTTP openHTTP = new openHTTP();
String respond;
ProgressBar pb;
TextView respondTextView;
Activity parentActivity;
public void setProgressBar(ProgressBar progressBar){
this.pb = progressBar;
}
public void setRespondText(TextView textView){
this.respondTextView = textView;
}
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
#Override
public void onPreExecute(){
pb.setVisibility(View.VISIBLE);
//parentActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
// WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
super.onPreExecute();
}
#Override
protected String doInBackground(register.RegisterParams... params) {
try {
HttpURLConnection httpConn = openHTTP.prepareConnection("someurl");
String jsonInputString = "{ username: " + params[0].username +", email: " + params[0].email
+ ", password: " + params[0].password + "}";
try(OutputStream os = httpConn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
} catch (Exception e){
e.printStackTrace();
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(httpConn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
respond = response.toString();
return respond;
} catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
pb.setVisibility(View.GONE);
respondTextView.setText(s);
super.onPostExecute(s);
}
}
and I have external class openHTTP.java which is responsible for opening HttpUrlConnection:
public class openHTTP {
public openHTTP(){
}
//provide URL to external file that you want make POST request to
public HttpURLConnection prepareConnection(String URL){
try {
java.net.URL url = new URL(URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Thanks in advance for help!
UPDATE
After logging processes I've discovered that exception:
java.io.IOException: Cleartext HTTP traffic to url not permitted, now I'm on my way searching for this problem
MY SOLUTION
So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml
Thanks for your help!

After logging processes I've discovered that exception: java.io.IOException: Cleartext HTTP traffic to url not permitted.
So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml Thanks for your help!

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.

cant set text in postExecute ,Async, Android

I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}

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

Want to login to Router with android application

I'm just starting to develop android application and want to try to connect to my router. Wrote application using Jackson, but get stuck with json request for login to the router. IP of my router is 192.168.1.1 and username and password should be taken from EditText fields.
android.os.NetworkOnMainThreadException
There is json string for login:
{ "jsonrpc": "2.0", "id": 1, "method": "call", "params": [ "00000000000000000000000000000000", "session",
"login", { "username": "root", "password": "admin01" } ] }
This is my RestRequest.java
public class RestRequest {
private static final String TAG = JacksonUtil.class.getSimpleName();
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public RestRequest(){
}
public String makeWebServiceCall(String url, int requestmethod){
return this.makeWebServiceCall(url, requestmethod, null);
}
public String makeWebServiceCall(String urladdress, int requestmethod, HashMap<String, String> params){
URL url;
String responce = "";
try {
url = new URL(urladdress);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setReadTimeout(15000);
urlconnection.setConnectTimeout(15000);
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
if(requestmethod == POST){
urlconnection.setRequestMethod("POST");
}else if(requestmethod == GET){
urlconnection.setRequestMethod("GET");
}
if(params != null){
OutputStream outputstream = urlconnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputstream, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
bufferedWriter.write(result.toString());
bufferedWriter.flush();
bufferedWriter.close();
outputstream.close();
}
int responceCode = urlconnection.getResponseCode();
if(responceCode == HttpsURLConnection.HTTP_OK){
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
while ((line = br.readLine()) != null){
responce += line;
}
}else {
responce = "";
}
} catch (Exception e){
Log.e(TAG, "IOException parsing to json", e);
}
return response;
}
Edited my LoginActivity.java
Can anyone to look at this activity and tell what I'm doing wrong
public class LoginActivity extends AppCompatActivity {
private String page_url = "http://192.168.1.1/ubus";
#Bind(R.id.user_name_edit_text)
TextView user_name;
#Bind(R.id.user_password_edit_text)
TextView user_password;
#Bind(R.id.login_button)
Button login_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = page_url;
String username = getUserName();
String password = getPassword();
TryToLogin tryToLogin = new TryToLogin();
tryToLogin.execute(url, username, password);
}
});
class TryToLogin extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
URL url = null;
try {
url = new URL(page_url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getUserName() {
String username = user_name.getText().toString();
return username;
}
private String getPassword() {
String password = user_password.getText().toString();
return password;
}
You cannot make network calls using the main thread in Android - this is by design to ensure the UI thread remains responsive and does not wait. You need to perform this call in an AsyncThread or normal Thread

how to make my code (AsyncTask) cleaner?

I need to build an android app for my final year project, (i am new to android development). Is there any idea to minimize the code or maybe separate into different classes.
I want to make my main activity shorter and cleaner for maintenance, and preferably if it can be coded using MVC architecture. There will be more UI components added later.
Thank you for ur attention.
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button)findViewById(R.id.find_button);
json_output = (TextView)findViewById(R.id.json_output);
user_origin = (EditText)findViewById(R.id.user_origin);
user_destination = (EditText)findViewById(R.id.user_destination);
find_button.setOnClickListener(new View.OnClickListener(){
String origin;
String new_origin;
String destination;
String new_user_destination;
#Override
public void onClick(View v){
origin = user_origin.getText().toString();
new_origin = origin.replaceAll(" ", "+");
destination = user_destination.getText().toString();
new_user_destination = destination.replaceAll(" ", "+");
String link = "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
//json_output.setText(link);
new JSONTask().execute(link);
}
});
}
public 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 final_json = buffer.toString();
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);
json_output.setText("result:" +result);
}
}
}
You can separate your JSONTask as a simple class,and execute its task,then define an interface in this class to pass some message or data should be handled by other class,and add a parameter type is this interface for constructor and save it as a field.like this:
public class JSONTask extends AsyncTask<String,String,String>{
private OnHandleResult mResult;
private String[] mParams;
public JSONTask(OnHandleResult onHandleResult,String... params){
this.mResult = onHandleResult;
this.mParams = params;
}
protected String doInBackground(String... params){
//params is empty,get params from this.mParams
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
//json_output.setText("result:" +result);
this.mResult.handleResult(result);
}
public static interface OnHandleResult{
void handleResult(final String result);
}
}
then let your activity implement interface onHandleResult,and hanlde result:set text to textview:
public class MainActivity extends AppCompatActivity implements JSONTask.OnHandleResult{
void handleResult(final String result){
json_output.setText("result:" +result);
}
}
and execute task like this:
new JSONTask(this,link).execute();
Usually it's good practise to have 1 class per file.
You can make your MainActivity a bit more readable
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button) findViewById(R.id.find_button);
json_output = (TextView) findViewById(R.id.json_output);
user_origin = (EditText) findViewById(R.id.user_origin);
user_destination = (EditText) findViewById(R.id.user_destination);
String link = build_link(user_origin, user_destination);
MyListener l = new MyListener(link);
find_button.setOnClickListener(l);
}
private String build_link(EditText user_origin, EditText user_destination) {
String origin = user_origin.getText().toString();
String new_origin = origin.replaceAll(" ", "+");
String destination = user_destination.getText().toString();
String new_user_destination = destination.replaceAll(" ", "+");
return "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
}
by isolating your listener's implementation:
public class MyListener implements View.OnClickListener {
String link;
public MyListener(String link) {
this.link = link;
}
#Override
public void onClick(View v) {
new JSONTask().execute(link);
}

Categories