Android 减少许多活动中的大量代码

Android 减少许多活动中的大量代码,android,format,reduce,Android,Format,Reduce,我需要帮助来减少这该死的代码。我知道这是地狱。对不起,我的英语不好 问题: 我读过关于parcelable的书,不知道如何使用tough(因为我的对象中有一个arraylist) 我可以创建一个通用类型的onclicklisteners吗(在本例中) 我尝试过assynctask,但是主ui被阻止,我得到了一个黑屏 最后更改方向3次会导致对话框出现异常 任何答案都会有很大帮助 public class AndroidfeedtsxActivity extends Activity impleme

我需要帮助来减少这该死的代码。我知道这是地狱。对不起,我的英语不好 问题:

  • 我读过关于parcelable的书,不知道如何使用tough(因为我的对象中有一个arraylist)
  • 我可以创建一个通用类型的onclicklisteners吗(在本例中)
  • 我尝试过assynctask,但是主ui被阻止,我得到了一个黑屏 最后更改方向3次会导致对话框出现异常
  • 任何答案都会有很大帮助

    public class AndroidfeedtsxActivity extends Activity implements ViewFactory {
     private int evento = 0;
     private boolean isfavorite = false;
     private Handler handler = new Handler();
     private ProgressDialog dialog;
     private List<Noticia> exists;
    
     /** first method called */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
    
         noticias();
     }
    
     /*/
      * --------------------------------------------------------------------
      */
    
     /*
      * /starts the main screen, and the imagebuttons
      */
     private void telaPrincipal(final List<Noticia> naoFormatada) {
                   //close progress dialog
         dialog.dismiss();
         handler.post(new Runnable() {
    
             @Override
             public void run() {
    
                 //Formating my xml
                 final List<Noticia> lista = new Formatador()
                 .Formatar(naoFormatada);
    
    
    
    
                 if (!(lista.isEmpty() || lista== null)) {
                     exists = naoFormatada;
                     setContentView(R.layout.main);
    
                     evento++;
    
                     ImageButton ImgBtnEsportes = (ImageButton) findViewById(R.id.ImgBtnEsportes);
                     ImgBtnEsportes.setClickable(true);
    
                     ImageButton ImgBtnTodas = (ImageButton) findViewById(R.id.ImgBtnTodas);
                     ImgBtnTodas.setClickable(true);
    
                     ImageButton ImgBtnComunidade = (ImageButton) findViewById(R.id.ImgBtnComunidade);
                     ImgBtnComunidade.setClickable(true);
    
                     ImageButton ImgBtnPolicia = (ImageButton) findViewById(R.id.ImgBtnPolicia);
                     ImgBtnPolicia.setClickable(true);
    
                     ImageButton ImgBtnFavoritos = (ImageButton) findViewById(R.id.ImgBtnFavoritos);
    
                     // show all news
                     ImgBtnTodas.setOnClickListener(new OnClickListener() {
                         @Override
                         public void onClick(View arg0) {
                             isfavorite = false;
                             telaMensagens(lista);
    
                         }
                     });
    
                     // show sport news only
                     ImgBtnEsportes.setOnClickListener(new OnClickListener() {
                         @Override
                         public void onClick(View arg0) {
                             isfavorite = false;
                             telaMensagens(Categorizador(lista, "Esportes"));
                         }
                     });
    
                     // show police news only
                     ImgBtnPolicia.setOnClickListener(new OnClickListener() {
                         @Override
                         public void onClick(View arg0) {
                             isfavorite = false;
                             telaMensagens(Categorizador(lista, "Polícia"));
                         }
                     });
    
                     // shows comunity news only
                     ImgBtnComunidade.setOnClickListener(new OnClickListener() {
                         @Override
                         public void onClick(View arg0) {
                             isfavorite = false;
                             telaMensagens(Categorizador(lista, "Comunidade"));
                         }
                     });
    
                     // show the favorited news
                     ImgBtnFavoritos.setOnClickListener(new OnClickListener() {
                         @Override
                         public void onClick(View arg0) {
                             NoticiaDAO banco = new NoticiaDAO(getBaseContext());
                             try {
                                 List<Noticia> noticias = banco.getLista();
                                 banco.close();
                                 isfavorite = true;
    
                                 telaMensagens(noticias);
                             } catch (ParseException e) {
                                 Log.e("Erro ao tentar abrir Favoritos", " " + e);
                             }
                         }
                     });
                 } else {
                     Toast t;
                     t = Toast
                             .makeText(
                                     getBaseContext(),
                                     "Não foi possível obter as noticias no momento...\nTente novamente mais tarde.",
                                     Toast.LENGTH_LONG);
                     t.show();
                     setContentView(R.layout.main);
                     evento++;
                     ImageButton ImgBtnEsportes = (ImageButton) findViewById(R.id.ImgBtnEsportes);
                     ImgBtnEsportes.setClickable(false);
                     ImageButton ImgBtnTodas = (ImageButton) findViewById(R.id.ImgBtnTodas);
                     ImgBtnTodas.setClickable(false);
                     ImageButton ImgBtnComunidade = (ImageButton) findViewById(R.id.ImgBtnComunidade);
                     ImgBtnComunidade.setClickable(false);
                     ImageButton ImgBtnPolicia = (ImageButton) findViewById(R.id.ImgBtnPolicia);
                     ImageButton ImgBtnFavoritos = (ImageButton) findViewById(R.id.ImgBtnFavoritos);
                     ImgBtnPolicia.setClickable(false);
                     ImgBtnFavoritos.setOnClickListener(new OnClickListener() {
                         @Override
                         public void onClick(View arg0) {
                             NoticiaDAO banco = new NoticiaDAO(getBaseContext());
                             try {
                                 List<Noticia> noticias = banco.getLista();
                                 banco.close();
                                 isfavorite = true;
    
                                 telaMensagens(noticias);
                             } catch (ParseException e) {
                                 Log.e("Erro ao tentar abrir Favoritos", " " + e);
                             }
    
                         }
                     });
    
                 }
    
             }
         });
     }
    
    公共类AndroidFeedTSXAActivity扩展活动实现ViewFactory{
    私有int evento=0;
    私有布尔值isfavorite=false;
    私有处理程序=新处理程序();
    私人对话;
    存在私有列表;
    /**调用的第一个方法*/
    @凌驾
    创建时的公共void(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    通知();
    }
    /*/
    * --------------------------------------------------------------------
    */
    /*
    */启动主屏幕和图像按钮
    */
    私有void telaPrincipal(最终列表){
    //关闭进度对话框
    dialog.dismise();
    handler.post(新的Runnable(){
    @凌驾
    公开募捐{
    //格式化我的xml
    最终列表lista=新格式ADOR()
    .Formatar(naoFormatada);
    if(!(lista.isEmpty()| | lista==null)){
    存在=naoFormatada;
    setContentView(R.layout.main);
    evento++;
    ImageButton imgbtnesport=(ImageButton)findViewById(R.id.imgbtnesport);
    imgbtnesport.setClickable(true);
    ImageButton ImgBtnTodas=(ImageButton)findViewById(R.id.ImgBtnTodas);
    ImgBtnTodas.setClickable(true);
    ImageButton ImgBtnComunidade=(ImageButton)findViewById(R.id.ImgBtnComunidade);
    ImgBtnComunidade.setClickable(true);
    ImageButton ImgBtnPolicia=(ImageButton)findViewById(R.id.ImgBtnPolicia);
    imgbtna.setClickable(true);
    ImageButton ImgBtnFavoritos=(ImageButton)findViewById(R.id.ImgBtnFavoritos);
    //显示所有新闻
    setOnClickListener(新的OnClickListener(){
    @凌驾
    公共void onClick(视图arg0){
    isfavorite=false;
    telaMensagens(lista);
    }
    });
    //仅显示体育新闻
    setOnClickListener(新的OnClickListener()){
    @凌驾
    公共void onClick(视图arg0){
    isfavorite=false;
    telaMensagens(Categorizador(lista,“Esportes”);
    }
    });
    //只显示警方新闻
    setOnClickListener(新的OnClickListener(){
    @凌驾
    公共void onClick(视图arg0){
    isfavorite=false;
    telaMensagens(Categorizador(lista,Polícia));
    }
    });
    //仅显示comunity新闻
    ImgBtnComunidade.setOnClickListener(新的OnClickListener(){
    @凌驾
    公共void onClick(视图arg0){
    isfavorite=false;
    telaMensagens(分类法(lista,“Comunidade”);
    }
    });
    //显示喜爱的新闻
    setOnClickListener(新的OnClickListener()){
    @凌驾
    公共void onClick(视图arg0){
    NoticiaDAO banco=新NoticiaDAO(getBaseContext());
    试一试{
    List noticias=banco.getLista();
    banco.close();
    isfavorite=true;
    telaMensagens(通知);
    }捕获(解析异常){
    Log.e(“Erro ao tentar abrir Favoritos”和“+e”);
    }
    }
    });
    }否则{
    吐司t;
    t=吐司
    .makeText(
    getBaseContext(),
    “无需通知,无需通知……\N更新日期。”,
    吐司长度(长);
    t、 show();
    setContentView(R.layout.main);
    evento++;
    ImageButton imgbtnesport=(ImageButton)findViewById(R.id.imgbtnesport);
    imgbtnesport.setClickable(false);
    ImageButton ImgBtnTodas=(ImageButton)findViewById(R.id.ImgBtnTodas);
    ImgBtnTodas.setClickable(false);
    ImageButton ImgBtnComunidade=(ImageButton)findViewById(R.id.ImgBtnComunidade);
    ImgBtnComunidade.setClickable(假);
    ImageButton ImgBtnPolicia=(ImageButton)findViewById(R.id.ImgBtnPolicia);
    ImageButton ImgBtnFavoritos=(ImageButton)findViewById(R.id.ImgBtnFavoritos);
    imgbtna.setClickable(false);
    setOnClickListener(新的OnClickListener()){
    @凌驾
    公共void onClick(视图arg0){
    NoticiaDAO banco=新NoticiaDAO(getBaseContext());
    试一试{
    List noticias=banco.getLista();
    banco.close();
    isfavorite=true;
    特拉曼萨
    
     /*
      * / call the screen with the news as a list
      */
     public void telaMensagens(final List<Noticia> noticias) {
    
         evento--;
         // controll the number of times the backbutton is pressed
    
         /*
          * / call the xml screen for the list
          */
         setContentView(R.layout.lista);
    
         /*
          * / declarando um listview em java que chama o listview do xml
          */
         ListView lista = (ListView) findViewById(R.id.listView1);
         if (!noticias.isEmpty()) {
             // declarando arrayadapter que adapta uma arraylist em uma lista
             /*
              * / android dependendo do método tostring()
              */
             ArrayAdapter<Noticia> adapter = new ArrayAdapter<Noticia>(this,
                     R.layout.listadjust, noticias);
    
             /*
              * / setando o adapter
              */
             lista.setAdapter(adapter);
    
             /*
              * / permitindo que a lista seja clicável
              */
             lista.setClickable(true);
    
             /*
              * / qual ação a lista tomará ao clicar em um item
              */
             lista.setOnItemClickListener(new OnItemClickListener() {
                 @Override
                 public void onItemClick(AdapterView<?> arg0, View arg1,
                         int arg2, long arg3) {
                     telaLeitura(arg2, noticias);
                 }
             });
         } else {
             Toast t;
             t = Toast.makeText(getBaseContext(),
                     "Não há noticias para essa categoria no momento...",
                     Toast.LENGTH_SHORT);
             t.show();
    
         }
     }
    
     /*/
      * --------------------------------------------------------------------------------
      */
    
     /*
      * / call the news reader screen and stantiate the imagebuttons to see images and */add to favorites
      */
     public void telaLeitura(int posicao, List<Noticia> noticias) {
         setContentView(R.layout.telaleitura);
         TextView texto = (TextView) findViewById(R.id.textView1);
         final Noticia atual = noticias.get(posicao);
         texto.setText(atual.getContent());
         texto.setClickable(true);
         final ImageButton getImageButton = (ImageButton) findViewById(R.id.imageButton1);
         ImageButton favoritos = (ImageButton) findViewById(R.id.imageButton2);
         ImageButton Excluir = (ImageButton) findViewById(R.id.imageButton3);
         if (!isfavorite) {
             favoritos.setVisibility(0);
         } else {
    
             Excluir.setVisibility(0);
         }
         /*
          * / controll delete button
          */
         Excluir.setOnClickListener(new OnClickListener() {
    
             @Override
             public void onClick(View v) {
                 AlertDialog.Builder builder = new AlertDialog.Builder(AndroidfeedtsxActivity.this);
                 builder.setMessage("Deseja excluir esse favorito?")
                        .setCancelable(false)
                        .setPositiveButton("Sim", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                 NoticiaDAO banco = new NoticiaDAO(getBaseContext());
                                 banco.excluir(atual.getId());
                                 banco.close();
                                 Toast t;
                                 t = Toast.makeText(getBaseContext(),
                                         "Favorito Excluido com sucesso.", Toast.LENGTH_SHORT);
                                 t.show();
                                 noticias();
                            }
                        })
                        .setNegativeButton("Não", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                 dialog.cancel();
    
                            }
                        });
                 AlertDialog alert = builder.create();
                 alert.show();
    
             }
         });
    
         /*
          * / controlling favorites insertion
          */
         favoritos.setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View arg0) {
                 final NoticiaDAO banco = new NoticiaDAO(getBaseContext());
    
                 try {
                     List<Noticia> Noticias = banco.getLista();
                     if (!Noticias.contains(atual)) {
                         //Cria alerta dialogo confirmando...
                         AlertDialog.Builder builder = new AlertDialog.Builder(AndroidfeedtsxActivity.this);
                         builder.setMessage("Deseja adicionar noticia aos favoritos?")
                                .setCancelable(false)
                                .setPositiveButton("Sim", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                         banco.inserir(atual);
                                         Toast t;
                                         t = Toast
                                                 .makeText(getBaseContext(),
                                                         "Adicionada aos favoritos!",
                                                         Toast.LENGTH_SHORT);
                                         t.show();
                                         banco.close();
                                    }
                                })
                                .setNegativeButton("Não", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                         dialog.cancel();
                                         banco.close();
                                    }
                                });
                         AlertDialog alert = builder.create();
                         alert.show();
    
                     } else {
                         Toast t;
                         t = Toast.makeText(getBaseContext(),
                                 "Notícia já está nos favoritos.",
                                 Toast.LENGTH_SHORT);
                         t.show();
                         banco.close();
                     }
                 } catch (ParseException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
    
    
             }
         });
    
         /*
          * /if the news have images
          */
         if (atual.getImages().size() > 0) {
             getImageButton.setVisibility(0);
    
             // oque o botão fará quando clicado
             getImageButton.setOnClickListener(new OnClickListener() {
    
                 @Override
                 public void onClick(View v) {
                     if (atual.getImages().size() > 0) {
                         // cria a intenção de chamar galeria, e inicia a
                         // activity galeria
                         Intent it = new Intent(getBaseContext(),
                                 GalleryTSX.class);
                         it.putStringArrayListExtra("Lista",
                                 (ArrayList<String>) atual.getImages());
                         setIntent(it);
                         startActivity(it);
                     }
                 }
             });
         }
     }
    
     /*
      * / controll backbutton when pressed twice(non-Javadoc)
      * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
      */
     @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    
             if (evento < 2 && evento > 0) {
                 Toast t;
                 // Toast é um alerta do sistema
                 t = Toast.makeText(this, "Pressione mais uma vez para sair",
                         Toast.LENGTH_SHORT);
                 t.show();
             }
             if (evento > 1) {
                 //Inicia serviço de alerta de Noticias Novas
                 startService(new Intent(this, UpdateService.class));
                 finish();
    
             }
             noticias();
             return true;
         }
    
         return super.onKeyDown(keyCode, event);
     }
    
    
    
     /*
      * / Controll news categorizer
      */
     public List<Noticia> Categorizador(List<Noticia> lista, String categoria) {
         List<Noticia> categorizada = new ArrayList<Noticia>();
         for (Noticia noticias : lista) {
             if (noticias.getCategory().equalsIgnoreCase(categoria)) {
                 categorizada.add(noticias);
             }
         }
         return categorizada;
     }
    
     /*
      * / must be implemented for gallery usage(non-Javadoc)
      * @see android.widget.ViewSwitcher.ViewFactory#makeView()
      */
     @Override
     public View makeView() {
         ImageView iView = new ImageView(this);
         iView.setScaleType(ImageView.ScaleType.FIT_CENTER);
         iView.setLayoutParams(new ImageSwitcher.LayoutParams(
                 LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    
         return iView;
     }
    
    
    
     /*/
      * (non-Javadoc)creates the menu
      * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
      */
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.layout.menu, menu);
         return true;
     }
    
     /*/
      * (non-Javadoc) create a option in the menu "update"
      * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
      */
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
    
         case R.id.text:
             this.exists=null;
             noticias();
             break;
    
         }
         return true;
     }
    
     // controlls if must be updated or not
     public void noticias() {
         dialog = ProgressDialog.show(this, "Aguarde...",
                 "Baixando noticias, por favor aguarde...", false, true);
         if(this.exists==null || this.exists.isEmpty()){
             new Thread() {
                 /*/
                  * (non-Javadoc) Pegar As noticias do RSS e fazer parse
                  * @see java.lang.Thread#run()
                  */
                 @Override
                 public void run() {
                     try {
                         List<Noticia> noticias = new ArrayList<Noticia>();
                         URL url = new URL(
                                 "http://www.tudosobrexanxere.com.br/index.php/rss");
                         SAXParserFactory factory = SAXParserFactory.newInstance();
                         NoticiaHandler handler = new NoticiaHandler();
                         SAXParser saxParser= factory.newSAXParser();
                         saxParser.parse(url.openStream(), handler);
                         noticias = handler.getMessages();
                         telaPrincipal(noticias);
                     } catch (ParserConfigurationException e1) {
                         Log.e("Exception no Parser de ParserConfiguration",
                                 "Exception" + e1);
                         Toast t;
                         // Toast é um alerta do sistema
                         t = Toast.makeText(AndroidfeedtsxActivity.this, "Problema ao obter notícias\nPor favor, use o menu para atualizar...",
                                 Toast.LENGTH_LONG);
                         t.show();
                         if(exists!=null){
                             telaPrincipal(exists);
                         }
                         else{
                             telaPrincipal(new ArrayList<Noticia>());
                         }
    
                     } catch (SAXException e1) {
                         // TODO Auto-generated catch block
                         Log.e("Exception no Parser de SaxException", "Exception"
                                 + e1);
                         Toast t;
                         // Toast é um alerta do sistema
                         t = Toast.makeText(AndroidfeedtsxActivity.this, "Problema ao obter notícias\nPor favor, atualize as noticias...",
                                 Toast.LENGTH_LONG);
                         t.show();
                         if(exists!=null){
                             telaPrincipal(exists);
                         }
                         else{
                             telaPrincipal(new ArrayList<Noticia>());
                         }
    
                     } catch (IOException e) {
                         if(exists!=null){
                             telaPrincipal(exists);
                         }
                         else{
                             telaPrincipal(new ArrayList<Noticia>());
                         }
                         Toast t;
                         // Toast é um alerta do sistema
                         t = Toast.makeText(AndroidfeedtsxActivity.this, "Problema na sua conexão com a Internet\nPor favor, tente novamente mais tarde...",
                                 Toast.LENGTH_LONG);
                         t.show();
                         Log.e("Exception no Parser de IO", "Exception" + e);
                     } catch (Exception e) {
                         if(exists!=null){
                             telaPrincipal(exists);
                         }
                         else{
                             telaPrincipal(new ArrayList<Noticia>());
                         }
                         Toast t;
                         // Toast é um alerta do sistema
                         t = Toast.makeText(AndroidfeedtsxActivity.this, "Problema ao obter notícia\nPor favor, atualize as noticias...",
                                 Toast.LENGTH_LONG);
                         t.show();
                         Log.e("Exception no Parser", "Exception" + e);
                     }
    
                 }
    
             }.start();
    
         }else telaPrincipal(exists);
    
     } 
    
    ImageButton ImgBtnEsportes = (ImageButton) findViewById(R.id.ImgBtnEsportes);
    ImgBtnEsportes.setClickable(true);
    ImgBtnEsportes.setTag("Esportes");
    
    ImageButton ImgBtnTodas = (ImageButton) findViewById(R.id.ImgBtnTodas);
    ImgBtnTodas.setClickable(true);
    ImgBtnEsportes.setTag("Todas");
    
     // etc
    
    OnClickListener buttonClickListener = new OnClickListener(){
    
         @Override
         public void onClick(View arg0) {
    
             String tag = ((String)arg0.getTag());
    
             if(tag.equalsIgnoreCase("Esportes")){
    
                 isfavorite = false;
                 telaMensagens(Categorizador(lista, "Esportes"));
    
             } else if(tag.equalsIgnoreCase("Todas")){
                 isfavorite = false;
                 telaMensagens(Categorizador(lista, "Todas")); 
             }
    
         }
    
    
    };
    
    ImgBtnEsportes.setOnClickListener(buttonClickListener);
    ImgBtnTodas.setOnClickListener(buttonClickListener);
    
        @Override
        public void onClick(View arg0) {
    
             int viewID = arg0.getId();
    
             if(viewID == R.id.ImgBtnEsportes){
    
                             isfavorite = false;
                             telaMensagens(Categorizador(lista, "Esportes"));
    
             } else if(viewID == R.id.ImgBtnTodas){
                 isfavorite = false;
                             telaMensagens(Categorizador(lista, "Todas")); 
             }
    
        }
    
     private void telaPrincipal(final List<Noticia> naoFormatada) {
          //close progress dialog
          dialog.dismiss();
    
    
         //Formating my xml
         final List<Noticia> lista = new Formatador()
         .Formatar(naoFormatada);
    
         if (!(lista.isEmpty() || lista== null)) {
             exists = naoFormatada;
             // etc
    
    }