简体   繁体   中英

System.InvalidOperationException Android

Writing Android app on Xamarin.

Have this error

 [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) 

I doing parser by url

Code of parser

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);
    };


}

I try to comment ParseAndDisplay- ParseAndDisplay3

And see Response

But when I uncomment ParseAndDisplay -ParseAndDisplay3 I have error "Application has stopped".

What's wrong with code?

It looks like your calls to ParseAndDisplay are being called while your async task (FetchAsync) is still running.

In your ParseAndDisplay functions, check the value of json and you will probably find it is null.

You need to wait for FetchAsync to complete before calling ParseAndDisplay. Or you could call ParseAndDisplay from FetchAsync

Solution was in this:

Old 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 ) ) 

New 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 ) ) 

We have disordered massive, that perceived like object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM