1

Helly Community. I´m fairly new to Android and probably the biggest noob when it comes to networking and backend. Right now I´m having following problem.

I´m building a simple chatting application and want my app to check the Parse server for a specific message parseobject.

Getting the Objects, working with them and deleting them works fine. If i do it only once.

This is how I get messages from the Cloud and add them to my App Layout.

ParseQuery<ParseObject> query = ParseQuery.getQuery("message");
            query.whereEqualTo("recipient", getRemote_id());

            query.findInBackground(new FindCallback<ParseObject>() {
              public void done(List<ParseObject> messages, ParseException e) {
                 if(messages != null){
                     Iterator itr = messages.iterator();
                      while(itr.hasNext()){
                          ParseObject message = (ParseObject)itr.next();

                         addMessageToLayout(message.getString("text"), "in", "new", "");  
                         try {
                            message.delete();
                        } catch (ParseException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                      } 
                 }

              }
            }); 

I want my app to check for new messages the whole time. Ive tried with AsyncTask and a while(true) loop. The loop constantly creates new asynctask objects. As result the app doesn´t react anymore and crashes.

When I use an instance of the runnable class im getting following error: NetworkOnMainThreadException, and the App crashes.

Because of this error i tried using asynctask in the first place. Isn´t a runnably object running on a different thread than the main thread as well?

I tried putting the thread to sleep for some seconds, still the app crashes in case of the async task.

Could the Problem be following: Im using anoher runnable object to update some animation in my app.

I also tried not using any kind of threading as the parse methods already work in background so they probably dont even need one. Again the app crashes because of an NetworkOnMainThreadException.

///_////

The weirdest thing comes now. If i´m not using a loop, and just check for messages when i enter the activity at first i´m getting an NetworkOnMainThreadException, but then the application somehow recovers into the newly opened activity and loads my messages from the server.

During that time of course the UI is blocked though. Still, thats the only way i can get it to work right now.

Doing it with a Handler and the TimerTask works, I can´t seem to close the thread when i exit the Activity though.

Here my code:

public void startLookingForMessages(){

        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {       
             @Override
             public void run() {

               handler.post(new Runnable() {
                  public void run() {  
                     new GetMessagesTask().execute();

                  }
                });
              }
        };
        timer.schedule(task, 0, 1000);

    }

I found out that im getting the NetworkOnMainThreadException only if i´m trying to shut down the thread or close the while loop when calling onStop(). If I let the thread do its own thing, that means not putting in any code to stop it any time, my app works fine. How could i overcome this problem?

I know this is getting kinda long. But maybe someone has the same Problem and can get some Info here.

Thanks you for your help already =)

sakramento
  • 369
  • 5
  • 16
  • solved my problem looking at this question http://stackoverflow.com/questions/17032024/how-to-call-asynctasks-periodically?rq=1 – sakramento May 18 '14 at 22:30
  • 1
    If you no longer need help, delete this question. – Stephen C May 18 '14 at 22:41
  • Edit: It still doesn´t work like i intended. I Found out that im getting the NetworkOnMainThreadException only if anything in the Activity is trying to shut down the thread that checks for messages. For example my while(running) loop. Which i closed by setting running to false in onStop(). – sakramento May 18 '14 at 22:55

1 Answers1

1

Don't do it this way. Just don't.

Think about it: you're calling an AsyncTask to check periodically if something is there. Now, that gets to be quite expensive. Think about the battery and network resources you waste if that message is not there. Therefore, you waste a lot of resources. It's not a good idea to do it like this. You waste the user's resources. In addition, you also need a service to run in the background, as your app will not always be running.

A good way to solve this is to use Google Cloud Messaging. So what Google Cloud Messaging does is it "pings" a device every time there's an update. This makes life easier on you, as you only need to check if your app has received one of these pings, and it also saves battery and network resources.

If you're using PHP for your server-side application, you can use this to get started with GCM and PHP: GCM with PHP (Google Cloud Messaging)

This page on Google's website should also help with implementing it.

By using GCM, you'll also avoid having infinite loops or checking for more information every x minutes. You don't have to check yourself if new information is available; it'll ping you when it's available.

Community
  • 1
  • 1
hichris123
  • 10,145
  • 15
  • 56
  • 70