I send a string from android to C# and from C# to android
it works on simulator but does't work on real android device
My phone using android 2.3
here is my code on Android:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
hienthi_lv_tab2 = (ListView) findViewById(R.id.lvhienthi);
chuoi = (EditText) findViewById(R.id.string);
ipserver = (EditText) findViewById(R.id.ipserver);
txt = (TextView) findViewById(R.id.Show);
quit = (Button) findViewById(R.id.quit);
connect = (Button) findViewById(R.id.Connect);
send = (Button) findViewById(R.id.Send);
quit.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
OUT_message = chuoi.getText().toString();
new Thread(new Runnable() {
final Handler handler = new Handler();
final Runnable updateUI2 = new Runnable() {
public void run() {
// TODO Auto-generated method stub
OUT_message = "Android: " + OUT_message;
add_chuoi(OUT_message);
}
};
public void run() {
// TODO Auto-generated method stub
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
out.println(OUT_message);
out.flush();
handler.post(updateUI2);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
Thread C_thread = new Thread(new ClientThread());
C_thread.start();
}
});
connect.setVisibility(1);
connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
connect.setVisibility(v.GONE);
Thread C_thread = new Thread(new ClientThread());
C_thread.start();
}
});
}
public class ClientThread implements Runnable {
final Handler handler = new Handler();
final Runnable updateUI = new Runnable() {
public void run() {
// TODO Auto-generated method stub
txt.setText(IN_message);
IN_message = "Server: " + IN_message;
add_chuoi(IN_message);
}
};
public void run() {
// TODO Auto-generated method stub
try {
IP = ipserver.getText().toString();
serverAddr = InetAddress.getByName(IP);
state_connnect = true;
Scanner in;
while (state_connnect) {
s = new Socket(serverAddr, 4444);
in = new Scanner(s.getInputStream());
IN_message = in.nextLine();
handler.post(updateUI);
in.close();
s.close();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void add_chuoi(String chuoi) {
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array_operator);
array_operator.add(chuoi);
hienthi_lv_tab2.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
here is my code on C#:
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
String hostname = "";
System.Net.IPHostEntry ip = new IPHostEntry();
hostname = System.Net.Dns.GetHostName();
ip = System.Net.Dns.GetHostByName(hostname);
lblhostname.Text = "Tên Server : " + ip.HostName;
foreach (System.Net.IPAddress listip in ip.AddressList)
{
lblip.Text ="Địa Chỉ IP Server : "+listip.ToString();
IPAddress ipAd = IPAddress.Parse(listip.ToString());
myList = new TcpListener(ipAd, 4444);
myList.Start();
}
}
void connect()
{
txt_show.Text="Waitting for connect from android...";
while (true)
{
server_socket = myList.AcceptSocket();
byte[] data_rec = new byte[1024];
int k = server_socket.Receive(data_rec);
char cc;
String mes = null;
for (int i = 0; i < k - 1; i++)
{
cc = Convert.ToChar(data_rec[i]);
mes += cc.ToString();
}
if (mes != null)
{
string_rec = mes.ToString();
txt_show.Text += Environment.NewLine + "Android: " + mes;
}
}
}
private void btn_send_Click(object sender, EventArgs e)
{
String data_send = txt_send.Text;
ASCIIEncoding asen = new ASCIIEncoding();
server_socket.Send(asen.GetBytes(data_send));
txt_show.Text += Environment.NewLine + "Server : " + txt_send.Text;
txt_send.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
S_thread = new Thread(connect);
S_thread.Start();
}
and this is logcat:
FATAL EXCEPTION:Thread-10 java.util.NoSuchElementException
at java.util.Scanner.nextLine(Scanner.java:1417)
at iNET.Android.Thread_TCP.ThreadActivity$ClientThread.run(ThreadActivity.java:207)
at java.lang.Thread.run(Thread.java:1019)
thanks all!
Not fully sure, But my guess is you are using different private network in Mobile and Pc. That's why you can send data while using emulator ( because both in pc) but not able to send using mobile.
After your comments I think your pc is in a private network. So you can not send message from the android application using the entered ip.
Related
On the MainActivity.java I have a method that connect with a server:
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
I'm calling this method from onTouchEvent():
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (is_start == true)
{
response = Get("http://10.0.0.2:8098/?cmd=start");
is_start = false;
}
else
{
response = Get("http://10.0.0.2:8098/?cmd=stop");
is_start = true;
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
textforthespeacch = a;
MainActivity.currentActivity.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
circlePath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
So now i'm connecting all the time to 10.0.0.2:8098
But that's when i connect my android device on my network on my pc room.
But if i move to the living room and connect to the network there a differenet network with another pc the pc ip is differenet in this case: 10.0.0.3:8099
So i added a button click event to the MainActivity.java:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
}
});
}
Inside the button click event I want to check after connected to the network with a wifi if the pc ip is 10.0.0.3:8099 or 10.0.0.2:8098
I need that it will try to connect to this servers and if success then to set to a global variable global string the ip.
I added a global variable: string ipaddress
Now i use static address in my code but i need to check which ip address is correct and then to set this ip to the variable which i will use later in my code as the ip address.
How do I make the checking in the button click event ?
This is what i tried now:
At the top of my MainActivity i added:
private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
Socket socket = null;
Then in the onCreate:
ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;
addListenerOnButton();
new Thread(new ClientThread()).start();
Then
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try {
String str = btnClick.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And the ClientThread
class ClientThread implements Runnable {
#Override
public void run() {
for (int i=0; i<ipaddresses.length; i++)
{
try
{
InetAddress serverAddr = InetAddress.getByName(ipaddresses[i]);
socket = new Socket(serverAddr, ipports[i]);
} catch (UnknownHostException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
This is a screenshot of the exception message i'm getting:
The exception is on the line:
new OutputStreamWriter(socket.getOutputStream())),
You must open sockets to check server connectivity. Here is an example on you send strings to server on click event:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8099;
private static final String SERVER_IP = "10.0.0.3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
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);
} 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();
}
}
}
}
So if you get an exception trying to connect to server, it means you haven't connectivity.
UPDATE: ok so I kept trying to press send until I received the java.net.SocketException: sendto failed: EPIPE (Broken pipe) exception as a toast message once and then there was no activity once again when I pressed the send button. Meaning I didn't get the exception again.
I have two apps where one acts as the server and the other as a client. I was able to send a message from the server to the client like this
dataOutputStream.writeUTF("hello");
basically as a hardcoded string
but when I added a textfield and a button to the server app and tried listening to the onClick like this
sendChatbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
dataOutputStream.writeUTF(chatMsg);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
}
}
});
Absolutely NOTHING happened when I press the SEND button and the client did not receive any message, I don't even get any exception as a toast. By the way I am able to send messages from the client to the server and the server receives the client's messages but the client doesn't get any messages from the server.
The logcat although shows this:
08-09 04:13:45.694: E/LocSvc_adapter(761): E/virtual loc_api_adapter_err LocApiV02Adapter::injectPosition(double, double, float):632]: error! status = eLOC_CLIENT_FAILURE_INVALID_PARAMETER, inject_pos_ind.status = UNKNOWN
08-09 04:15:25.220: A/ActivityManager(761): Service ServiceRecord{42e78d58 u0 com.estrongs.android.pop/com.estrongs.android.ui.notification.ESTaskService} in process ProcessRecord{449c4320 9734:com.estrongs.android.pop/u0a245} not same as in map: null
08-09 04:16:06.444: E/AudioStreamOutALSA(269): PCM_Write set_amp_mode,1
Here's my Server code:
public class ServerActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
EditText chatBoxText;
Button sendChatbtn, startGameBtn;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_socket);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
chatBoxText=(EditText) findViewById(R.id.chatBox);
sendChatbtn=(Button) findViewById(R.id.sendChatButton);
startGameBtn=(Button) findViewById(R.id.startGamebutton);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
closeSockets();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
String chatMsg = chatBoxText.getText().toString();
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
ServerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
String messageFromClient = "";
//If no message sent from client, this code will block the program
messageFromClient = dataInputStream.readUTF();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
ServerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
sendChatbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
dataOutputStream.writeUTF(chatMsg);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
}
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
final String errMsg = e.toString();
ServerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(errMsg);
}
});
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
return ip;
}
public void closeSockets()
{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
Here's the Client Code:
public class ClientActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
EditText welcomeMsg;
private MyClientTask myClientTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
editTextAddress = (EditText) findViewById(R.id.address);
editTextPort = (EditText) findViewById(R.id.port);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
textResponse = (TextView) findViewById(R.id.response);
welcomeMsg = (EditText)findViewById(R.id.welcomemsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textResponse.setText("");
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
String tMsg = welcomeMsg.getText().toString();
if(tMsg.equals("")){
tMsg = null;
Toast.makeText(ClientActivity.this, "No Welcome Msg sent", Toast.LENGTH_SHORT).show();
}
MyClientTask myClientTask = new MyClientTask(editTextAddress
.getText().toString(), Integer.parseInt(editTextPort
.getText().toString()),
tMsg);
myClientTask.execute();
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String msgToServer;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
if(msgToServer != null){
dataOutputStream.writeUTF(msgToServer);
}
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
return null;
}
protected void CloseSockets()
{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
protected void onDestroy()
{
myClientTask.CloseSockets();
super.onDestroy();
}
}
You are not updating the chatMsg string after the onClick, so it initializes as a zero length string, and does not change.
When onClick occurs, you need to get the current string from your TextView:
#Override
public void onClick(View v) {
// add this!!!
chatMsg = chatBoxText.getText().toString();
try {
dataOutputStream.writeUTF(chatMsg);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
}
}
I am using Jsoup to parse a part of a website and then put it into a string. I want to visualize this string into a textView, but since only the thread that had created the textView can modify it i need to pass the value of the string into the main thread. how?
This is the code: (ignore the tabhost stuff)
public class NewsAndAnnouncements extends Activity {
TabHost host;
FlyOutContainer container;
Button bttoggle;
Button bt1;
String loggity;
TextView tv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.container = (FlyOutContainer) this.getLayoutInflater().inflate(
R.layout.newsandannouncements, null);
this.setContentView(container);
host = (TabHost) findViewById(R.id.tabhost);
host.setup();
TabSpec specs = host.newTabSpec("TAGGITY EINZ");
specs.setContent(R.id.tab1);
specs.setIndicator("News");
host.addTab(specs);
specs = host.newTabSpec("TAGGITY ZWEI");
specs.setContent(R.id.tab2);
specs.setIndicator("Notices");
host.addTab(specs);
specs = host.newTabSpec("TAGGITY DREI");
specs.setContent(R.id.tab3);
specs.setIndicator("Events");
host.addTab(specs);
tv1 = (TextView) findViewById(R.id.textView1);
/*
* bttoggle = (Button) findViewById(R.id.bttoggle); bt1 = (Button)
* findViewById(R.id.Button1);
*
* bttoggle.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View v) { // TODO Auto-generated method
* container.toggleMenu(); } });
*
* bt1.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View v) { // TODO Auto-generated method
* container.toggleMenu(); } });
*/
Thread newsThread = new Thread() {
public void run() {
Document doc = null;
try {
doc = Jsoup
.connect(
"http://acs.bg/Home/About_ACS/News_and_Events/News.aspx")
.get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Elements myin = doc.getElementsByClass("news_list");
loggity = myin.toString();
Log.i("ELEMENTS HTML", loggity);
}
};
newsThread.start();
tv1.setText(loggity);
}
}
Try using AsyncTask instead of the Thread. To modify views on your ui thread use the runOnUiThread() method in your activity.
runOnUiThread(new Runnable() {
#Override
public void run() {
tv1.setText("...");
}
});
Use an AsyncTask instead of a raw Thread:
new AsyncTask<URL, Object, Document>() {
protected Document doInBackground(URL... urls) {
// parse URL and return document
}
protected void onPostExecute(Document result) {
// this runs in UI thread
// show document in UI
}
}).execute(myURL);
There are two ways to d it-
1)- Using AsyncTask
2)- Using Handler
Thread newsThread = new Thread()
{
public void run()
{
Document doc = null;
try {
doc = Jsoup
.connect(
"http://acs.bg/Home/About_ACS/News_and_Events/News.aspx")
.get();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Elements myin = doc.getElementsByClass("news_list");
loggity = myin.toString();
mHandler.post(new Runnable()
{
#Override
public void run()
{
try
{
tv1.setText(loggity);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
Log.i("ELEMENTS HTML", loggity);
}
};
newsThread.start();
You can initialize the Hanlder in the start.
try this sample code, don't know if this is the better way:
public class MainThread {
public static void main(String args[]) {
Thread2 t2 = new Thread2();
Thread nextThread = new Thread(t2);
nextThread.start();
try {
nextThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println();
System.out.println(t2.getStr());
}
private static class Thread2 implements Runnable{
private String str;
#Override
public void run() {
setStr("T2 Thread String");
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
}
I want to retrieve array of string from my webservice and have to show it in my android project in Toast I coded it like this but its not showing anything can anyone please help me out :(
public class InsertData extends MainActivity {
EditText txt_1,txt_2;
Button SetData,GetData;
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://10.0.2.2:49371/WebService1.asmx";
private static String SOAP_ACTION = "http://tempuri.org/GetData";
private static String SOAP_ACTION2 = "http://tempuri.org/ThrowData";
private static String METHOD_NAME = "GetData";
private static String METHOD_NAME2 = "ThrowData";
String DateTime;
String IMEI;
//private static String[] arrString = new String[40];
Long time = (long) 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.setdata);
txt_1 = (EditText) findViewById (R.id.editText1);
txt_2 = (EditText) findViewById (R.id.editText2);
SetData = (Button) findViewById(R.id.button1);
GetData = (Button) findViewById(R.id.button2);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy : HH:mm:ss");
DateTime = df.format(c.getTime());
txt_1.setText(DateTime);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
txt_2.setText(IMEI);
}
public void OnClickGetData(View view){
final Handler hnd = new Handler();
final Runnable r = new Runnable(){
public void run(){
SoapObject obj = new SoapObject(NAMESPACE,METHOD_NAME2);
SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelop.setOutputSoapObject(obj);
HttpTransportSE androidHTTP = new HttpTransportSE(URL,7000);
try{
androidHTTP.call(SOAP_ACTION2, envelop);
}catch(IOException e){
e.printStackTrace();
}catch(XmlPullParserException e){
e.printStackTrace();
}
try {
#SuppressWarnings("unchecked")
java.util.Vector<String> result11 = (java.util.Vector<String>)envelop.getResponse(); // to get List of Strings from the SoapObject.. then
final ArrayList<String> prjList = new ArrayList<String>();
for(String cs : result11)
{
prjList.add(cs);
}
hnd.post(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i <prjList.size();i++){
//arrString[i] = reques.toString();
String Nu = prjList(i).toString();
Toast.makeText(InsertData.this,Nu , Toast.LENGTH_LONG).show();
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
} catch (SoapFault e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
public void OnClickSetData(final View view)
{
final Handler hnd = new Handler();
final Runnable ru = new Runnable(){
//#SuppressWarnings("deprecation")
#Override
public void run() {
// TODO Auto-generated method stub
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
PropertyInfo pi2 = new PropertyInfo();
pi.namespace = NAMESPACE;
pi.setName("Date");
pi2.setName("IMEI_NO");
pi.setValue(DateTime);
pi2.setValue(IMEI);
pi.setType(String.class);
pi2.setType(String.class);
request.addProperty(pi);
request.addProperty(pi2);
SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelop.dotNet = true;
envelop.setOutputSoapObject(request);
HttpTransportSE androidHttp = new HttpTransportSE(URL,7000);
try
{
androidHttp.call(SOAP_ACTION, envelop);
}
catch(IOException e)
{
e.printStackTrace();
}
catch (XmlPullParserException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(ru).start();
}
}
and here is my webservice which is made in .NET its retriving data when i m retrieving it in my browser but not showing in android application
public string[] ThrowData()
{
string ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
SqlCommand cmd = new SqlCommand();
List<string> data = new List<string>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
cmd.CommandText = "SELECT IMEI_NO FROM MAD";
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
data.Add(dr["IMEI_NO"].ToString());
}
}
return data.ToArray();
}
Have a Log statement to see if its entering the loop and is receiving the expected value. If it does that but does not show the Toast, its because you are not showing the Toast on the UI thread. If you want to show any change on the UI, you need to do them in UI thread. To show toast here, you may use runOnUiThread. Eg:
YourActivityName.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(InsertData.this,Nu , Toast.LENGTH_LONG).show();
}
});
Edit:
For knowing more about Log statements see Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one? and http://developer.android.com/reference/android/util/Log.html
Hope this helps.
In my android project, i have successfully passed 2 strings[(TV ON(by button 1) and TV OFF(by button 2)] from my android phone to my PC by 2 simple button using WiFi.but here i need to pass 2 strings using single toggle button [(TV ON(click on toggle button) and TV OFF(again click on toggle button)] instead of 2 simple button(which is mentioned above).
sorry for my bad English.
thanks in adv.
java code-
package com.example.wifitoggle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.widget.ToggleButton;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private Button button;
private Button button1;
private ToggleButton toggleButton1;
private String messsage;
int port = 0; //
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// etIP = (EditText) findViewById(R.id.editText1);
// etPort = (EditText) findViewById(R.id.editText2);
//etMsg = (EditText) findViewById(R.id.editText3);
button = (Button) findViewById(R.id.button1);
button1 = (Button) findViewById(R.id.button2);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV ON" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV OFF" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
}
}
Try this..
toggleButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//do something if on
}else{
//do something if off
}
});
An alternative to this
toggleButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((toggleButton1.isChecked()))
{
//do something if on
}
else
{
//do something if off
}
}
});
here is the correct code
mToggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mToggleButton.isChecked()) {
messsage = "TV ON";
Log.d("On", "Button On" + messsage);
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new
// Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4", 2000);
printwriter = new PrintWriter(client
.getOutputStream(), true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} else {
messsage = "TV OFF";
Log.d("off", "Button off " + messsage);// etMsg.getText().toString();
// etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new
// Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4", 2000);
printwriter = new PrintWriter(client
.getOutputStream(), true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
});
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4", 2000);
printwriter = new PrintWriter(client.getOutputStream(),
true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();