从BackgroundTask方法获取数组到另一个Activity

时间:2014-02-24 22:39:04

标签: java android arrays android-activity

我是Java / ADT的新手,我正试图从“活动A”到“活动B”获得一个数组。该应用程序从网页获取信息,然后将其保存在一对数组中并显示信息。我想点击“转到图表”按钮(调用viewallday())重定向到活动B,活动B将显示包含所有这些信息的图形。

问题是它们是一个自刷新阵列(1秒刷新),并且当应用程序处于图形模式(活动B)时不想放弃此功能。关于如何做到这一点的任何想法?

提前感谢大家,我从这个网站上学到很多东西。

UPDATE :我正在尝试使用Singleton模式。但LogCat说:

02-26 22:21:59.300:E / AndroidRuntime(2677):致命异常:主要 02-26 22:21:59.300:E / AndroidRuntime(2677):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.Chispa / com.example.Chispa.Activity_allday}:android.os.NetworkOnMainThreadException 02-26 22:21:59.300:E / AndroidRuntime(2677):引起:android.os.NetworkOnMainThreadException

更新2:终于搞定了!!这是我使用的代码:

以下是活动A的代码:

public class MainActivity extends Activity {

private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvdate=(TextView)findViewById(R.id.tvdate);
        tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
        tvmax=(TextView)findViewById(R.id.tvmaximo);
        tvmid=(TextView)findViewById(R.id.tvmedio);
        tvmin=(TextView)findViewById(R.id.tvminimo);

        new BackGroundTask().execute();

        callAsynchronousTask();

    }


    public void callAsynchronousTask() {
        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {       
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {       
                        try {
                            BackGroundTask performBackgroundTask = new BackGroundTask();
                            // PerformBackgroundTask this class is the class that extends AsynchTask 
                            performBackgroundTask.execute();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public class Pair
    {
        public String[] bar;
        public String[] values;
    }

       public void viewallday(View view) {



            Intent intent = new Intent(MainActivity.this, Activity_allday.class);


            startActivity(intent);



        }  





    class BackGroundTask extends AsyncTask<Void, Void, Pair> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }



        public String[] getValuesGraph(Document doc) {


                int cont=24,var=7;
                String bar[] = new String[cont];



               /*
                * Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
                */

               for (cont=0; cont < 24; cont++){

               String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
               bar[cont] = onMouseOver.split("'")[9];


               }


               return bar;



        }



        public String[] getValuesFooter(Document doc) {



            String values[] = new String[7];


            /*
                * Getting elements from the graphic footer
                */

               String delimiters= "[ /]+";
               Elements elements = doc.select("td.cabeceraRutaTexto");
               elements.size(); // 6



                   /*  Getting text from table */
                   values[0] = elements.get(0).text(); // TITLE
                   values[1] = elements.get(1).text(); // TEXT MAX VALUE
                   values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
                   values[3] = elements.get(3).text(); // TEXTO MIN VALUE

                   /* Getting numbers from table */

                   values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
                   values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
                   values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE    


                   return values;


         }


        public Document getUrl(){

              try {
                    URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?FECHA=20140226");
                    /*URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?lang=es&frameId=4064&segmento=1&promocion=");*/
                    Document doc = Jsoup.connect(url.toString()).get();

                    return doc;      

              } catch (IOException e) {
                    e.printStackTrace();
                }
              return null;
        }

        @Override
        public Pair doInBackground(Void... params) {

            Pair p = new Pair();


                GlobalVariables gs = (GlobalVariables) getApplication();
                gs.setBar(getValuesGraph(getUrl()));

                p.bar = getValuesGraph(getUrl());

                p.values = getValuesFooter(getUrl());


         return p;


        }



        public String ActualHourValue() {

            Format formatter = new SimpleDateFormat("H");
            String onlyhour = formatter.format(new Date());

            return onlyhour;


        }

        public void ShowDateHour(){


            Calendar c = Calendar.getInstance();
            SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
            String formattedDate3 = df3.format(c.getTime());
            tvdate.setText("Fecha y hora actuales : "+formattedDate3);

        }


        @Override
        protected void onPostExecute(Pair p) {



            int hour =  Integer.parseInt(ActualHourValue());
            tvvaloractual.setText(p.bar[hour]+" €/MWh");

            tvmax.setText(p.values[4]+" €/MWh");
            tvmid.setText(p.values[5]+" €/MWh");
            tvmin.setText(p.values[6]+" €/MWh");

            ShowDateHour();

           /*super.onPostExecute(p.values);*/
        }





    }




}

以下是活动B的代码:

public class Activity_allday extends MainActivity {


private TextView tvall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_day_price);

        TextView tvall=(TextView)findViewById(R.id.tvall); 

        GlobalVariables gs = (GlobalVariables) getApplication();
        String[] s = gs.getBar();
        tvall.setText(s[0]);       

    }

}

这是一个GlobalVariable类,它捕获我想要发送给Activity B的数组:

public class Activity_allday extends MainActivity {


private TextView tvall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_day_price);

        TextView tvall=(TextView)findViewById(R.id.tvall); 

        GlobalVariables gs = (GlobalVariables) getApplication();
        String[] s = gs.getBar();
        tvall.setText(s[0]);       

    }

}

这就是全部!希望它对未来的用户有所帮助。

感谢大家的帮助。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

在AsyncTask中,定义一个接口及其中的方法,将数据传递回调用活动,并在该方法内部调用下一个活动并将数据设置为额外的。

这是最简单的方法。

在AsyncTask中,在onPostExecute(result)中,使用try块来调用属于上述接口的方法,该方法必须由调用活动实现。

<强> HomeActivity.java

/public class SampleActivity extends Activity implements SampleAsyncTask.OnUpdateListener{

 @Override
 public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);

     executeAsync();
 }

 public void executeAsync(){

     new SampleAsyncTask(this).execute("someFlagToCheck");
 }

 @Override
 public void onDataProcessed(String result){

    Intent intent = new Intent(this, SecondActivity.class);
    intent.putExtra("data", result);
    startActivity(intent);
 }
}

<强> SampleAsyncTask.java

public class SampleAsyncTask extends AsyncTask<Void, Void, String>{

    Context context;

    //constructor
    SampleAsyncTask(Context context){
       this.context = context;
    }

    @Override
    public void doInBackground(String... params){

         //do something depending on the arguments in params
         return "data";
    }


    @Override
    public void onPostExecute(String result){

        try{
           ((OnUpdateListener) context).onDataProcessed(result);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public interface OnUpdateListener{

        public void onDataProcessed(String data);
    }
}

请按照此示例操作。调用活动实现AsyncTask的接口并覆盖其方法,当异步任务完成结果时将调用该方法。

我希望这会有所帮助。

答案 1 :(得分:0)

解决方案:

以下是活动A的代码:

public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvdate=(TextView)findViewById(R.id.tvdate);
    tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
    tvmax=(TextView)findViewById(R.id.tvmaximo);
    tvmid=(TextView)findViewById(R.id.tvmedio);
    tvmin=(TextView)findViewById(R.id.tvminimo);

    new BackGroundTask().execute();

    callAsynchronousTask();

}


public void callAsynchronousTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {       
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {       
                    try {
                        BackGroundTask performBackgroundTask = new BackGroundTask();
                        // PerformBackgroundTask this class is the class that extends AsynchTask 
                        performBackgroundTask.execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public class Pair
{
    public String[] bar;
    public String[] values;
}

   public void viewallday(View view) {



        Intent intent = new Intent(MainActivity.this, Activity_allday.class);


        startActivity(intent);



    }  





class BackGroundTask extends AsyncTask<Void, Void, Pair> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }



    public String[] getValuesGraph(Document doc) {


            int cont=24,var=7;
            String bar[] = new String[cont];



           /*
            * Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
            */

           for (cont=0; cont < 24; cont++){

           String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
           bar[cont] = onMouseOver.split("'")[9];


           }


           return bar;



    }



    public String[] getValuesFooter(Document doc) {



        String values[] = new String[7];


        /*
            * Getting elements from the graphic footer
            */

           String delimiters= "[ /]+";
           Elements elements = doc.select("td.cabeceraRutaTexto");
           elements.size(); // 6



               /*  Getting text from table */
               values[0] = elements.get(0).text(); // TITLE
               values[1] = elements.get(1).text(); // TEXT MAX VALUE
               values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
               values[3] = elements.get(3).text(); // TEXTO MIN VALUE

               /* Getting numbers from table */

               values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
               values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
               values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE    


               return values;


     }


    public Document getUrl(){

          try {
                URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?FECHA=20140226");
                /*URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?lang=es&frameId=4064&segmento=1&promocion=");*/
                Document doc = Jsoup.connect(url.toString()).get();

                return doc;      

          } catch (IOException e) {
                e.printStackTrace();
            }
          return null;
    }

    @Override
    public Pair doInBackground(Void... params) {

        Pair p = new Pair();


            GlobalVariables gs = (GlobalVariables) getApplication();
            gs.setBar(getValuesGraph(getUrl()));

            p.bar = getValuesGraph(getUrl());

            p.values = getValuesFooter(getUrl());


     return p;


    }



    public String ActualHourValue() {

        Format formatter = new SimpleDateFormat("H");
        String onlyhour = formatter.format(new Date());

        return onlyhour;


    }

    public void ShowDateHour(){


        Calendar c = Calendar.getInstance();
        SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
        String formattedDate3 = df3.format(c.getTime());
        tvdate.setText("Fecha y hora actuales : "+formattedDate3);

    }


    @Override
    protected void onPostExecute(Pair p) {



        int hour =  Integer.parseInt(ActualHourValue());
        tvvaloractual.setText(p.bar[hour]+" €/MWh");

        tvmax.setText(p.values[4]+" €/MWh");
        tvmid.setText(p.values[5]+" €/MWh");
        tvmin.setText(p.values[6]+" €/MWh");

        ShowDateHour();

       /*super.onPostExecute(p.values);*/
      }





    }


  }

活动B:

public class Activity_allday extends MainActivity {


private TextView tvall;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_day_price);

    TextView tvall=(TextView)findViewById(R.id.tvall); 

    GlobalVariables gs = (GlobalVariables) getApplication();
    String[] s = gs.getBar();
    tvall.setText(s[0]);       

}

}

全局变量类,它捕获我想要发送到活动B的数组:

public class Activity_allday extends MainActivity {


private TextView tvall;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_day_price);

    TextView tvall=(TextView)findViewById(R.id.tvall); 

    GlobalVariables gs = (GlobalVariables) getApplication();
    String[] s = gs.getBar();
    tvall.setText(s[0]);       

}
}

谢谢大家的帮助!!