android AysncTask doInbackground - java

I am new in android, I am trying to implement socket in android it is a simple client-server app.
where I have created 2 buttons ("connect", "disconnect"), and using AysncTask doInBackground i am connecting to the server and disconnecting from the server but it's working for connection only, when I am trying to disconnect my app close unfortunately.
Below there is my mainactivity code.
Thanks for helping
package com.example.sockettest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import java.io.*;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.lang.String;
class conn extends AsyncTask<String, Void, Void>{
Socket operator_socket;
#Override
protected Void doInBackground(String... voids) {
String str;
str = voids[0];
if (str.equals("conn")) {
try {
operator_socket = new Socket("192.168.0.103", 6666);
}catch (UnsupportedEncodingException e) { e.printStackTrace(); }
catch (UnknownHostException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
} else if (str.equals("CC")){
try {
operator_socket.getOutputStream().write("EX".getBytes("US-ASCII"));
operator_socket.close();
} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
catch (UnknownHostException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
} else {
}
return null;
}
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
conn new_conn = new conn();
public void connect_operator(View v){
new_conn.execute("conn");
}
public void close_conn(View v){ new_conn.execute("CC"); }
}

You can call execute only once on one instance of an AsyncTask. new_conn is being initialised only once. Now if you try to create a new object every time to call execute, you won't be able to use operator_socket Socket variable as a member variable of AsyncTask class. You are getting exception when calling execute more than once on a single instance of AsyncTask
Read these docs

Related

The getAssets() method in the Android library does not work

As a newbie to Android programming, I have attached four files to the assets folder of my library.
You can see the attached image.
I want to access these files through the Android library using the below code (if I don't use this code in Android library, it runs without an error when I use it in MainActivity).
public void copy_weights() {
try {
AssetManager assetFiles = getAssets();
String[] files = assetFiles.list("");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace(); //catch the error in this line
} catch (Exception e) {
e.printStackTrace();
}
}
but this code give me the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.Context.getAssets' on a null object refrence
I tried other methods like direct accessing via home:///android_asset/7.cfg but it can't access the files too.
EDIT 1
I call the copy_weights() in mainActivity like below
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final new_class newClass=new new_class();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button =(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView textView=(TextView) findViewById(R.id.textView);
newClass.copy_weights();
}
});
}
EDIT 2
new_class code
package com.example.mylittlelibrary;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.dnn.Net;
import org.opencv.imgcodecs.Imgcodecs;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
public class new_class extends AppCompatActivity {
private boolean opencv_sucessfully_included;
private static int BUFFER_SIZE = 1024;
public new_class() { }
private static void copyAssetFiles(InputStream in, OutputStream out) {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void copy_weights() {
try {
AssetManager assetFiles = getAssets();
// MyHtmlFiles is the name of folder from inside our assets folder
String[] files = assetFiles.list("");
// Initialize streams
InputStream in = null;
OutputStream out = null;
for (int i = 0; i < files.length; i++) {
File file = new File(Environment.getExternalStorageDirectory() + "/" + files[i]);
if (!file.exists()) {
in = assetFiles.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyAssetFiles(in, out);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can't initialize an Activity like that. If you need a reference to a Context (such as with getAssets()) you should pass it to the class.
First, remove your AppCompatActivity extension:
public class new_class {
Then change your constructor and add a global variable:
private Context context;
public new_class(Context context) {
this.context = context;
}
You'll notice some of your methods are now in red and unresolved. Just add context. before them. For example
context.getAssets()
Make a new instance of that class by adding a this argument to it:
final new_class newClass = new new_class(this);
Also, you shouldn't put anything before super.onCreate() is called, so move that to go after it.

Reconnecting to Bluetooth in android / Reading after Reconnect

I have a program that establishes a Bluetooth connection, reads the InputStream to a textView, and can disconnect from the module. While I can successfully disconnect and reconnect to the module (HC-05) as many times as I please, I can't get an InputStream read anymore after I reconnect. I believe it is because I don't know how to reinitialize the thread I'm using to read the InputStream. I am very new to java and android programming, any help with this issue would be appreciated.This is my code:
The textView for the read display is called 'Status' and I am hoping to "reset" the thread upon the onclick connect().
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements Runnable {
private BluetoothAdapter adapter;
private InputStream inputStream;
private OutputStream outputStream;
private Thread thread;
private TextView Status;
private TextView Connection;
private BluetoothSocket socket = null;
private boolean threadStatusInitial=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Status=(TextView) findViewById(R.id.StatusID);
Connection=(TextView) findViewById(R.id.ConnectionStatus);
adapter= BluetoothAdapter.getDefaultAdapter();
if(adapter==null){
Toast.makeText(this,"bluetooth is unavailable",Toast.LENGTH_SHORT).show();
finish();
return;
}
thread=new Thread(this);
}
public void connect(View view){
Set<BluetoothDevice> devices=adapter.getBondedDevices();
for(BluetoothDevice device:devices){
if(device.getName().startsWith("HC-05")){
try {
socket=device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
socket.connect();
Connection.setText("Connected");
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
if (threadStatusInitial){
thread.start();
threadStatusInitial=false; //this ensures that the thread.start() method will only be called during the first connection
}
} catch (IOException e) {
Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
}
}
}
public void Disconnect(View view) throws InterruptedException {
if (inputStream != null) {
try {inputStream.close();} catch (Exception e) {}
inputStream = null;
}
if (outputStream != null) {
try {outputStream.close();} catch (Exception e) {}
outputStream = null;
}
if (socket != null) {
try {socket.close();} catch (Exception e) {Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();}
socket = null;
}
Connection.setText("Disconnected");
}
#Override
public void run() {
String textInput = "hi";
byte[] writeBytes=textInput.getBytes();
if(outputStream!=null){
try {
outputStream.write(writeBytes);
} catch (IOException e) {
Toast.makeText(this,"Unable to Write to Bluetooth ",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
while(inputStream!=null){
byte [] buffer=new byte[2048];
try {
int length=inputStream.read(buffer);
final String strReceived = new String(buffer, 0, length);
runOnUiThread(new Runnable(){
#Override
public void run() {
Status.setText(strReceived);
}});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Can't send message over hotspot, using TCP connection. Android

I'm creating an simple app, in which I want to send message over local wifi connection using TCP. So I'm creating hotspot on one device and connect it from other device.
Now, on hosting device, I'm running following server application and on connecting device I'm running client application.
But nothing happens when I press send button on client device. My code for both server and client is as following:
Code for server:
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Code for client:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket socket;
private String TAG="XXX";
private static final int SERVERPORT = 5000;
private String SERVER_IP ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
SERVER_IP = getWifiApIpAddress();
}
public String getWifiApIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if (intf.getName().contains("wlan")||intf.getName().contains("ap")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& (inetAddress.getAddress().length == 4)) {
Log.d(TAG, inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
// out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I'm following this tutorial. As explained there, It is working fine in android emulators. But doesn't work on actual devices.
So I thought the IP address should be given different on different hotspots. So I've written a method in client code to get server hotspot's IP address and than connect to it. But still nothing happens on pressing send button.
So, What am I missing here? Is my method correct? Is there any mistakes in port numbers?
In the tutorial, author is doing something called port forwarding. What about port forwarding for actual devices?
I've searched everywhere for this on Internet but can't find any exact solution or any tutorial explaining this type of application. Please help me!
EDIT:
when I run this in real devices, It is giving NllPointerException in clients code, on following line:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
You don't need to forward anything on device, just make sure your device is on the same network & use the port you have hard-coded or defined in the settings.
We forward port in emulator because its running on your host machine & we are telling the host to forward traffic coming on that specific port to emulator, since in an actual device you don't need to do that so you just to have to make sure your device is on the same network & correct port is being called.

Trying to run an Asynctask into a service, eclipse looks good, but app crashes Whats wrong here?

Im trying to make an app witch looks on a JSON encoded php file, there that all right. All runs perfectly, but now im attempting to put that class into a Service beacuse i want to run it on background and repeatedly, but application crushes, (on the phone and simulated)
So can anyone tell me whats wrong here?
Here is the code
First the main activity . java
[...]IMPORTS
public class ServiceMainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
}
public void onClickComenzar(View v) {
startService(new Intent(getBaseContext(), MyService.class));
}
public void onClickDetener(View v) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
And here the Service activity . java , the place where im trying to put my asynctask
package attempt.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.text.Html;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
try {
new DoBackgroundTask().execute("http://iatek.eu/sys/getsmsx.php");
} catch (Exception ex) {
ex.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getBaseContext(), "service stoped",
Toast.LENGTH_SHORT).show();
}
private class DoBackgroundTask extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
// HttpResponse response = httpclient.execute(httppost);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
protected void onProgressUpdate( ) {
// TODO Auto-generated method stub
}
#Override
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray;
String dana = null;
try {
jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(1);
String sms = childJSONObject.getString("sms");
Toast.makeText(getBaseContext(), "sms"+sms,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}
public StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
}
My objetive on this code is to show some php data on a toast, but it doesnt... i dont know why, help me pleasee!!
Thanks a lot!
I think using InentService is better suited for what you are trying to accomplish. It runs on a separate Thread, and it stops itself when it is done.

Android - Threads not executing

So yeah, my thread isn't executing, or doing the code within it. I just wanted to run a shell script from my sdcard, and show a "loading" circles or "progress" circle or whatever you want to call it. When I click the button to run the thread, I get the progress/loading bar/circle, but it just sits there and does nothing. I've looked at some examples but still cannot figure out what I did wrong. Here's my code:
package com.cydeon.plasmamodz;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeoutException;
import com.stericson.RootTools.*;
import com.stericson.RootTools.exceptions.RootDeniedException;
import com.stericson.RootTools.execution.CommandCapture;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Install extends Activity{
private static ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install);
Button bInstall = (Button) findViewById(R.id.bInstallTheme);
bInstall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog();
}
});
}
public void showDialog(){
progressDialog = ProgressDialog.show(Install.this, "", "Installing Theme", true);
Thread thread = new Thread();
thread.start();
}
public void run(){
try{
Thread.sleep(1000);
CommandCapture command = new CommandCapture(0, "su", "sh /sdcard/plasma/scripts/install.sh");
try {
RootTools.getShell(true).add(command).waitForFinish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (RootDeniedException e) {
e.printStackTrace();
}
}catch (InterruptedException e){
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
private static Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
So, am I doing something wrong? Why won't it run my code? Thanks!
The thread doesn't know what to run. Change
public class Install extends Activity{
to
public class Install extends Activity implements Runnable {
and change
Thread thread = new Thread();
to
Thread thread = new Thread(this);

Categories

Resources