How To Create Asynctask To Prevent Networkonmainthreadexception
I'm new to android application development. I tried to develop an android server client chat for my first project. This is the code for the client side. When the client press btnJ
Solution 1:
Change your code as:
btnJoin.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View view){
newLongOperation().execute("");
}
}
privateclassLongOperationextendsAsyncTask<String, Void, String> {
Socket socket = null;
String strresult="";
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
@OverrideprotectedStringdoInBackground(String... params) {
try {
socket = newSocket("192.168.1.4", 9092);
dataOutputStream = newDataOutputStream(socket.getOutputStream());
dataInputStream = newDataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
strresult.append(dataInputStream.readUTF() + "\n");
// txtIP.append(dataInputStream.readUTF() + "\n");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strresult;
}
@OverrideprotectedvoidonPostExecute(String result) {
TextView txtIP= (TextView) findViewById(R.id.txtIP);
// txtIP.append(result + "\n");
txtIP.setText(result + "\n");
}
@OverrideprotectedvoidonPreExecute() {
}
}
Solution 2:
Use AsyncTask like this :
First have it nested in your class, it should look similar to :
privateclassCommunicatorextendsAsyncTask<Void, Void, Boolean> {
String tmp;
String err;
@OverrideprotectedBooleandoInBackground() {
try {
socket = newSocket("192.168.1.4", 9092);
dataOutputStream = newDataOutputStream(socket.getOutputStream());
dataInputStream = newDataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
returntrue;
}
@OverrideprotectedvoidonPreExecute() {
}
@OverrideprotectedvoidonPostExecute(Boolean result) {
txtIP.append(dataInputStream.readUTF() + "\n");
}
}
When you have AsyncTask,you can start it like this :
...
@OverridepublicvoidonClick(View v) {
Communicator c=newCommunicator();
c.execute();
}
....
Solution 3:
try to implement this code in your app
privateclassLongOperationextendsAsyncTask<Object, Integer, Object> {
@OverrideprotectedvoidonPreExecute() {
super.onPreExecute();
}
@OverrideprotectedObjectdoInBackground(Object... params) {
//do hard work herereturn params;
}
@OverrideprotectedvoidonProgressUpdate(Integer... values) {
}
@OverrideprotectedvoidonPostExecute(Object result) {
super.onPostExecute(result);
}
}
Solution 4:
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
privateclassDownloadFilesTaskextendsAsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is calledif (isCancelled()) break;
}
return totalSize;
}
protectedvoidonProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protectedvoidonPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
for more details refer below links...
http://www.vogella.com/articles/AndroidPerformance/article.html
http://developer.android.com/reference/android/os/AsyncTask.html
Post a Comment for "How To Create Asynctask To Prevent Networkonmainthreadexception"