android:异步进程从onPostExecute获取数据后查看或传递视图到onPostExecute

时间:2015-11-22 23:40:29

标签: android asynchronous textview

我正在尝试动态添加额外的输入字段到我的视图。

我首先使用异步函数从url读取json字符串,并将其动态映射到带有GSON的hasmap的对象。

接下来我想迭代hashmap来创建和添加输入字段:

public class NewProductActivity extends Activity {

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_product);

     TextView view =  (TextView) this.findViewById(android.R.id.content);// is this the correct way to get view?

    new loadTemplateAttributes(view).execute();// android studio complains about passing view here

   .. snip...

    class loadTemplateAttributes extends AsyncTask<String, String, HashMap> {

    HashMap mymap;

    .. snip...

 protected void onPostExecute(HashMap mymap) {

        pDialog.dismiss();

        Iterator it = mymap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            String name = (String) pair.getKey();
            TemplateAttribureProperties t = (TemplateAttribureProperties) pair.getValue();
            String type = t.getType();
            System.out.println("Name=" + name + " type=" + type);

            LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout2);

            // add text view
            TextView tv = new TextView(this); // 'this' is unknow here
            tv.setText(name);
            ll.addView(tv);

            EditText et = new EditText(view); // 'view' is what i want to pass but dont know how
            et.setText();
            ll.addView(et);
            it.remove(); 
        }

问题是&#39;这个&#39;在onPostExecute函数中是未知的。

我读到了一些关于将视图传递给异步函数的内容,但对我而言,目前还不清楚如何在第一时间获取视图以及如何在...后传递视图...

也有很多选项似乎不起作用,因为它们已被弃用或不安全,因为可能会根据评论引入内存泄漏。

真的迷失在这里。

2 个答案:

答案 0 :(得分:0)

我不知道你在做什么但是你可以在onCreate()之前使用Context context;TextView view;使其成为全局,然后你可以在你的方法中调用TextView tv = new TextView(context);

public class NewProductActivity extends Activity {
Context context=this;
private TextView view;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_product);

    view =  (TextView) findViewById(android.R.id.content);

}

答案 1 :(得分:0)

  

new loadTemplateAttributes(view).execute(); // android studio抱怨在这里传递视图

你必须在asynctask中添加构造函数,如:

  class loadTemplateAttributes extends AsyncTask<String, String, HashMap> {
      View view;
      public loadTemplateAttributes(View v) {
          view = v;
      }
  

TextView tv = new TextView(this); //'这个'这里不知道

来自java中的内部类,在您的情况下使用NewProductActivity.this语法引用父类。

  

EditText et = new EditText(view); //'view'是我想传递但不知道怎么做的               et.setText();

如上所述,您可以将aproach与构造函数一起使用,或直接引用活动视图:NewProductActivity.this.view。但是你必须在你的活动中查看一个类字段。

高级:使您的活动成为内部类而不是静态,并且还将视图传递给它,可能会导致引用泄漏,并且在您使用由于屏幕旋转而无效的视图(在AsyncTask内部)时也会崩溃。如果您的AsyncTask正在进行网络操作,这尤其可行。为了防止它始终使AsyncTasks成为静态,如果您将视图或活动传递给它们,那么将这些引用包装在WeakReference<>

相关问题