How to use runOnUiThread in a class? - android

My code is designed to read a .txt file from a URL, and then display the text inside my textview. the problem is, I am using this code in a class. and getting this error- "cannot resolve method runOnUiThread". How do I fix this??
public class mydownloaderclass {
// this method is called from MainActivity
public static void checkForUpdates(Context context) {
new Thread() {
#Override
public void run() {
String path ="http://host.com/info.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView text = (TextView) findViewById(R.id.TextView1);
text.setText(bo.toString());
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
I tried using asynctask
public class readtextfile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL("https://www.dropbox.com/myfile.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
while ((line = in.readLine()) != null) {
//get lines
result += line;
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}

Create a Handler instead to execute statements on Main Thread like this
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//Write your RUN on UI Runnable code here
TextView text = (TextView) findViewById(R.id.TextView1);
text.setText(bo.toString());
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
} });

Try passing a view context. It can be the activity context where the text view is defined.
The runOnUiThread runs on the main looper so it required a UI context.
For that You can define a member field in the class where the Thread is defined and set it in the constructor. Or if the thread is in the activity itself. then simply set the context field in OnCreate and use it in the thread.
Hope this helps. :)
Let me know if this fixes it.

I would suggest you to use AsyncTask, android makes this class specially for doing some task on a working thread(doInBackgroung()) and then update UI in onPostExecute() method.

Related

How Android Async Task Works with UrlConnection

I am new with the android. I am developing an app that will load content from target url in file. If the url didn't work, it will contact our server to request the correct url. If still fail, then it will ask the url from user input dialog. And it will try to initialize again. I have code like this:
if (initialize(target)!=true) {
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("sns", getSerial(PREF_NAME));
jsonParam.put("code", pwd);
} catch (JSONException e) {
e.printStackTrace();
}
target = getContent(samURL + "/sam_ip", jsonParam);
if (initialize(target)!=true) {
askIpUserDialog();
}
}
and the initialize() as follow
private boolean initialize(String url) {
Boolean success = false;
if ((!url.trim().startsWith("http://")) && (!url.trim().startsWith("https://"))) {
url = "http://" + url;
}
if (url.endsWith("/")) {
url = url.substring(0,url.length()-1);
}
String sUrl = url + "/android_view";
URL pUrl;
HttpURLConnection urlConn = null;
try {
DataOutputStream printout;
DataInputStream input;
pUrl = new URL (sUrl);
urlConn = (HttpURLConnection) pUrl.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", pwd);
printout = new DataOutputStream(urlConn.getOutputStream());
String str = jsonParam.toString();
byte[] data = str.getBytes("UTF-8");
printout.write(data);
printout.flush();
printout.close ();
int HttpResult = urlConn.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
success = true;
WebView view=(WebView) this.findViewById(R.id.webView);
view.setWebChromeClient(new WebChromeClient());
view.setWebViewClient(new WebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(sUrl);
}else{
success = false;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(urlConn!=null)
urlConn.disconnect();
}
return success;
}
I just know that in android, url connection should run in separate thread. That's why I got the following error:
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
My question is, how do I use AsyncTask to avoid the error?
I saw there is doInBackground() which I can put the initialize() function there.
I saw also there is onPostExecute() event which I can check the result from the doInBackground(), but I don't understand yet how do I retrieve the return of initialize() which placed inside doInBackground()?
Bonus question, later I'd like to place all this job inside an intentservice. Do I need to stil use the asynctask? Does intentservice itself is an asynctask?
you can try some thing like this and also u can use a different thread
final Handler h = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
final File file = new File(path);
Log.i("path",path);
downloadFile(url[j], file);
h.post(new Runnable(){
#Override
public void run() {
txt.setText(""+jp);
jp++;
}
});
}
}
};
new Thread(r).start();
}
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
Log.i("len","" + contentLength);
Log.i("url1","Streaming from "+url+ "....");
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
Log.v("FileError" , e.toString());
return; // swallow a 404
} catch (IOException e) {
Log.v("FileError" , e.toString());
return; // swallow a 404
}
catch (Exception e) {
Log.v("FileError" , e.toString());
return; // swallow a 404
}
}
and also you cant access ui elements on different thread you have to use handler or run on ui thread.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
this.pd = ProgressDialog.show(this, "Loading..", "Please Wait...", true, false);
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected Void doInBackground(String... args) {
//do your stuff here }
}
}
Network traffic (and all other logic which takes some time to process) should always be handled by a background thread and never on the Main thread.
Use an ASyncTask to execute the logic.
private class YourTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// perform your network logic here
return "YourResult";
}
#Override
protected void onPostExecute(String result) {
// Update your screen with the results.
}
}
Call the ASyncTask in your code:
new YourTask().execute("");

Why can't I return a string from an AsyncTask?

I am trying to read an online txt file from my Dropbox and put its content into a string with an Asynctask but I can't manage to return my string.
My Code:
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String path ="https://dl.dropboxusercontent.com/u/29289946/PCGAMEDONWLOADER/Slots/All%20Games/Rows_available/link2.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
String album = bo.toString();
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return album;
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.loadingtext);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
Now eclipse underlines "album" next to return, so I can't use it in further operations.
Thanks for your help.
Why you run the UI thread to assign the data to a string...you can use it in side your thread.
Simply do in your doInBackground method()like:
bo.write(buffer); // Write Into Buffer.
String album = bo.toString();
return album;
And here your main problem is you define your String variable locally inside runInMainThread() method. Then how you access it out of its surrounding area. If you don't want to change your program then just define the String globally like:
public String doInBackGround()String...params){
String album = "";
.....
....
And asign the value anywhere... like album=bo.toString(); and return ....
You initialized album in this function:
runOnUiThread(new Runnable() {
#Override
public void run() {
String album = bo.toString();
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So it is only available in this scope. You could have seen this by checking what error Eclipse actually shows you.
It's because you declare your album String in your runOnUiThread, so it will not be known outside of it. Try to declare it in your onPostExecute like follow:
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String path ="https://dl.dropboxusercontent.com/u/29289946/PCGAMEDONWLOADER/Slots/All%20Games/Rows_available/link2.txt";
URL u = null;
//Declare it here as final
final String album=null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
album = bo.toString();
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return album;
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.loadingtext);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}

saving data to interal memory with async task (newboston tutorials sample) error it has progress bar

this is my first post here
i'm new, so be good with me!
i'm following travis's tutorials and it goes to saving data and using async task
i really focused but i can't find out whats wrong with my code, so i posted here! :
I added the logcat!
it worked without async and progress bar (both save and load)
latest changes!:
i fixed the progress bar but loadwithasync class is not working, i mean this line:
I think this must return the Srting ld and set that in text view res. but it is not looking this way! why travis from mybringback! didn't wrote the line like Strig s = new loadWith..... ? can u tell me where is the problem! i'm confused and i don't know how to debug properly!!
new loadWithAsyncTask().execute(FILENAME);
public class SaveAndLoadInternal extends Activity implements OnClickListener {
EditText file, data;
TextView res;
FileInputStream fis;
FileOutputStream fos;
String FILE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save_load_internal);
Button load, save;
file = (EditText) findViewById(R.id.etSLIfile);
data = (EditText) findViewById(R.id.etSLIdata);
res = (TextView) findViewById(R.id.tvSLIres);
load = (Button) findViewById(R.id.bSLIload);
save = (Button) findViewById(R.id.bSLIsave);
// set file and close it!
load.setOnClickListener(this);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
FILE_NAME = file.getText().toString();
switch (v.getId()) {
case R.id.bSLIload:
//Commented just for doing some tweaks! run
//loading process in another thread to give UI thread rest :D for avoid hanging!
FileInputStream fis = null;
String ld = "LOADING FAILED!";
/* try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
while (fis.read(b) != -1) {
ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
res.setText(ld);
*/
new loadWithAsyncTask ().execute(FILE_NAME);
// execute will run doInBackground method!
break;
case R.id.bSLIsave:
String sd = data.getText().toString();
/*
// one way to save in file is below! must work but it isn't!
File f = new File(FILE_NAME);
try {
fos = new FileOutputStream(FILE_NAME);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
// /*
// first param: what is being passed in (FILE_NAME)
// second param for progress bar (we use integer here)
// third one is what we will return! (the saved text! String ld)
public class loadWithAsyncTask extends AsyncTask<String, Integer, String>{
ProgressDialog pd;
String Ld = "LOADING FAILED!";
FileInputStream fis = null;
// this gonna called first
#Override
protected void onPreExecute(){
// example: setting up variables or something else!
pd = new ProgressDialog(SaveAndLoadInternal.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(100);
pd.show();
}
#Override
protected String doInBackground(String... params) {
//for progress dialog
for(int i =0 ; i< 20 ; i++){
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pd.dismiss();
try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
res.setText(String.valueOf(fis.available()));
while (fis.read(b) != -1) {
Ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
//return the string!
return Ld;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// progress of loading in example!
#Override
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}
}// */
}
When you look at the error, you'll see that onProgressUpdate() throws a NPE. Looking at the code, there are two possibilities: 1. pd is null or 2. progress is null. Add a breakpoint or some logging there to see what exactly is going on.
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}

Android Thread / AsyncTask, ExceptionInInitializerError and RuntimeException on "runOnUiThread"

I need your help with two Errors I´m getting on
Creating a Thread, where I`m creating a file
After the file stuff, a AsyncTask getting executed to send the file to a server (multipart/form-data)
Thats how the first part looks like:
public void startResultTransfer(final int timestamp, final int duration, final String correction, final float textSize, final int age, final int switch_count, final Activity activity){
synchronized(DataTransmission.class){
new Thread() {
public void run() {
FileWriter fw = null;
//1.Check if file exists
File file = new File(FILE_PATH);
if(!file.exists()){
//File does not exists, when we have to generate the head-line
try {
fw = new FileWriter(FILE_PATH);
fw.append("timestamp\tduration\tcorrection\ttext_size\tage\tswitch_count"); //Headline
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//2. Write Result
try {
if(fw == null)
fw = new FileWriter(FILE_PATH);
fw.append("\n"+String.valueOf(timestamp)+"\t");
fw.append(""+String.valueOf(duration)+"\t");
fw.append(""+correction+"\t");
fw.append(""+String.valueOf(textSize)+"\t");
fw.append(""+String.valueOf(age)+"\t");
fw.append(""+String.valueOf(switch_count)+"\t");
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//3. File Transfer
if(isOnline(activity))
transferFileToServer(activity);
}
}.start();
}
}
The function "transferFileToServer" looks like this:
public synchronized void transferFileToServer(Activity activity){
String id = id(activity);
File file = new File(FILE_PATH);
if(id != null && file.exists()){
final String url = URL+id;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
TransmissionTask task = new TransmissionTask();
task.execute(url);
}
});
}
}
Now, I`m getting an "ExceptionInInitializerError" with the explanatory message
Caused by java.lang.RuntimeException Can't create handler inside thread that has not called Looper.prepare()"
at the line "activity.runOnUiThread".
In the first function I need to call "transferFileToServer" after some pre settings. But the function should be called unattached from the first function, too.
Should I maybe implement a MessageHandler for executing the AsyncTask at the end of Thread?
http://developer.android.com/reference/android/os/Looper.html
Or should I maybe Change the "AsyncTask" in the "transferFileToServer" function to a Thread, because I don`t do any UI operations?
Edit: The method started from the Async-Task
class TransmissionTask extends AsyncTask<String, Void, String> {
public TransmissionTask() {
}
#Override
protected String doInBackground(String... params) {
synchronized(DataTransmission.class){
try {
HttpURLConnection urlConn;
java.net.URL mUrl = new java.net.URL(params[0]);
urlConn = (HttpURLConnection) mUrl.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
String boundary = "---------------------------14737809831466499882746641449";
String contentType = "multipart/form-data; boundary="+boundary;
urlConn.addRequestProperty("Content-Type", contentType);
DataOutputStream request = new DataOutputStream(urlConn.getOutputStream());
request.writeBytes("\r\n--"+boundary+"\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\""+FILE_NAME+"\"\r\n");
request.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
File myFile = new File(FILE_PATH);
int size = (int) myFile.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(myFile));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.write(bytes);
request.writeBytes("\r\n--"+boundary+"--\r\n");
request.flush();
request.close();
InputStream responseStream = new BufferedInputStream(urlConn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
{
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
responseStream.close();
urlConn.disconnect();
return response;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
if(result.toLowerCase().contains("erfolgreich")){
//If successfull delete File
File file = new File(FILE_PATH);
file.delete();
}
}
}
}
Remove runOnUiThread:
public synchronized void transferFileToServer(Activity activity){
String id = id(activity);
File file = new File(FILE_PATH);
if(id != null && file.exists()){
final String url = URL+id;
TransmissionTask task = new TransmissionTask();
task.execute(url);
}
}
The main idea of AsyncTask to run background operation/logic without Threads or Handlers.
You don't need wrap AsyncTask with additional Thread and bind with UI Thread what you did
From your code:
public void startResultTransfer(/* ... */){
....
new Thread() {
.....
transferFileToServer(/* ... */); // its wrong!!!
....
}.start()
}
transferFileToServer starts your AsyncTask and you run it not in main UI Thread but in single Thread.
This is a problem.
Start your AsyncTask from Activity.

android - LAN socket programming -- getting nullpointer and address-in use exception

i've done an application in which the android application send datas to java desktop swing application as well as send datas from desktop to android using TCP socket programming through wifi.
Th application is a Hotel Kitchen order booking system
The problem describes that Dine_Tables class contains buttons which represents each tables in a hotel, on clicking table1 button for example it starts the BackgroundServers Asyntask which runs a server for receiving desktop application datas also it takes the activity from Dinein_Tables.java to Food_Customizer.java.
In Food_Customizer.java on clicking submit button it starts ServersendAsyncAction Asyntask which sends some datas to desktop swing application.
The desktop application after processing sends some datas to android application, The server that runs in the android application on receiving the datas goes again from Food_Customizer.java to Dinein_Tables.java activity in the BackgroundServers Asyntask onPostExecute method.
The problem is that when i do this process a two or three times the application stop due to address-in use and Null-Pointer exception at socket = serverSocket.accept(); in the BackgroundServers Asyntask.
Can anyone please tell me some solution for this problem
Dinein_Tables.java
public class Dinein_Tables extends Activity {
:
:
table1.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
Food_Customizer.BackgroundServers ob = new Food_Customizer().new BackgroundServers(contexts);
ob.execute("");
Intent toAnotherActivity = new Intent(v.getContext(), Food_Customizer.class);
startActivity(toAnotherActivity);
finish();
}
}, 100L);
}
});
}
Food_Customizer.java
public class Food_Customizer extends Activity {
:
:
submit= (Button)findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd = ProgressDialog.show(contexts, "Sending to Server...","Please Wait...", true, false);
new ServersendAsyncAction().execute();
}
});
:
:
/****************************** AsyncTask ********************************************************/
private class ServersendAsyncAction extends AsyncTask<String, Void, String> {
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
boolean flag = true;
while (flag) /******** If data is send flag turn to be false *******/
{
try {
socket = new Socket("192.168.1.74", 4444);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(datastosend);
flag = false;
} catch (UnknownHostException e) {
flag = true;
e.printStackTrace();
} catch (IOException e) {
flag = true;
e.printStackTrace();
}
/******** CLOSING SOCKET *****************/
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAOUTPUTSTREAM *******/
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAINPUTSTREAM ********/
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
protected void onPostExecute(String result) {
}
/********************* ENDING OF ASYN TASK CLASS ServersendAsyncAction ***************************/
}
public Context con;
public static ServerSocket serverSocket = null;
public class BackgroundServers extends AsyncTask<String, Void, String> {
public BackgroundServers(Context context) {
con=context;
}
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(9999);
System.out.println("Listening :9999");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
String incoming_message=(dataInputStream.readUTF());
incoming_message=incoming_message.replace("/", "");
String recdatas[]=incoming_message.split("#");
if(recdatas[0].equalsIgnoreCase("success"))
{
DatabaseConnection dbs=new DatabaseConnection(con);
int status=dbs.update("UPDATE hotel_pub_tables SET status='occupied' WHERE tableno='"+recdatas[1]+"'");
if(status>0)
{
tabelstatus=1;
//msg.obj="Table status changed!!!";
System.out.println("Table status changed!!!");
if (true) {
System.out.println("entered 222");
System.out.println(tabelstatus);
if(tabelstatus==1)
{
System.out.println(tabelstatus);
Food_Customizer.pd.dismiss();
System.out.println("success");
}
else if(tabelstatus==2)
{
Food_Customizer.pd.dismiss();
Intent intent = new Intent(Food_Customizer.this, Dinein_Tables.class);
startActivity(intent);
finish();
}
}
}
else
tabelstatus=2;
dbs.close();
}
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
#Override
protected void onPostExecute(String result) {
System.out.println("eneterd on posttttttttttttttt");
con.startActivity(new Intent(con, Dinein_Tables.class));
finish();
}
}
}
/********************* ENDING OF ASYN TASK CLASS BackgroundServers ***************************/
}
Well it's obvious that you setup your server on port 9999:
serverSocket = new ServerSocket(9999);
But you connect with the server on port 4444:
socket = new Socket("192.168.1.74", 4444);
Make sure you connect to the correct port-number otherwise it wont work. Hope this helps.

Categories

Resources