Sockets in android and listview - android

I have an Android application that includes a Socket in an Asynctask and it works, but I do not know if this is the right way to implement it.
Another thing, my onProgressUpdate updates my list adapter and causes lag when I play animation with it.
Someone have a good solution for that?

Are you sure you are not during any computation on the UI thread?
Check out this page, there are some guidelines on how to use the various thread mechanisms in Android.
If this does not solve your problem, try posting the part of your code that handles the population of the list.

I did it like this ... (just for the Socket connection)
private class EstablishConnectionTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
boolean ok = false;
dataSend = false;
//establish the Connection to the server and returns if it succeed or not
ok = client.createClient(server, port);
//try to send the data and return if it succeed or not
if(ok) dataSend = client.sendData(profilename);
if(dataSend) {
//close the connection
client.closeConnection();
}
return null;
}
protected void onPreExecute() {
//bring a process Dialog to the front
showDialog(DIALOG_CONNECTING);
}
protected void onPostExecute(Void result) {
removeDialog(DIALOG_CONNECTING);
if(dataSend) {
Toast.makeText(Activity_sendXML.this, "xml versendet", 2000).show();
}
else{
showDialog(DIALOG_CONNECTION_REFUSED);
}
}
}

Related

AsyncTask Workflow

I am currently working on an android application that has to handle a network connection using several AsyncTasks.
This is the first task that is establishing the connection and calling a new task which is handling the microphone input.
private class establishConnectionTask extends
AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
// initialize connection
initConnection();
MicrophoneTask micTask = new MicrophoneTask();
micTask.execute("");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
mReadInputTask = new readInputTask();
mReadInputTask.execute("");
super.onPostExecute(result);
}
Everything works fine, the connection is working and I can transfer data. Also the MicrophoneTask is doing it's job.
Here comes the problem:
In the onPostExecute method I am creating a new AsyncTask which should handle all the network input.
This is how the readInputTask looks like:
private class readInputTask extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute()
{
Log.d("DEBUG", "pre");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// blocking readInput method
Log.d("DEBUG", "doInBackground");
}
#Override
protected void onPostExecute(String result) {
Log.d("DEBUG", "post");
super.onPostExecute(result);
}
}
The readInputTask somehow gets stuck in the onPreExecute method of the readInputTask. The only output I get is "pre", eventhough I also expect "doInBackground" and "post".
Does anyone see an error or knows a solution for this?
Any help is appreciated!
mReadInputTask.execute("");
When you use AsyncTask#execute(params), the AsyncTasks are executed serially: one after the other. To execute AsyncTasks in parallel, use AsyncTask#executeOnExecutor(...).
From the docs on executeOnExecutor (Executor exec, Params... params):
This method is typically used with THREAD_POOL_EXECUTOR to allow
multiple tasks to run in parallel on a pool of threads managed by
AsyncTask, however you can also use your own Executor for custom
behavior.

Source not found on AsyncTask.execute()

I am trying to get along with AsyncTask..
what my problem was that i was building a table of textviews dynamically, based on the output of a procedure.. But then i figured that by using asynctask i can do it in a more efficient way..So, what i did is as follows:
private class DisplayReport extends AsyncTask<Void, Void, Boolean>{
protected void onPreExecute(){
//Message -- "Please wait while the Report Loads..."
}
#Override
protected Boolean doInBackground(Void... params) {
//Here i fetch the data from the procedure via a web service
//parse the result of web service and set a bool variable true or false based on whether the dataset fetched is empty or not.
}
protected void onPostExecute(Boolean value){
if(value == true){
"Please try again later!!"
}
else{
runOnUiThread(GenTable);
}
}
private Runnable GenTable = new Runnable(){
public void run(){
try {
displayReport(result); // in this method i build the table.
} catch (Exception e) {
ad.setTitle("Error..");
ad.setMessage(e.toString());
}
}
};
}
the above async class is an inner class in my main class which extends activity.
and this is how i am executing the asynctask..
DisplayReport dr = new DisplayReport();
dr.execute();
now when i debug, i get the "source not found" error on dr.execute()..
i tried searching a lot on the net, but i simply cannot find out anything concrete. Also, please let me know if my approach is incorrect..
this question might seem very silly, but i am new to android and java as well and any help would be really great..
Thanks!
Execute is going to start a new thread. You don't want to debug into it. Instead, put breakpoints in onPreExecute, doInBackground, and onPostExecute and you can see when each of those gets called.
onPostExecute is already being run in the UI thread, so you should not create another runnable for it. Just make your onPostExecute like this:
protected void onPostExecute(Boolean value){
if(value == true){
String message = "Please try again later!!";
// Do something here with your message
}
else{
displayReport(result);
}
}

Loading a layout using ASyncTask in Android

I have an application that loads a dialog with some images specified in the dialog's XML layout. I've read a lot about using images in Android and being careful with the VM budget so I believe that any handling of images with the potential to take up a decent amount of memory should be handled off of the main thread. With that said I was wondering if it is wise to load an entire layout off of the UI thread using an ASyncTask. I have a working code but I couldn't find out if this was good practice through some Google searches. Here is the code below.
This is the case statement that triggers when the user presses a button to load the dialog.
case R.id.showDialog:
vibrator.vibrate(vibrateMilis);
mDialog = new Dialog(getActivity(), R.style.CustomDialog);
new LoadLayout().execute("");
break;
And here is the ASyncTask
private class LoadLayout extends AsyncTask<String, Void, String>
{
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params)
{
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_layout);
mDialog.setCancelable(true);
return null;
}
#Override
protected void onPostExecute(String result)
{
progressDialog.cancel();
mDialog.show();
}
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(
getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values)
{
// Do nothing
}
}
So this code works but the question I have is this. Is this considered good practice? It seems a bit hacky for my taste. I didn't come across this with multiple Google searches so that's why I'm a bit concerned. I mean if it was good practice it would've been documented somewhere right?
Thanks for any input.
Have you refer the android developer site. your approach is wrong. For more guidance please refer Vogella Documentation. Its a nice explaination of AsyncTask.
Also refer below example code for the AsyncTask.
// The definition of our task class
private class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
displayProgressBar("Downloading...");
}
#Override
protected String doInBackground(String... params) {
String url=params[0];
// Dummy code
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return "All Done!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
updateProgressBar(values[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dismissProgressBar();
}
}
Hope it will help you a lot.
Enjoy Coding... :)
I think you are doing it in a wrong way , because :
First,when call method doInBackground() , It will in other thread , you can only change UI elements in main thread .
Second,show a dialog is not waste time,you can call it in onPreExecute() or onPostExecute(String result),and just do actions in doInBackground() that make user wait ,like get data from network or database.
You can not load whole Layout in background thread(pls note AsyncTask.postExecute() is executed on main thread). Because all the UI components should be modified from only Main Thread(also called UI thread). You can use the background thread just to gather the information that is needed for displaying UI.

How to work with AsyncTask and threads?

The goal:
Using Google App Engine server and Android client, I'm trying to put on the Google map at the Android client Users overlays. Every 30 seconds I'm polling the server and getting Vector that contains users and adding it to the map.
Current status:
I'm dong all that using in one new thread, So after running the app I got:
weird behaviors(delayed overlays, multiple overlays) and after that crushed with ConcurrentModificationException.
After reading a bit i figured out that I need to work with AsyncTask.
Correct me if I'm wrong,But I understand that everything done in the Activity at at onCreate is "running" in UIhread so I need to put the "Logic" (All the Network handling) in doInBackground and all the UI Handling like putting overlays on the map in onPostExecute.
My Question are:
1) In the current status I'm doing:
new Thread()
{
#Override
public void run()
{
super.run();
while(true)
{
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
putNewOnlineUserOnTheMap();
}
}
}.start();
What is the right way to convert this To AsyncTask?
Do I poll the server still using new thread in the doInBackground or there is right way to do this?
2) Is there a specific list of what counts as UI to put in onPostExecute or any concepts list?
In my case I guess that in need to put putNewOnlineUserOnTheMap() in onPostExecute.
Thanks.
Something similar to the following:
class UpdateTask extends AsyncTask<Void, Vector, Void>{
#Override
protected Void doInBackground(Void... params) {
// this is running in a background thread.
while (!isCancelled()) {
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
// send the result back to the UI thread
// onProgressUpdate will be called then
publishProgress(responseFromServer);
}
return null;
}
#Override
protected void onProgressUpdate(Vector... values) {
// this is executed on the UI thread where we can safely touch UI stuff
putNewOnlineUserOnTheMap(values[0]);
}
}
You can't use the result of the task since the task is finished then. But you can use the progress publishing mechanism to get periodic results. If you use it like that and do the modification on the UI thread you should not get ConcurrentModificationException because you do the modifications on the one thread that can safely modify the UI.
One thing to note here: create new instances of your Vector in the background thread and then use it to update the UI. But don't touch the same object afterwards in the backgroundthread. That way you don't need any synchronization since after the background thread sends it away it is only the UI thread that touches it. (and you could use a simple ArrayList instead of a Vector)
AsyncTask uses generics and varargs.The parameters that are passed to the asyntask are . TypeOfVariableArgumentsParameters is passed into the doInBackground(), ProgressParam is used for progress information and ResultParam must be returned from doInBackground() and is passed to onPostExecute() as parameter.
example:--
protected class ParsingTask extends AsyncTask> {
private ProgressDialog loadingDialog = new ProgressDialog(JsonParserActivity.this);
protected void onPreExecute() {
loadingDialog.setMessage("loading app store..");
loadingDialog.show();
}
#Override
protected ArrayList<Items> doInBackground( Context... params ) {
// do ur process here.
return result;
}
if (!this.isCancelled()) {
}
return result;
}
#Override
protected void onProgressUpdate(String... s) {
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( ArrayList<Items> response ) {
//if u r dealing with list view and adapters set the adapter here at the onPostExecute()
loadingDialog.dismiss();
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled", 1).show();
}
}
You can use AsyncTask like below. Hope this will help you..
Class YourClass{
void YourClass(){
NetworkTask nT = new NetworkTasK();
nT.execute();
}
}
protected class NetworkTask extends AsyncTask<Void, String, Boolean>
{
#Override
protected Boolean doInBackground(Void... params)
{
try
{
String response;
while(keepreceiving)
{
response = in.readLine();//Prog Counter stops here until getting i/p.
if(response != null)
yourFunctionForResponse(response);
}
}
catch (Exception ex)
{
}
return null;
}
private void yourFunctionForResponse(String response){
//things to do....
}
}
You may also try runOnUiThread(Runnable action) along with this to implement your work.

How to run queries in the background

I have listed of products with different category. I have to sort them. Because of the queries, It is taking more time to load. Between two activities, the screen is coming black. I want to run the query in the background. How can I do that and how to use its result in main activity?
private class InsertTask extends AsyncTask {
String cat;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
Boolean success = false;
try {
category(cat);
success = true;
} catch (Exception e) {
if(e.getMessage()!=null)
e.printStackTrace();
}
return success;
}
#Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
}
private void category(String category) {
try{
Cursor1 = mDbHelper.fetchcategory(category);
}catch(Exception e){
Log.v("Excep", ""+e);
}
}
And when called
InsertTask task = new InsertTask();
task.execute();
I have listed the category in buttons. How can I get the values then?
You should use AsyncTask for that. And some more info.
Its good you have thought of AsyncTask. Firstly, you can declare this class as inner in you class activity (if you haven't previously did) and so you are able to access you view class members.
You can do this also by creating thread and one handler that will be used to update your UI components. Remember that if you use threads you'll need to lock/unlock your database object because of the thread safety(if any other thread is accessing the database for any reason). Read more about thread safety of dbs.
I was doing some searching myself, and I came across this read, its rather long but looks extremely helpful, with lots of code examples. (I bookmarked it for myself).
Threads, Async, and Handlers O MY!
But some form of threading is the ticket.
From Android dev.
(My favorite code snippet)
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
//Do Work here
}
}).start();
}

Categories

Resources