gpt4 book ai didi

android - Xamarin 安卓 : Exception thrown when adding new ImageView to ViewFlipper

转载 作者:行者123 更新时间:2023-11-29 01:40:17 25 4
gpt4 key购买 nike

这是我的第一个 Xamarin 项目。我正在尝试为 Android 创建一个简单的幻灯片应用程序。

这是托管 ViewFlipper 的 Main.axml 代码。

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ViewFlipper
android:id="@+id/view_flipper"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ViewFlipper>
</RelativeLayout>

这是 Activity 代码。

namespace RS
{
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[Activity (Label = "RS", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);

// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);

StartSlideshow (this);
}

private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;

url = url.Replace("\"", "");

using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}

return imageBitmap;
}

private void StartSlideshow(Context ctx)
{
string[] slides = null;
string url = "http://jsonplaceholder.typicode.com/photos";
var httpReq = (HttpWebRequest)HttpWebRequest.Create (new Uri (url));

httpReq.BeginGetResponse ((ar) => {

//Fetch the slides
var request = (HttpWebRequest)ar.AsyncState;
using (var response = (HttpWebResponse)request.EndGetResponse (ar)) {
var s = response.GetResponseStream ();
var j = (JsonArray)JsonArray.Load (s);

//Prepare the slides
slides = (from result in j
select result ["url"].ToString ()).ToArray ();

//Display the slides
ViewFlipper mViewFlipper = FindViewById<ViewFlipper>(Resource.Id.view_flipper);

for (int i = 0; i < 10; i++) {
ImageView image = new ImageView(ctx);
image.SetImageBitmap(GetImageBitmapFromUrl(slides[i]));
try {
mViewFlipper.AddView(image);
} catch (Exception ex) {
Log.Error(ex.ToString(), "Couldn't add image to flipper");
}
}

mViewFlipper.AutoStart = true;
mViewFlipper.SetFlipInterval (2000);
mViewFlipper.StartFlipping ();
}
} , httpReq);

}
}
}

当我尝试向 ViewFlipper 添加一个新的 ImageView 时(在我从 Web 服务调用中获取要显示的图像列表之后),出现以下错误。

ex  {Android.Util.AndroidRuntimeException: Exception of type 'Android.Util.AndroidRuntimeException' was thrown.
at Android.Runtime.JNIEnv.CallVoidMethod (IntPtr jobject, IntPtr jmethod, Android.Runtime.JValue[] parms) [0x00063] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.12-series/163212a9/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:507
at Android.Views.ViewGroup.AddView (Android.Views.View child) [0x00043] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.12-series/163212a9/source/monodroid/src/Mono.Android/platforms/android-19/src/generated/Android.Views.ViewGroup.cs:1761
at RS.MainActivity+<>c__DisplayClass2.<StartSlideshow>b__0 (IAsyncResult ar) [0x000a0] in c:\Users\girish\Dropbox\Work\Rejini\android\RejiniSlider\RS\RS\MainActivity.cs:84
--- End of managed exception stack trace ---
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4039)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:709)
at android.view.View.requestLayout(View.java:12675)
at android.view.View.requestLayout(View.java:12675)
at android.view.View.requestLayout(View.java:12675)
at android.view.View.requestLayout(View.java:12675)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:268)
at android.view.View.requestLayout(View.java:12675)
at android.view.ViewGroup.addView(ViewGroup.java:3206)
at android.widget.ViewAnimator.addView(ViewAnimator.java:182)
at android.view.ViewGroup.addView(ViewGroup.java:3165)
at android.view.ViewGroup.addView(ViewGroup.java:3145)
at dalvik.system.NativeStart.run(Native Method)
} Android.Util.AndroidRuntimeException

两个问题:

  1. 这是在 Android 中构建动态幻灯片的错误方法吗?

  2. 如何修复上面显示的错误?

感谢您的帮助。

更新:我根据 tomjen 和 Simon 的回答更新了代码以使用异步。这是更新后的方法:

private Task<Bitmap> GetImageBitmapFromUrl(string url)
{
Task<Bitmap> imageBitmap = null;

url = url.Replace("\"", "");

RunOnUiThread ( () => {
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadDataTaskAsync(url);
if (imageBytes != null) // && imageBytes.Result.Length > 0
{
try {
imageBitmap = BitmapFactory.DecodeByteArrayAsync(imageBytes.Result, 0, imageBytes.Result.Length);
} catch (Exception ex) {
Log.Error(ex.ToString(), "Couldn't download image");
}
}
}
});

return imageBitmap;
}

不幸的是,我仍然遇到同样的错误。 :(

最佳答案

不要使用 BeginGet/EndGet 模式。它的存在只是出于历史原因。使用(更容易的)async/await 模式——这也确保其余的发生在 UI 线程上。

您需要的方法是 WebClient 类 ( http://msdn.microsoft.com/en-us/library/system.net.webclient.downloaddatataskasync(v=vs.110).aspx ) 中的 DownloadDataAsyncTask。

改变

private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;

url = url.Replace("\"", "");

using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}

return imageBitmap;
}

类似的东西

private async Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;

url = url.Replace("\"", "");

using (var webClient = new WebClient())
{
var imageBytes = await webClient.DownloadDataAsyncTask(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length);
}
}

return imageBitmap;
}

这样做的结果是方法中的所有内容(IO 除外)都在主线程上运行,并且该代码只是等待 IO 完成。

您也可以(并且应该)对另一种方法执行类似的操作。您可以在 WebClient 对象上使用 DownloadStringAsyncTask 方法来执行此操作 (http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstringtaskasync(v=vs.110).aspx)。

关于android - Xamarin 安卓 : Exception thrown when adding new ImageView to ViewFlipper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com