Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 切换到AsyncTask后未显示UI_Java_Android_Json_Android Asynctask - Fatal编程技术网

Java 切换到AsyncTask后未显示UI

Java 切换到AsyncTask后未显示UI,java,android,json,android-asynctask,Java,Android,Json,Android Asynctask,在阅读了AsyncTask的效率之后,我最近切换到了AsyncTask。移植我的代码花了一些时间,但最终我做到了。我有一个AsyncTask首先运行,设置从json对象获取的背景图像/颜色。之后,它为JSON文件中的所有其他字段设置TableRows。背景会更改,但UI不会显示。我将System.out.println放在我的AsyncTask中,我看到代码已通过onPostExecute方法执行,但没有显示任何UI。我不知道问题是什么,因此我发布了这个问题 以下是我的任务: class Get

在阅读了AsyncTask的效率之后,我最近切换到了AsyncTask。移植我的代码花了一些时间,但最终我做到了。我有一个AsyncTask首先运行,设置从json对象获取的背景图像/颜色。之后,它为JSON文件中的所有其他字段设置TableRows。背景会更改,但UI不会显示。我将System.out.println放在我的AsyncTask中,我看到代码已通过onPostExecute方法执行,但没有显示任何UI。我不知道问题是什么,因此我发布了这个问题

以下是我的任务:

class GetImageAsync extends AsyncTask<String, Void, Drawable> {
private final WeakReference<View> ViewReference;
private String data;
private Context context;
private boolean isImageView;
private boolean scale;
private int id = -1;
private int color = -1;
private int height = -1;

public GetImageAsync(TableLayout tr, String data, Context context) {

    isImageView = false;
    this.context = context;
    this.data = data;
    ViewReference = new WeakReference<View>(tr);
    System.out.println("inside async");

} 

public GetImageAsync(ImageView iv, int id, Context context) {
    isImageView = true;
    this.context = context;
    this.id = id;
    ViewReference = new WeakReference<View>(iv);
} 

public GetImageAsync(ImageView imageView,String data, Context context, int height) {
    System.out.println("profile async");
    this.height  = height;
    isImageView = true;
    this.context = context;
    this.data = data;
    ViewReference = new WeakReference<View>(imageView);
} 

// Decode image in background. 
@Override 
protected Drawable doInBackground(String... params) {
    System.out.println(id + " : " + isImageView);
    if(isImageView && id != -1) {
        return getImageFromResource();
    } else {
        if(data.startsWith("#")) {
            color = Color.parseColor(data);
            return null;
        }
        try {
            return getImageFromWeb(data, scale);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
} 

private Drawable getImageFromResource() {
    return context.getResources().getDrawable(id);
}

private Drawable getImageFromWeb(String data, boolean b) throws MalformedURLException, IOException {
    Bitmap img = BitmapFactory.decodeStream(new URL(data).openConnection().getInputStream());
    if(height != -1) {
        return new BitmapDrawable(context.getResources(), getCroppedBitmap(Bitmap.createScaledBitmap(
                Bitmap.createScaledBitmap(img,
                        img.getWidth(),
                        img.getWidth(), true),
                height * 2,
                height * 2, true)));

    } 
    return new BitmapDrawable(context.getResources(), img);

}

// Once complete, see if ImageView is still around and set bitmap. 
@Override 
protected void onPostExecute(Drawable bitmap) {

    if(isImageView) {                                                       //this block does not {
        System.out.println("post "+isImageView);

        System.out.println("iv");
        if (ViewReference != null && bitmap != null) {
            final ImageView imageView = (ImageView) ViewReference.get();
            if (imageView != null) {
                imageView.setImageDrawable(bitmap);
            } 
        }                                                                   // }
    } else {                                                                //this block runs {
        System.out.println("post "+isImageView);

        if (ViewReference != null) {

            final TableLayout tr = (TableLayout) ViewReference.get();

            if (tr != null) {
                if(color != -1) {
                    tr.setBackgroundColor(color);

                } else {
                    tr.setBackground(bitmap);

                }
            } 
        } 
    }                                                                       // }

} 

public static Bitmap getCroppedBitmap(Bitmap bitmap) {

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int radius = Math.min(h / 2, w / 2);
    Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Config.ARGB_8888);

    Paint p = new Paint();
    p.setAntiAlias(true);

    Canvas c = new Canvas(output);
    c.drawARGB(0, 0, 0, 0);
    p.setStyle(Style.FILL);

    c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);

    p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

    c.drawBitmap(bitmap, 4, 4, p);
    p.setXfermode(null);
    p.setStyle(Style.STROKE);
    p.setColor(Color.BLACK);
    p.setStrokeWidth(1);

    c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
    return output;
}
} 

你在哪里打电话给createUI?它不在postExecute@meda添加了代码我认为您正在传递ApplicationContext,您可能需要传递Activity。这是您开始Aysnc任务的地方。我尝试过执行getBaseContext和此操作,但仍然不起作用。但是,我发现如果我注释掉了AsyncTask,因此imageview没有得到图像,它仍然不会显示我的UI。我知道它与AsyncTask无关,因为我输入了int System.out,它说它访问了.addViewv。我不知道我的代码出了什么问题。。。
private void createUI(JSONObject jObject) throws JSONException {
    int absIndex = 0;
    if (android.os.Build.VERSION.SDK_INT >= 16) {
        new GetImageAsync(tr, jObject.getString(("bg")), getApplicationContext()).execute("");
        System.out.println("after async");

        /*if (bgcolor != -1) {
            System.out.println("color: " + bgcolor);
            tr.setBackgroundColor(bgcolor);
        } else if (bgpic != null) {
            tr.setBackground(bgpic);
        }*/
    }

    for (int i = 0; i < keys.length; i++) {
        values.add(i, new ArrayList<String>());
        values.get(i).add(0, keys[i]);
        values.get(i).add(1, jObject.getString(keys[i]));
    }

    String lastString = WhoIsLast(jObject);

    trcard.setBackground(getResources()
            .getDrawable(R.drawable.bg_card/* abc_menu_dropdown_panel_holo_light */));
    trcard.addView(tlcard);
    tr.setPadding(0, 0, 0, 0);

    TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
            TableLayout.LayoutParams.MATCH_PARENT,
            TableLayout.LayoutParams.WRAP_CONTENT);

    int[] attrs = { android.R.attr.dividerVertical };
    TypedArray typedArray = getApplicationContext().obtainStyledAttributes(
            attrs);
    Drawable divider = typedArray.getDrawable(0);
    typedArray.recycle();

    tableRowParams.setMargins(20, 20, 20, 0);
    trcard.setLayoutParams(tableRowParams);
    tlcard.setDividerDrawable(divider);

    tlcard.setDividerPadding(4);

    tableScrollView.addView(trcard);

    for (int i = 0; i < keys.length; i++) {
        String value = values.get(i).get(1);
        if (value != "") {
            String key = values.get(i).get(0);
            boolean last = false;

            if (i == keys.length || value.equals(lastString) || i == 0) {
                last = true;
                System.out.println(value +" = "+lastString);
            }
            insertElement(value, key, absIndex++, last, drawables[i]);
            if (!last) {
                absIndex++;
            }
        }
    }



}



private String WhoIsLast(JSONObject j) throws JSONException {
    if (j.getString("facebook").equals("")) {
        return "";
    }
    if (j.getString("twitter").equals("")) {
        return "facebook";
    }
    if (j.getString("email").equals("")) {
        return "twitter";
    }
    if (j.getString("phone").equals("")) {
        return "email";
    }

    return "";
}
int absIndex = 0;
private void insertElement(String data, String key, int i,
        boolean b, Integer id) throws JSONException {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View newRow = inflater.inflate(R.layout.row, null, false);
    newRow.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT,
            TableRow.LayoutParams.WRAP_CONTENT));

    TextView dataTextView = (TextView) newRow
            .findViewById(R.id.rowTextView);
    dataTextView.setText("\t " + data);
    ImageView iv = (ImageView) newRow.findViewById(R.id.rowImageView);
    newRow.setId(absIndex++);
    newRow.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            //omitted 
    });

    View v = new View(this);
    v.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT, 1));
    v.setBackgroundColor(Color.argb(25, 111, 111, 111));

    dataTextView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    if (i == 0) {
        System.out.println("before async iv");
        new GetImageAsync(iv, jObject.getString("profilepic"), getApplicationContext(), dataTextView.getMeasuredHeight()).execute("");
        System.out.println("after async iv");

        //async.execute(""); 
        dataTextView.setShadowLayer(3, 0, 0, Color.BLACK);
        dataTextView.setTextColor(getResources().getColor(R.color.white));
    } else {
        new GetImageAsync(iv, id, getApplicationContext()).execute("");
    }



    if (i == 0) {
        dataTextView.setTextSize(30);

        tableScrollView.addView(newRow, i);
        System.out.println("adding i=0null");
    } else {
        System.out.println("adding i = "+i +tlcard);

        tlcard.addView(newRow, i - 1);
        if (!b) {
            tlcard.addView(v, i);
        }
    }
}
    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            jObject = getJson("http://www.tabcards.com/req/androidapi/L2o30H8JlFMtFYHW3KLxkts20ztc5Be6Z6m6v315/json/"
                    + value);
            System.out.println(value);
            if (jObject != null) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            createUI(jObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
    });
    thread.start();