System.InvalidOperationException Android

时间:2015-10-30 10:14:35

标签: c# android xamarin xamarin.android

在Xamarin上编写Android应用程序。

出现此错误

[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] System.InvalidOperationException: Operation is not valid due to the current state of the object
[MonoDroid] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0x00028>
[MonoDroid] at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>m__0 (object) <0x0003f>
[MonoDroid] at Android.App.SyncContext/<Post>c__AnonStorey0.<>m__0 () <0x00027>
[MonoDroid] at Java.Lang.Thread/RunnableImplementor.Run () <0x0003f>
[MonoDroid] at Java.Lang.IRunnableInvoker.n_Run (intptr,intptr) <0x0003b>
[MonoDroid] at (wrapper dynamic-method) object.abf695dd-f4ec-4a71-8e1c-73614b06354b (intptr,intptr) <0x0003b>
[AndroidRuntime] Shutting down VM
[AndroidRuntime] FATAL EXCEPTION: main
[AndroidRuntime] java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
[AndroidRuntime] 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
[AndroidRuntime] 	at dalvik.system.NativeStart.main(Native Method)
[AndroidRuntime] Caused by: java.lang.reflect.InvocationTargetException
[AndroidRuntime] 	at java.lang.reflect.Method.invokeNative(Native Method)
[AndroidRuntime] 	at java.lang.reflect.Method.invoke(Method.java:511)
[AndroidRuntime] 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
[AndroidRuntime] 	... 2 more
[AndroidRuntime] Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.InvalidOperationException: Operation is not valid due to the current state of the object
[AndroidRuntime] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0x00028>
[AndroidRuntime] at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>m__0 (object) <0x0003f>
[AndroidRuntime] at Android.App.SyncContext/<Post>c__AnonStorey0.<>m__0 () <0x00027>
[AndroidRuntime] at Java.Lang.Thread/RunnableImplementor.Run () <0x0003f>
[AndroidRuntime] at Java.Lang.IRunnableInvoker.n_Run (intptr,intptr) <0x0003b>
[AndroidRuntime] at (wrapper dynamic-method) object.abf695dd-f4ec-4a71-8e1c-73614b06354b (intptr,intptr) <0x0003b>
[AndroidRuntime] 
[AndroidRuntime] 	at mono.java.lang.RunnableImplementor.n_run(Native Method)
[AndroidRuntime] 	at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:29)
[AndroidRuntime] 	at android.os.Handler.handleCallback(Handler.java:725)
[AndroidRuntime] 	at android.os.Handler.dispatchMessage(Handler.java:92)
[AndroidRuntime] 	at android.os.Looper.loop(Looper.java:153)
[AndroidRuntime] 	at android.app.ActivityThread.main(ActivityThread.java:5330)

我通过网址

进行解析

解析器代码

string url2 = "http://new.murakami.ua/?mkapi=getProductsByCat&cat_id=182";
    JsonValue json = await FetchAsync(url2);

    ParseAndDisplay1(json);
    ParseAndDisplay2(json);
    ParseAndDisplay3(json);
private async Task<JsonValue> FetchAsync(string url2)
{
    // Create an HTTP web request using the URL:
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url2));
    request.ContentType = "application/json";
    request.Method = "GET";`

    // Send the request to the server and wait for the response:
    using (WebResponse response = await request.GetResponseAsync())
    {
        // Get a stream representation of the HTTP web response:
        using (Stream stream = response.GetResponseStream())
        {
            // Use this stream to build a JSON document object:
            JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

            Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());


            // Return the JSON document:
            return jsonDoc;
        }
    }
}

private void ParseAndDisplay1(JsonValue json)
{


    //ImageButton product = FindViewById<ImageButton>(Resource.Id.vugor);
    TextView productname = FindViewById<TextView>(Resource.Id.posttittle);
    TextView price = FindViewById<TextView>(Resource.Id.price);
    TextView weight = FindViewById<TextView>(Resource.Id.weight);
    JsonValue firstitem = json[43];
    //Console.Out.WriteLine(firstitem["post_title"].ToString());
    productname.Text = firstitem["post_title"];
    price.Text = firstitem["price"] + " грн";
    weight.Text = firstitem["weight"] + "г";
    productname.Click += delegate
    {
        var intent485 = new Intent(this, typeof(LanchiDetails1));
        StartActivity(intent485);
    };



}
private void ParseAndDisplay2(JsonValue json)
{


    //ImageButton product = FindViewById<ImageButton>(Resource.Id.vugor);
    TextView productname = FindViewById<TextView>(Resource.Id.posttittle1);
    TextView price = FindViewById<TextView>(Resource.Id.price1);
    TextView weight = FindViewById<TextView>(Resource.Id.weight1);
    JsonValue firstitem = json[3];
    //Console.Out.WriteLine(firstitem["post_title"].ToString());
    productname.Text = firstitem["post_title"];
    price.Text = firstitem["price"] + " грн";
    weight.Text = firstitem["weight"] + "г";

    productname.Click += delegate
    {
        var intent486 = new Intent(this, typeof(LanchiDetails2));
        StartActivity(intent486);
    };



}
private void ParseAndDisplay3(JsonValue json)
{


    //ImageButton product = FindViewById<ImageButton>(Resource.Id.vugor);
    TextView productname = FindViewById<TextView>(Resource.Id.posttittle2);
    TextView price = FindViewById<TextView>(Resource.Id.price2);
    TextView weight = FindViewById<TextView>(Resource.Id.weight2);
    JsonValue firstitem = json[2];
    //Console.Out.WriteLine(firstitem["post_title"].ToString());
    productname.Text = firstitem["post_title"];
    price.Text = firstitem["price"] + " грн";
    weight.Text = firstitem["weight"] + "г";
    productname.Click += delegate
    {
        var intent487 = new Intent(this, typeof(LanchiDetails3));
        StartActivity(intent487);
    };


}

我尝试评论ParseAndDisplay- ParseAndDisplay3

请参阅回复

但是当我取消注释ParseAndDisplay -ParseAndDisplay3时,我有错误“应用已经停止”。

代码有什么问题?

2 个答案:

答案 0 :(得分:0)

当您的异步任务(FetchAsync)仍在运行时,看起来正在调用ParseAndDisplay。

在你的ParseAndDisplay函数中,检查json的值,你可能会发现它是null。

在调用ParseAndDisplay之前,您需要等待FetchAsync完成。或者你可以从FetchAsync调用ParseAndDisplay

答案 1 :(得分:0)

解决方案就是:

旧API

Array
(
    [43] => WP_Post Object
        (
            [ID] => 4378
            [post_author] => 4
            [post_date] => 2015-10-01 12:47:54
            [post_date_gmt] => 2015-10-01 08:47:54
            [post_content] => 
            [post_title] => Ямато
            [post_excerpt] => Курячий бульйон з яйцем / салат овочевий з заправкою насу / крохмальна локшина з овочами та свининою
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => yamato-0
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-08 14:38:18
            [post_modified_gmt] => 2015-10-08 10:38:18
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/yamato-0/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/YAmato.jpg
            [visibility] => visible
            [price] => 99.00
            [weight] => 225/110/175
            [energy] => 
            [sku] => 172
            [category] => 182
        )

    [3] => WP_Post Object
        (
            [ID] => 4377
            [post_author] => 4
            [post_date] => 2015-10-01 12:47:54
            [post_date_gmt] => 2015-10-01 08:47:54
            [post_content] => 
            [post_title] => Хонсю
            [post_excerpt] => Місо суп / салат овочевий з лососем / курячі крильця теріякі з сирним соусом
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => honsyu
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-08 14:37:27
            [post_modified_gmt] => 2015-10-08 10:37:27
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/honsyu/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/Honsyu.jpg
            [visibility] => visible
            [price] => 99.00
            [weight] => 165/120/180/40
            [energy] => 
            [sku] => 156
            [category] => 182
        )

    [4] => WP_Post Object
        (
            [ID] => 4237
            [post_author] => 7
            [post_date] => 2015-09-08 12:29:11
            [post_date_gmt] => 2015-09-08 08:29:11
            [post_content] => 
            [post_title] => Фудзіяма
            [post_excerpt] => Суп суймоно з кальмаром / салат теріякі з куркою / рол з огірком / рис смажений з грибами
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => fudziyama
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-08 14:38:51
            [post_modified_gmt] => 2015-10-08 10:38:51
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/fudziyama/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/Fudziyama.jpg
            [visibility] => visible
            [price] => 99.00
            [weight] => 210/140/116/180 
            [energy] => 
            [sku] => 471
            [category] => 182
        )

)

新API

Array
(
    [0] => WP_Post Object
        (
            [ID] => 4378
            [post_author] => 4
            [post_date] => 2015-10-01 12:47:54
            [post_date_gmt] => 2015-10-01 08:47:54
            [post_content] => 
            [post_title] => Ямато
            [post_excerpt] => Курячий бульйон з яйцем / салат овочевий з заправкою насу / крохмальна локшина з овочами та свининою
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => yamato-0
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-08 14:38:18
            [post_modified_gmt] => 2015-10-08 10:38:18
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/yamato-0/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/YAmato.jpg
            [visibility] => visible
            [price] => 99.00
            [weight] => 225/110/175
            [energy] => 
            [sku] => 172
            [category] => 182
        )

    [1] => WP_Post Object
        (
            [ID] => 4377
            [post_author] => 4
            [post_date] => 2015-10-01 12:47:54
            [post_date_gmt] => 2015-10-01 08:47:54
            [post_content] => 
            [post_title] => Хонсю
            [post_excerpt] => Місо суп / салат овочевий з лососем / курячі крильця теріякі з сирним соусом
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => honsyu
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-08 14:37:27
            [post_modified_gmt] => 2015-10-08 10:37:27
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/honsyu/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/Honsyu.jpg
            [visibility] => visible
            [price] => 99.00
            [weight] => 165/120/180/40
            [energy] => 
            [sku] => 156
            [category] => 182
        )

    [2] => WP_Post Object
        (
            [ID] => 4237
            [post_author] => 7
            [post_date] => 2015-09-08 12:29:11
            [post_date_gmt] => 2015-09-08 08:29:11
            [post_content] => 
            [post_title] => Фудзіяма
            [post_excerpt] => Суп суймоно з кальмаром / салат теріякі з куркою / рол з огірком / рис смажений з грибами
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => fudziyama
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-08 14:38:51
            [post_modified_gmt] => 2015-10-08 10:38:51
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/fudziyama/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/Fudziyama.jpg
            [visibility] => visible
            [price] => 99.00
            [weight] => 210/140/116/180 
            [energy] => 
            [sku] => 471
            [category] => 182
        )

)

我们已经混乱了,感觉像物体