get files and send telegram bot android - java

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.

Related

Android - Problem with executing AsyncTask thread

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!

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

Unable to send data to server in Android

I'm new to Android. Don't know which part has gone wrong. The thing is I'm unable to send the data to the server in Android Studio.
This is the error I'm facing
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\students\connection.php:6 Stack trace: #0 C:\xampp\htdocs\students\add_employee.php(2): include() #1 {main} thrown in C:\xampp\htdocs\students\connection.php on line 6
The code goes like this...
Main Activity
public class MainActivity extends AppCompatActivity {
Button b1;
EditText e1;
private ProgressDialog pDialog;
private JSONObject json;
private int success=0;
private HTTPURLConnection service;
private String strname ="";
//Initialize webservice URL
private String path = "http://localhost/student/add_employee.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
e1 = (EditText) findViewById(R.id.editText9);
service=new HTTPURLConnection();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!e1.getText().toString().equals("") ) {
strname = e1.getText().toString();
//Call WebService
new PostDataTOServer().execute();
} else {
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(MainActivity.this, Student1.class);
startActivity(intent);
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("name", strname);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
json = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(success==1) {
Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
}
}
}
}
HTTPURLConnection
public class HTTPURLConnection {
String response="";
URL url;
public String ServerData(String path,HashMap<String, String> params) {
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//Log.d("Output",br.toString());
while ((line = br.readLine()) != null) {
response += line;
Log.d("output lines", line);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
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"));
}
return result.toString();
}}
My PHP code
add_employee.php
<?php
include('connection.php');
$emp_name=$_POST["name"];
$success=0;
$status="Active";
$sql = "INSERT INTO `employee` (`emp_name`)
VALUES ('$emp_name')";
if(mysql_query($sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>
connection.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('student');
?>

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

Categories