I am a beginner in the android studio. I will successfully connect the database but I don't know how to read a data 5 seconds once in an android studio.
I want to how to read data from the database every 5 seconds once
#Override
protected String doInBackground(String... voids) {
String result = "";
String name = voids[0];
String word = voids[1];
Log.d("myTag", "This is my test");
String connstr ="http://192.168.43.123/suruthi/login.php";
try {
URL url = new URL(connstr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")
+"&&"+ URLEncoder.encode("pass", "UTF-8")+"="+URLEncoder.encode(word, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line ="";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
ips.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
}
The below timer function is working only image changes but it is not suitable for reading a database ever 5 sec once
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run()
{
/* iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length)
{
i=0;
}*/
doInBackground();
}
});}}
catch (InterruptedException e)
{
}}};
}
I tried above the timer function to read a database but it is not working..please guide me to resolve the issues..
Related
This question already has answers here:
The AsyncTask API is deprecated in Android 11. What are the alternatives?
(19 answers)
Closed 1 year ago.
I'm new to Android Java and I would really appreciate it I can get some references and/or examples to make some simple network calls without using AsyncTask.
I'm making a program to parse a simple JSON Object from a URL.
In Android 11 (API 30), All AsyncTask are going to be deprecated as shown here:
https://developer.android.com/reference/android/os/AsyncTask
This is an example of how to send a request without AsyncTask using Thread
void send_request(final String url) {
try {
Thread thread = new Thread() {
public void run() {
Looper.prepare();
final JSONObject[] maindata = {new JSONObject()};
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
String data = "";
String error_data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
int status = httpURLConnection.getResponseCode();
Log.d("GET RX", " status=> " + status);
try {
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
Log.d("GET RX =>", " " + data);
sdbw sd = new sdbw(act);
maindata[0] = new JSONObject(data);
} catch (Exception exx) {
InputStream error = httpURLConnection.getErrorStream();
InputStreamReader inputStreamReader2 = new InputStreamReader(error);
int inputStreamData2 = inputStreamReader2.read();
while (inputStreamData2 != -1) {
char current = (char) inputStreamData2;
inputStreamData2 = inputStreamReader2.read();
error_data += current;
}
Log.e("TX", "error => " + error_data);
}
} catch (Exception e) {
Log.e("TX", " error => " + e.getMessage());
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, 2000);
Looper.loop();
}
};
thread.start();
} catch (Exception ex) {
Log.e("ERROR =>", "" + ex.getMessage());
ex.printStackTrace();
}
}
Heres what i found for room query, works well
val x = Executors.newSingleThreadExecutor().submit(Callable { mDao.getX() }).get()
I'm using a method called registerDevice() in my android app
code to send and receive specific data which contains multiple lines. But I keep getting this error:
W/System.err: java.net.SocketException: Connection reset
public void registerDevice(){
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Socket s = new Socket(gateway, 1234);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
output.println("hello world\r\n");
output.flush();
StringBuffer stringBuffer = new StringBuffer("");
String line = null;
while ((line = input.readLine()) != null) {
stringBuffer.append(line);
}
final String st = line.substring(5);
handler.post(new Runnable() {
#Override
public void run() {
if (st.trim().length() != 0)
Toast.makeText(getApplicationContext(),st,Toast.LENGTH_LONG).show();
}
});
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
UPDATE: I changed the code to this:
Socket s = new Socket(gateway, 1234);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
output.println("hello world\r\n");
output.flush();
final String st = input.readLine();
handler.post(new Runnable() {
#Override
public void run() {
if (st.trim().length() != 0)
Toast.makeText(getApplicationContext(),"st",Toast.LENGTH_LONG).show();
}
});
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm Still getting exceptions on the "final String st = input.readLine();" line. I am supposed to get a MAC address from the server and then the server closes the connection.I checked the server and there is nothing wrong with it, it closes the connection AFTER it sends me the MAC.
Guys I found the problem, it was the packet I was sending, I just changed outout.println() to output.write(), so now the server recognized my command and sent the data I needed which led to my input stream not being empty and avoiding exceptions.
I wanna convert xml data from URL to json using this library , but it doesn't handle xml from URLs..! only if it was a string or file, so I wanna convert the data inside the url into a string!
is it possible?
This fragment can help you
new Thread() {
public void run() {
URL url = null;
BufferedReader in = null;
try {
url = new URL("your url");
in = new BufferedReader(
new InputStreamReader(
url.openStream(),"UTF-8"));//in most cases there is utf 8
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = in.readLine()) != null)
builder.append(inputLine);
String urlContent = builder.toString();
// process your received data somehow
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}.start();
When I'm trying to download html using this method:
public class DownloadHtml extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char currentChar = (char) data;
result += currentChar;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
}
And logging a result
DownloadHtml downloadHtml = new DownloadHtml();
String result = null;
try {
result = downloadHtml.execute("http://stackoverflow.com").get();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("Html", result);
I am gettin only small part of it.
Is there a way to get whole HTML of webpage?
Solution was simple. Looks like Log.i doesn't print everything in one go.
When I have tried to get all the links from HTML they were successfully printed.
Here is my code. I did a "GET" method for have a response of my DB.
Then I read my own file csv. All is ok in this point, but... I have not idea how can i do a "POST" method. i know that i need to use "addRequestProperty"method.
Any idea for create vertex and edge?
public void run() throws MalformedURLException, JSONException, IOException {
String viaURl = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxx/mydb";
URL url = new URL(viaURl);
HttpURLConnection conexion = null;
String texto = null;
String json;
BufferedReader in = null, in2 = null;
int numDump = 5;
String dato;
String csvSplitBy = ";";
int numApps = 0;
OutputStreamWriter out;
try {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxx", "xxxxxxxxxxxxx.".toCharArray());
}
});
conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestMethod("GET");
conexion.connect();
System.out.println("¡¡¡Conectado!!!");
in = new BufferedReader(new InputStreamReader(conexion.getInputStream()));
out = new OutputStreamWriter(conexion.getOutputStream());
json = "";
while ((texto = in.readLine()) != null) {
json += texto;
}
in.close();
System.out.println(json);
conexion.setDoOutput(true);
try {
for (int i = 0; i < numDump; i++) {
String csvFile = "/home/danicroque/dump/dump_" + i;
try {
in2 = new BufferedReader(new FileReader(csvFile));
while ((dato = in2.readLine()) != null) {
numApps++;
String[] datos = dato.split(csvSplitBy, 15);
conexion.setRequestMethod("POST");
conexion.addRequestProperty("_id0" , datos[0]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("Fin");
}
}
}
Thank in advance.
You can use this POST methods to create class:
http://your_host:2480/class/mydb/className
to add property to a class
http://your_host:2480/property/mydb/className/propertyName
You can fine more detailed information here.
Hope it helps,
Alex.
UPDATE:
To insert use this POST method:
http://your_host:2480/command/mydb/sql/insert into className(propertyName) values(“yourValue”)