I can't understand why the EditText gives me a strange value that is saved in the variables I use.
For example, when I save the content of these EditText to some variables, this values is saved:
variable: android.widget.EditText{41940958 VFED..CL .F...... 24,158-456,225 #7f080002 app:id/etHost}
This is my code:
public class MainActivity extends Activity {
Button btnConnetti;
EditText etUsername;
EditText etPassword;
EditText etHost;
String host=null;
String username=null;
String password=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnConnetti = (Button) findViewById(R.id.btnConnetti);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
etHost = (EditText) findViewById(R.id.etHost);
btnConnetti.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
host = etHost.toString().trim();
username = etUsername.toString().trim();
password = etPassword.toString().trim();
Log.d("deb","host: "+etHost.toString());
if(host.isEmpty() || username.isEmpty() || password.isEmpty())
{
new AlertDialog.Builder(getApplicationContext())
.setTitle("Login fallito!")
.setMessage("Compilare tutti i campi richiesti.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
return;
}
}).create().show();
}
else
{
myClickHandler(getCurrentFocus());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void myClickHandler(View view) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new InviaDati(host,username,password).execute();
} else {
// display error
}
}
}
class InviaDati extends AsyncTask<String, Integer, Void>
{
InputStream is = null;
String host,username,password;
public InviaDati(String host,String username,String password)
{
this.host=host;
this.username=username;
this.password=password;
}
#Override
protected void onPreExecute()
{
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("deb",host+"/callback.php?username="+username+"&password="+password);
try {
URL url = new URL(host+"/callback.php?username="+username+"&password="+password);
Log.d("deb",host+"/callback.php?username="+username+"&password="+password);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("DEBUG_TAG", "The response is: " + response);
is = conn.getInputStream();
// Makes sure that the InputStream is closed after the app is
// finished using it.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
}
}
wrong in the following
etHost.toString().trim();
do like
etHost.getText().toString().trim();
use
host = etHost.getText().toString().trim();
username = etUsername.getText().toString().trim();
password = etPassword.getText().toString().trim();
call getText() for getting value from EditText instead of only calling toString()
host = etHost.toString().trim();
you are storing text description of EditText inside the string.. what you want is the actual text inside it.. change it to
host = etHost.getText().toString();
Related
I know that there is a lot of questions about this, but I'm desperated...
I'm trying to show a Dialog while doing an AsyncTask, that must be easy but I'm no able to do it...
I had tried with .execute() and .get() and I had put a for to make the task take a long time, but nothing..
Here is my class:
public class OrdenNuevaActivity extends Activity {
#Override
protected void onCreate(Bundle bundle) {
Log.v("FLUJO", this.getClass().toString());
super.onCreate(bundle);
setContentView(R.layout.activity_orden_nueva);
aceptarOrdenNuevaButton = (Button) findViewById(R.id.aceptarOrdenNuevaButton);
aceptarOrdenNuevaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase tareaCambiarEstadoOrdenEnBDServer = new TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(idOrden, Estados.ACEPTADO,OrdenNuevaActivity.this);
try {
tareaCambiarEstadoOrdenEnBDServer.execute();
} catch (Exception e) {
e.printStackTrace();
}
Toast toast1 = Toast.makeText(getApplicationContext(), "Orden Aceptada", Toast.LENGTH_SHORT);
toast1.show();
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
UtilsVictor.addPuebloAlAceptarOrden(context,terminoOrdenAceptadaDetalleTV.getText().toString());
finish();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(OrdenNuevaActivity.this).create();
alertDialog.setTitle("ERROR!");
alertDialog.setMessage("NO hay cobertura, vuelva a intentarlo mas tarde");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setIcon(R.drawable.common_signin_btn_icon_normal_light);
alertDialog.show();
}
}
});
}
public class TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase extends AsyncTask<String,Integer,Boolean>{
private static final String TAG = "AppMovil";
private Integer mOrdenId;
private String mEstadoString;
boolean resul = true;
boolean tareaRealizada = false;
boolean catchPasado = false;
private Context mContext;
private ProgressDialog mPD;
public TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(Integer idO ,String estadoO, Context cntx) {
mContext = cntx;
mOrdenId = idO;
mEstadoString = estadoO;
mPD = new ProgressDialog(mContext);
}
public boolean getResultado(){
return resul;
}
public boolean getTareaRealizada(){
return tareaRealizada;
}
public boolean getCatchPasado(){
return catchPasado;
}
#Override
protected void onPreExecute() {
mPD.setTitle("Please Wait..");
mPD.setMessage("Loading...");
mPD.setCancelable(false);
mPD.show();
}
#Override
protected Boolean doInBackground(String... params) {
for(int i=0; i<999999;i++){
Log.v("A", "A");
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("id", mOrdenId);
jsonObject.put("estado", mEstadoString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URIS.URI_TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString);
post.setHeader("content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
post.setEntity(stringEntity);
HttpResponse response = httpClient.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode >200 & responseCode < 400) {
Log.v(TAG, "Orden Enviada OK a nuestro Server");
tareaRealizada = true;
resul = true;
} else {
Log.v(TAG, "FALLO al Enviar Orden a nuestro Server");
resul = false;
tareaRealizada = true;
}
} catch (Exception e) {
catchPasado = true;
resul = false;
e.printStackTrace();
}
return resul;
}
#Override
protected void onCancelled() {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onPostExecute(Boolean result) {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
Where is the mistake?
I've created a Textview with a null value and button in my my Mainactivity and fetched some data from sql database server using AsyncTask method on button click and stored in to my textview. Then I called an intent to another activity activity2 to show something and I returned to my Mainactivity using intent.But I can't view the previously set data in textview. It shows null value.I want to set it previously fetched data.how can I set that?
public class MainActivity extends Activity {
public ImageView prev, now, next;
String depvisitid;
public TextView display, bottom, ptname, docname;
public String tokenh,tokenext,tokennow;
public String pname,pnamenext,pnamenow;
public boolean status;
public String drname,current;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (ImageView) findViewById(R.id.previmg);
now = (ImageView) findViewById(R.id.token);
next = (ImageView) findViewById(R.id.nextimg);
display = (TextView) findViewById(R.id.textView2);
ptname = (TextView) findViewById(R.id.textView3);
bottom = (TextView) findViewById(R.id.tokennum);
docname = (TextView) findViewById(R.id.textView);
// Connect runner = new Connect();
// runner.execute();
The setOnClickListener method:
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String sleepTime = time.getText().toString();
}
});
now.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
display.setText(tokenh);
ConnectNow nw = new ConnectNow();
nw.execute();
Intent i = new Intent(getApplicationContext(), StatusUpdate.class);
i.putExtra("patientname", pname);
i.putExtra("tokenno", tokenh);
i.putExtra("depvisitid", depvisitid);
startActivity(i);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Connect runner = new Connect();
runner.execute();
}
});
}
The onBackPressed:
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
// finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
class Connect extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet reset1 = null;
try {
reset1 = stmt.executeQuery(" select a.TOKENNO,b.FNAME,a.TOKENSTATUS,e.EMPFNAME,a.DEPVISITID from DEPTVISIT a,PATIENT_MASTER b,APP_EMPLOYEE e where a.PID=b.PID and (a.TOKENSTATUS='O' or a.TOKENSTATUS='S' ) and e.EMPID=a.EMPID and a.EMPID=2 and CONVERT(date,a.OPDATE)='2016-05-09' order by TOKENNO desc;");
while (reset1.next()) {
tokenh = reset1.getString("TOKENNO");
pname = reset1.getString("FNAME");
drname = reset1.getString("EMPFNAME");
depvisitid= reset1.getString("DEPVISITID");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return tokenh;
}
protected void onPostExecute(String result) {
bottom.setText(tokenh);
ptname.setText(pname);
docname.setText(drname);
}
}
The connect now class:
class ConnectNow extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "ssssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj****");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open****");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='S' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
System.out.println("status updated to S");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return status;
}
protected void onPostExecute(Boolean result) {
bottom.setText(tokenh);
ptname.setText(pnamenext);
docname.setText(drname);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settings=new Intent(getApplicationContext(),Settings.class);
startActivity(settings);
}
return super.onOptionsItemSelected(item);
}
}
SECOND ACTIVITY StatusUdate.java:
public class StatusUpdate extends Activity {
public String tokenstatN, tokenstatY;
Button visited, notvisited;
String pname,tokennum,depvisitid;
TextView patnam,tknum;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statusupdate);
visited = (Button) findViewById(R.id.button);
notvisited = (Button) findViewById(R.id.button2);
patnam= (TextView) findViewById(R.id.textView4);
tknum= (TextView) findViewById(R.id.textView5);
Bundle extras = getIntent().getExtras();
pname = extras.getString("patientname");
tokennum = extras.getString("tokenno");
depvisitid = extras.getString("depvisitid");
patnam.setText(pname);
tknum.setText(tokennum);
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
The NotVisit class:
class NotVisit extends AsyncTask<String, String, Boolean> {
boolean status = false;
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openhhhh");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "openlll");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='N' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
Log.d("status", String.valueOf(status));
return status;
}
}
Whenever you wish to go to previous screen, Always finish the Activity that is on top. Here in your case, You are always creating new instance of MainActivity and this is the reason for getting null when you go back. Try using this in your StatusUpdate.java.
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
StatusUpdate.this.finish();
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
StatusUpdate.this.finish();
}
});
You can store the retrieved text in a static field of your activity class, but it's better save and restore it on activity recreation.So modify your activity like:
#Override
public void onCreate(Bundle b) {
// activity initialization
// textView = ...
if (b != null) {
textView.setText(b.getString("dbtext"));
}
}
and
#Override
protected void onSaveInstanceState(Bundle b) {
super.onSaveInstanceState(b);
b.putString("dbtext", textView.getText());
}
I had to establish a socket in ActivityA in normal and ready to send data,
but now I want to also be able to use the same socket connection to transmit the data in ActivityB.I have looked for information on the Internet, it seems can use the singleton.I studied for a few days, I still don't know how to start, even find some examples of exercises too, but still do not know how to use my original program.
I want to first establish between ActivityA and SERVER connection, and to pass a value to the SERVER, then press the button to switch to ActivityB, and also transmit values to SERVER
Give me some advice or teaching sites can be, so that I can continue to study it, thank you very much
Establish socket methods:
public class MainActivity extends Activity {
Button Btn_Wifi,Btn_Power,Btn_Flame;
Boolean connected=false;
Boolean powerstatus=false;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null ;
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView();
setListensers();
setButtonStatus();
}
private void mainView(){
Btn_Wifi = (Button) findViewById(R.id.Btn_Wifi);
Btn_Power = (Button) findViewById(R.id.Btn_Power);
Btn_Flame = (Button) findViewById(R.id.Btn_Flame);
}
private void setListensers(){
Btn_Wifi.setOnClickListener(BtnWifiOnClickListener);
Btn_Power.setOnClickListener(BtnPowerOnClickListener);
Btn_Flame.setOnClickListener(BtnFlameOnClickListener);
}
private void setButtonStatus(){
Btn_Power.setEnabled(false);
Btn_Flame.setEnabled(false);
}
Button.OnClickListener BtnWifiOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!connected){
try {
socket = new Socket("IP", PORT);
dataOutputStream = new DataOutputStream(socket.getOutputStream());//and stream
changeConnectionStatus(true);//change the connection status
}catch (UnknownHostException e) {
changeConnectionStatus(false);
}catch (IOException e) {
changeConnectionStatus(false);
}
}else{
try {//try to close the socket
socket.close();
changeConnectionStatus(false);//change the connection status
} catch (UnknownHostException e) {//catch and
changeConnectionStatus(false);
} catch (IOException e) {//catch and
changeConnectionStatus(false);
}
}
}
};
Button.OnClickListener BtnPowerOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!powerstatus){
try {
byte[] pon ={(byte) 0x10,(byte) 0x10};
dataOutputStream.write(pon);
dataOutputStream.flush();
PowerStatus(true);
}catch(Exception obj){
PowerStatus(false);
}
}else{
try {
byte[] poff ={(byte) 0x11,(byte) 0x11};
dataOutputStream.write(poff); //writeBytes(String str)
dataOutputStream.flush();
PowerStatus(false);
}catch(Exception obj){
PowerStatus(true);
}
PowerStatus(false);
}
}
};
Button.OnClickListener BtnFlameOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, FlameActivity.class);
startActivity(intent);
}
};
public void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
if(isConnected){//if connection established
Btn_Wifi.setText("CONNECTED");
Btn_Power.setEnabled(true);
}else{
Btn_Wifi.setText("NOT WIFI");
Btn_Power.setText("POWER OFF");
Btn_Power.setEnabled(false);
PowerStatus(false);
}
}
public void PowerStatus(Boolean isPowerOn) {
powerstatus=isPowerOn;//change variable
if(isPowerOn){//if connection established
Btn_Power.setText("POWER ON");
Btn_Flame.setText("SET FLAME");
Btn_Flame.setEnabled(true);
}else{
Btn_Power.setText("POWER OFF");
Btn_Flame.setText("CANT SET FLAME");
Btn_Flame.setEnabled(false);
}
}
}
You can certainly use it by declaring,i.e: in MainActivity which creates socket connection,static YourSocketClass objSocket // which creates connection and to use it in another Activity just called it as follow i.e:MainActivity.objSocket.yourMethod(any_param). by declaring static you can access it.
public static CommunicationClient objCommunicationClient;
public boolean setConnection(final String ipAddress, final Context context,
final boolean isFromSearch) {
class EstablishConnection extends AsyncTask<Void, Void, Boolean> {
ProgressDialog objDialog;
#Override
protected void onPreExecute() {
objDialog = new ProgressDialog(context);
objDialog.setMessage(context.getResources().getString(
R.string.strConnecting));
objDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
objDialog.show();
objDialog.setCancelable(false);
objDialog.setCanceledOnTouchOutside(false);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean isConnected = false;
boolean isValid = false;
StrictMode.setThreadPolicy(policy);
objCommunicationClient = new CommunicationClient(ipAddress);
isSocketInitiated = objCommunicationClient.initSocket();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
CommonUtils.SSID = info.getSSID();
if (!isSocketInitiated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.strCantConnect),
Toast.LENGTH_LONG).show();
}
});
} else {
isConnected = true;
if (!isFromSearch) {
CommonUtils.IP = ipAddress;
try {
objCommunicationClient.sendRequest(context,
"<APP_SPECIFIC>");
} catch (Exception e) {
e.printStackTrace();
}
} else {
isValid = isFromSearch;
}
if (isValid) {
final Intent objIntentToGraph = new Intent(context,
GraphDataActivity.class);
objIntentToGraph
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(objIntentToGraph);
overridePendingTransition(
R.anim.slide_in_right,
R.anim.slide_out_left);
finish();
}
});
}
}
return isConnected;
}
#Override
protected void onPostExecute(Boolean result) {
try {
objDialog.cancel();
} catch (Exception err) {
err.printStackTrace();
}
super.onPostExecute(result);
}
}
boolean status = false;
try {
status = new EstablishConnection().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return status;
}
}
// and in my other Activity i called it as
MainActivity_HomePage.objCommunicationClient.sendRequest(
context, CommonUtils.STOP_COMMAND); //send request is method which send message to server.
My goal is to create Java application which would be server, and Android(client) socket connection, and make Android phone listen to my commands send from a server. My question is, how should i make my Android phone always listen for incoming commands(Strings) pushed from Java application. What is a best choice ? Thread, Service ?
Here is my code : Server in java:
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
Android Client code:
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
DataOutputStream os;
public final String TAG = "CLIENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
ConnectThread thread = new ConnectThread();
thread.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ConnectThread extends AsyncTask<String, String, String> {
public ConnectThread() {
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.i(TAG,"Do in background");
return connect();
}
public String connect() {
try {
Log.i(TAG," creating socket");
socket = new Socket("192.168.1.10", 9000);
Log.i(TAG," socket created");
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
Log.i(TAG," Streams are set");
Log.i(TAG,"::"+is.readUTF().toString());
text.setText(is.readLine().toString());
return is.readLine().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
Log.d("fail", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("fail", e.toString());
}
return "nothing";
}
}
}
I have solved my problem. Im sending messages from my java server to android trough a socket, and android is always listening. Here is my code:
Java :
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeUTF("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
And android :
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
ObjectOutputStream os;
public final String TAG = "CLIENT";
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
handler = new Handler();
Thread x = new Thread(new ClientThread());
x.start();
handler = new Handler();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//
public class ClientThread implements Runnable {
public ClientThread() {
// TODO Auto-generated constructor stub
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String line = null;
while ((line = in.readUTF()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
}
}
Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().