i have a problem with android application that contain a AsyncTask. When i try to debug it androidStudio bring me to a section of comments of asynctask. i don't understand if this problem is caused by problem on library or if the problem is on the logic of costruction: i have a class that
-fetch an integer from UI then
-lunch asynctask that connect to a server and receive the data (put its on a variable), then
-redraw the ui and set out the data on a textview
like the code:
public class MainActivity extends Activity
{
LinearLayout spazioGen;
TextView[] cell;
LinearLayout[] rows;
LinearLayout def;
LinearLayout solution;
private Socket client;
private PrintWriter printwriter;
private BufferedReader in;
private EditText textField;
private TextView serverOut;
private Button button;
private String messsage;
private String inputLine;
private Integer dimensionChoosed = 10;
private String word1 = "";
private String word2 = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.dimension);
button = (Button) findViewById(R.id.findCenter);
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
dimensionChoosed = Integer.parseInt(messsage.toString());
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
createGriglia();
}
});
}
private void createGriglia(Integer dimensionChoosed)
{
int i,j;
spazioGen = new LinearLayout(this);
spazioGen.setOrientation(LinearLayout.VERTICAL);
spazioGen.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
spazioGen.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_ext));
spazioGen.setPadding(5, 5, 5, 5);
//create an array of textview to fillup with data received from server
setContentView(spazioGen);
}
private class SendMessage extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{
client = new Socket("192.168.0.104", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.println(messsage); // write the message to output stream
printwriter.flush();
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // get the client message
String message = "";
while ((message = bufferedReader.readLine()) != null && !(message.equals("flag")))
{
word1 = message;
//do stuff with data received
}
while ((message = bufferedReader.readLine()) != null)
{
word2 = message;
//do stuff with data received
}
inputStreamReader.close();
System.out.println(message);
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
createGriglia(dimensionChoosed);
}
}
}
Thanks in advance
thanks to everybody who helps me.
I solved this problem installing latest version of android studio.
I hope this can help who got my same problem
Related
What I'm trying to do is to constantly update a TextView once I read a new line from a BufferedReader that reads serial data from a Bluetooth module. Currently, the data gets displayed once, then the connection is closed and nothing happens.
Shouldn't content() and refresh() functions call each other up endlessly, so that the connection is never closed?
Here's my code so far:
public class MainActivity extends AppCompatActivity {
static final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String line;
int cnt = 0;
BluetoothSocket btSocket = null;
InputStream in = null;
BufferedReader br = null;
TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = (TextView)findViewById(R.id.data);
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
System.out.println(bt.getBondedDevices());
BluetoothDevice hc06 = bt.getRemoteDevice("00:14:03:05:5A:94");
System.out.println(hc06.getName());
do {
try {
btSocket = hc06.createInsecureRfcommSocketToServiceRecord(mUUID);
System.out.println(btSocket);
btSocket.connect();
System.out.println(btSocket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
cnt++;
} while(!btSocket.isConnected()&& (cnt < 5));
content();
try {
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void content() {
try {
in = btSocket.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
line = br.readLine();
System.out.println(line);
refresh();
} catch (IOException e) {
e.printStackTrace();
}
}
private void refresh(){
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
data.setText(line);
content();
}
};
handler.postDelayed(runnable, 100);
}
}
Here I created a fan activity and every time when I Click to any button
It Start Fan-Socket class and create a new Socket on every click button.
But I am getting a delay when I Click buttons continueosly.
how can I Send a multiple request using single Socket and on each button
click how can I send a msg string through the Socket??
Is there is Something that creating a buffer and putting a value in
that buffer and call each buffer value on every click.
if it so How can I do that.. ??
Kindly help me to solve this issue as
I am new in android programming I can not able to solve this problem
from several day
Fan Activity:
public class FAN extends AppCompatActivity {
private Button buttonOn;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_fan);
buttonOn = (Button) findViewById(id.Buttonon);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
buttonOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (turnOn) {
int tmpInt = 2;
String FAN = String.valueOf(tmpInt); //Converting int to string.
FAN_SOCKET b1 = new FAN_SOCKET(); // calling class fan socket
b1.execute(FAN); //calling fan-socket class and pass the the 2 value through it.
turnOn = false;
}
else {
int tmpInt = 0;
String FAN = String.valueOf(tmpInt); //Converting int to string.
FAN_SOCKET b1 = new FAN_SOCKET(); // calling class fan socket
b1.execute(FAN); //sending value to socket.
turnOn = true;
}
}
});
Fan-Socket Class:
class FAN_SOCKET extends AsyncTask<String,Void,String>{
Socket socket = null;
PrintWriter pw;
String response;
#Override
protected String doInBackground(String... voids) {
String massage = null;
try {
massage = voids[0];
socket = new Socket("192.168.0.79",8888 );
pw = new PrintWriter(socket.getOutputStream());
pw.write(massage);
try {
pw.flush();
pw.close();
socket.close();
} catch (SocketException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I'm trying to send commands from my phone to my computer using Sockets.
I've tryed the answers here:
Android and PC Socket connection
But after some digging i found out that you need to use a Async task so i tryed this:
Using AsyncTask for android network connection
But for some reason my socket times out. Is there a way to find out why? because from the error i can't tell:
The error from Logcat:
And this is the client code:
public class MainActivity extends AppCompatActivity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message;
private static final int SERVERPORT = ####;
private static final String SERVER_IP = "########";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
}
public void onClick(View view) {
message = textField.getText().toString();
textField.setText(""); // Reset the text field to blank
new AsyncAction().execute();
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
System.out.println("background running");
System.out.println(message);
client = new Socket(SERVER_IP, SERVERPORT); // connect to server
System.out.println(client.isConnected());
System.out.println("test");
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(message); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
I wrote a Server for this in Java and tested it in the emulator.
I had two things to do :
The server IP is "10.0.2.2" if you are using an Android Emulator. LocalHost is de Emulator Virtual Machine.
Your application needs Permission Internet in manifest
Here is the server Code
/**
*
* #author Jean-Pierre
*/
public class SocketServer {
private static final int portnumber = 4444;
public static void main(String[] args) {
SocketServer socketServer = new SocketServer();
socketServer.run();
}
/**
* Reads a String from the client
* Converts it to Uppercase
* and sends it Back.
*/
private void run() {
try {
ServerSocket serverSocket = new ServerSocket(portnumber);
Socket clientSocket = serverSocket.accept();
System.out.println("connected with :" + clientSocket.getInetAddress());
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
InputStreamReader is =
new InputStreamReader(clientSocket.getInputStream());
BufferedReader in =
new BufferedReader(is);
while (true) {
String line = in.readLine();
if (line != null) {
System.out.println("recieved:" + line);
out.println(line.toUpperCase());
}
}
} catch (IOException ex) {
Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
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);
}
I did a TCP client on Java and works fine, but when I import the class to my Android project, it doesn't work.
Android code:
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.SEND);
ssid = (EditText) findViewById(R.id.textSsid);
pass = (EditText) findViewById(R.id.textPass);
debugText = (EditText) findViewById(R.id.debugText);
cliente = new ClienteTCP();
debugText.setText("Version 1-prealpha");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
demo(v);
}
});
}
public void demo(View view) {
cliente.configure(ssid.getText(), pass.getText());
CharSequence cs = cliente.sendMessage("Hola Mundo");
if ( cs != null)
debugText.setText(cs);
else
debugText.setText("ERROR OCURRED");
}
// ...
I always get the "ERROR OCURRED" message, I try to use another IPs, but all of them works fine on Java and not on android.
The class code:
private CharSequence SSID, pass;
private String HOST = "52.28.45.92"; // My external server i tried with localhot server too ...
// of course i have a server aplication running hahaha
private int PORT = 5000;
private Socket s;
private DataOutputStream oms;
// ...
public CharSequence sendMessage(String ms) {
DataInputStream ims;
CharSequence data = null;
try {
s = new Socket(HOST,PORT);
oms = new DataOutputStream(s.getOutputStream());
ims = new DataInputStream(s.getInputStream());
oms.writeUTF(ms+getFull());
data = ims.readUTF();
oms.close();
ims.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
I think it can be due to my emulator, any ideas? is the code wrong?
EDIT: Server code:
# ...
# Wrote on Python:
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data+'\r\n')
conn.close()