【问题标题】:Using the response of one Class into another将一个类的响应用于另一个类
【发布时间】:2010-11-02 06:13:44
【问题描述】:

我创建了一个应用程序,其中我扩展了一个 Activity 并使用 Asynctask 成功地从 Web 服务获得响应,现在我想在主 Activity 之外的另一个类中对收到的响应进行 Json 解析。

如何做到这一点?如何在单独的类中使用接收到的主活动响应,因为在下一个类中我只想使用从主类获得的响应进行解析。

谁能给我一个答案!

谢谢, 大卫

【问题讨论】:

    标签: android json parsing class android-asynctask


    【解决方案1】:

    您可以通过传递给另一个类的构造函数或作为任何函数参数传递来将值发送给另一个类。

    或者如果你想将值传递给 Asynctask 类

     public class abc extends Activity {
    
     new AsynctaskClassName.execute(response);      
     }
    

    Asynctask 将是

     public class AsynctaskClassNameextends AsyncTask <String, String, String> {
     protected Z doInBackground(String... res){  
     ...  
      response = res[0]  
     ...   
    }
    

    或者将价值传递给另一个意图,最好是通过

        Intent.putExtra("response", response);
    

    并被阅读

     Bundle extras = getIntent().getExtras();
     String response = extras.getString("response");
    

    【讨论】:

      【解决方案2】:

      您可以简单地创建一个新类

      public class Parser
      {
      public static String rawJSON;
      ....
      }
      

      现在在您的 AsyncTask 中,只需像这样将 JSON 响应存储在 Parser.rawJSON 中

      protected Z doInBackground(X...x){
      ...
      Parser.rawJSON=responseFromServer(URL);
      ...
      }
      

      &你完成了!

      【讨论】:

      • 我在 AsyncTask 的 onPostExecute 方法中得到了来自 Web 服务的响应,如下所示:protected void onPostExecute(String result) { System.out.println("Output Response:-----> " + 结果); }
      • 我可以在任何地方直接使用 Result 变量吗?
      • @david 不,要在 Parser 类中使用您的结果: void onPostExecute(String result) { System.out.println("Output Response:----->" + result); Parser.rawJSON= 结果}
      猜你喜欢
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      相关资源
      最近更新 更多