Question

Je vérifie si une chaîne est NULL dans un thread, si son null, le démarrage du gestionnaire un Runnable qui commence une nouvelle activité.

Tout fonctionne très bien, mais, après la nouvelle activité est affichée, il revient à l'appelant et l'activité, il se bloque.

Voici un extrait de code.

if(username==null)
{
    dialogs.dismiss();
    handlers.post(new MyRunable());
}

et est Runnable

public class MyRunable implements Runnable
{
    public void run(){

    Toast.makeText(ListActivity.this, "Your Connection is too slow",Toast.LENGTH_LONG).show();

    startActivity(new Intent(ListActivity.this,Anim.class));

    }
}

Voici ma source complète

    package com.cram;

    import java.io.File;
    import java.io.IOException;

    import javax.xml.parsers.ParserConfigurationException;

    import org.xml.sax.SAXException;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnClickListener;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Typeface;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.os.Handler;
    import android.util.Log;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    public class BuddyListActivity extends Activity
    {

        String ss;
        private static ProgressDialog dialogs,dialog;
        private Thread downloadThreads;
        boolean results=false;
        Context ctx;
        String[]ddd;
        ListView lv1;
        String [] icons;
        BuddyDbAdapter adapter;
        NetworkInfo netinfo;
        Cursor cursor;
        String values;
        GetBuddy gb;
        BuddyDB db;
        String[] username;
        String[] firstname;
        String[] lastname;
        String[] avatar;
        String[] id;
        File[] iconss;
        Handler handlers;
        boolean ready=false;


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.buddy);
            db=new BuddyDB(BuddyListActivity.this);
            Typeface font = Typeface.createFromAsset(getAssets(),"fonts/Fortheloveofhate.ttf");
    TextView btxt = (TextView) findViewById(R.id.textbuddy);
    btxt.setTypeface(font);
    ctx=getApplicationContext();    
    lv1=(ListView)findViewById(R.id.list22);
    netinfo=null;
    adapter=new BuddyDbAdapter(BuddyListActivity.this);
    netinfo=checkDataConnection(getApplicationContext());
    handlers = new Handler();
    adapter.open();

    if(netinfo!=null)
    {   
        downloadThreads = (Thread) getLastNonConfigurationInstance();
        if (downloadThreads != null && downloadThreads.isAlive()) {
        dialog = ProgressDialog.show(this, "Download", "downloading");
        }

        startdownload();

    }




    if(netinfo==null)
    { 

        cursor=adapter.showBuddy();         
        if (cursor==null||cursor.moveToFirst()==false) 
        {
             AlertDialog.Builder buddybox = new AlertDialog.Builder(this);
                buddybox.setMessage("You have No Buddies Yet douche!!");
    buddybox.setNeutralButton("Okay", new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        startActivity(new Intent(getBaseContext(),Anim.class));
                    }
                });
                buddybox.setCancelable(false);
             buddybox.show();
    }
        else
            {
            cursor.moveToFirst();   
            int j=0;
            ddd=new String[cursor.getCount()];
            icons=new String [cursor.getCount()];
                do
                {
            String firstName = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_FISTNAME));
            String lastname  = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_LASTNAME));
            String Avatar    = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.AVATAR));
            ddd[j]=firstName+" "+lastname;
    Log.d("Test", ddd[j]);
    icons[j]=Avatar;
    Log.d("Test", icons[j]);
    j++;
        }while(cursor.moveToNext());


        iconss= new File[icons.length];
        Log.d("Test",icons.length+"");
    for (int q = 0; q < icons.length; q++) {
        iconss[q] = new File(Download.ROOT +"/"+ icons[q]+".jpg");
    Log.d("Test", iconss[q].getAbsolutePath().toString());
    }
    //adapter.close();
                    lv1.setAdapter(new BuddyAdapter(BuddyListActivity.this,R.layout.list1,ddd,iconss));
                    onDestroy();
                }



            }
        }

    private void box() {
        // TODO Auto-generated method stub

    cursor=adapter.showBuddy(); 
    if (cursor==null||cursor.moveToFirst()==false) 
    {
        dialogs.dismiss();
         AlertDialog.Builder buddybox = new AlertDialog.Builder(this);
            buddybox.setMessage("You have No Buddies Yet ass!!");
    buddybox.setNeutralButton("Okay", new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            startActivity(new Intent(getBaseContext(),Anim.class));
                        }
                    });
                    buddybox.setCancelable(false);
                 buddybox.show();

        }

        }

        private NetworkInfo checkDataConnection(Context applicationContext) {
        final ConnectivityManager connMgr = (ConnectivityManager)BuddyListActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkinfo=null;
        final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if(wifi.isConnected()||mobile.isConnected())
        {networkinfo=connMgr.getActiveNetworkInfo();
         return networkinfo;
        }

        else
        {
            return null;
        }

    }
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (adapter != null) {
                adapter.close();
            }

        }

        @Override
        protected void onStop()
        {
            super.onStop();
            finish();

        }
        private void startdownload() {
            dialogs = ProgressDialog.show(BuddyListActivity.this, "Contacting Our Servers", "Geting Your Buddies Avatar");
        downloadThreads = new MyThread();
        downloadThreads.start();

    }

    public class MyThread extends Thread {

        @Override
        public void run() {
            try {

                new Thread();
                GetBuddy tt=new GetBuddy();
                String xml=tt.get();
                if(xml==null)
                {   dialogs.dismiss();
                    handlers.post(new MyRunable());
                    ready=false;
                    //downloadThreads.suspend();

    }
    final Download cd = new Download();
    results = cd.downloadBitmap();
    if(results)
    {
    BuddyParse bp=new BuddyParse();

    try {

        username=bp.show(xml);
    //                  if(username==null)
    //                  {   dialogs.dismiss();
    //                      handlers.post(new MyRunable());
    //                      //downloadThreads.suspend();
    //                  }
        firstname=bp.firstname();
        lastname=bp.lastname();
        avatar=bp.avatar();
        id=bp.id();
        adapter.deleteAll();
        ready=true;
    } 
    catch (ParserConfigurationException e) 
    {
        e.printStackTrace();
    }
    catch (SAXException e) 
    {
        e.printStackTrace();
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    //  Log.d("len", username.length+"");

    for(int k=0; k<username.length;k++)
    { 
    adapter.insertBuddy(id[k], username[k], firstname[k], lastname[k], avatar[k]);
    Log.d("Test", id[k]+username[k]+firstname[k]+lastname[k]+avatar[k]+"");
    }
    box();
    cursor=adapter.showBuddy();
    cursor.moveToFirst();
    int i=0;
    ddd=new String[cursor.getCount()];
    icons=new String [cursor.getCount()];
        do
        {
    String firstName = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_FISTNAME));
    String lastname  = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_LASTNAME));
    String Avatar    = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.AVATAR));
    ddd[i]=firstName+" "+lastname;
    Log.d("Test", ddd[i]);
    icons[i]=Avatar;
    Log.d("Test",icons[i]);
    i++;
        }while(cursor.moveToNext());


     iconss= new File[avatar.length];
    for (int k = 0; k < avatar.length; k++) {
        iconss[k] = new File(Download.ROOT+"/"+avatar[k]+".jpg");

    Log.d("Test", iconss[k].getAbsolutePath()+"thread");
    //Log.d("Test", ddd[k]);
            }

        if (results&&ready)
            {
            dialogs.dismiss();
            handlers.post(new MyRuns());

            }
    } 
    //              else
    //              {   dialogs.dismiss();
    //                  handlers.post(new MyRunable());
    //                  
    //              }
            }finally {

            }

        }


    }

    public class MyRuns implements Runnable {
        public void run() {
            ready=true;
            lv1.setAdapter(new BuddyAdapter(ctx,R.layout.list1,ddd,iconss));
            onDestroy();
        }
    }
    public class MyRunable implements Runnable {
        public void run() {
            //Toast.makeText(BuddyListActivity.this, "Your Connection is too slow", Toast.LENGTH_LONG).show();
                startActivity(new Intent(BuddyListActivity.this,Anim.class));


            }
        }
    }
Était-ce utile?

La solution 2

Réglage RETURN dans le bloc try catch et la mise en android:noHistory="true" dans Android Manifest pour toutes les activités fixe mon problème

Autres conseils

utilisez thread principal pour commencer votre chèque de fil runOnUiThread (Action Runnable)

Si vous essayez de créer une tâche async dans un autre thread, je vous recommande d'utiliser la classe suivante:

private final class MyRunnable extends
            AsyncTask<Void, Void, Document> {
        protected Document doInBackground(Void... params) {

        }

        protected void onPostExecute(Document result) {

        }
    }

Il vous suffit de modifier les paramètres.

Plus d'infos ici: http://developer.android.com/reference/android/os/AsyncTask.html

Terminez votre activité actuelle lors du démarrage une autre activité de runnable.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top