【问题标题】:Error with doInBackground methoddoInBackground 方法出错
【发布时间】:2023-03-07 17:25:01
【问题描述】:

我在下面的课程中有一个错误。 错误出现在以下方法上:doinbackground。它说:“该方法必须返回 Void 的结果类型”。因此我无法构建。

我不知道如何解决它。我是 android 和 java 的新手,我不知道在哪里将 return 放在 void 方法上。

一定很明显(我希望如此),请帮我解决这个问题并解释为什么会出现这个错误。

这是我的课:(已编辑)

我确实添加了 null 来消除错误,但后来出现异常(已编辑)

编辑:我尝试将更新的 UI 项目移动到 onPostExecute,现在活动永远加载。这是我更新的课程和日志:

public class ShopActivity extends Activity {

private int userIcon, jewelleryIcon;
private GoogleMap theMap;
private LocationManager locMan;
private Marker userMarker;
private Marker bijouterie;
private Button emailButton;
private long latitude;
private long longitude;
private String image1;
private String image2;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
private ImageButton button4;
private ImageButton button5;
private ImageButton button6;
private ImageButton catalogue;
private Button goToMap;
private String thebooketurl = null;
private ProgressDialog pDialog;

// URL to get JSON
private static String url = "http://api.json?client_id=id&client_secret=id";

/** Called when the activity is first created. 
 * @return */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Portrait only
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    //Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_shop);



    // View's main buttons

    goToMap = (Button)findViewById(R.id.mapClick);
    goToMap.setOnClickListener(new OnClickListener()  
    {
        @Override          
        public void onClick(View goToMap) {
            Intent intent = new Intent(ShopActivity.this, FullMapActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.fadein, R.anim.fadeout);
        }
    });

    button1 = (ImageButton)findViewById(R.id.imageButton1);
    button1.setOnClickListener(new OnClickListener()  
    {
        @Override          
        public void onClick(View Button1) {
            finish();//go back to the previous Activity
            overridePendingTransition(R.anim.backin, R.anim.backout); 
        }
    });

    button2 = (ImageButton)findViewById(R.id.imageButton2);
    button2.setOnClickListener(new OnClickListener()  
    {
        @Override          
        public void onClick(View Button1) {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("message/rfc822");
            i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"contact@mail.com"});
            i.putExtra(Intent.EXTRA_SUBJECT, "");
            i.putExtra(Intent.EXTRA_TEXT   , "");
            try {
                startActivity(Intent.createChooser(i, "Send mail..."));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(ShopActivity.this, "Pas de client de messagerie installé sur cet appareil.", Toast.LENGTH_SHORT).show();
            }
        }
    });

    button3 = (ImageButton)findViewById(R.id.imageButton3);
    button3.setOnClickListener(new OnClickListener()  
    {
        @Override          
        public void onClick(View Button1) {
            Intent intent = new Intent(ShopActivity.this, PhilosophyActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.animationin, R.anim.animationout);
        }
    });

    button4 = (ImageButton)findViewById(R.id.imageButton4);
    button4.setOnClickListener(new OnClickListener()  
    {
        @Override          
        public void onClick(View Button1) {
            finish();//go back to the previous Activity
            overridePendingTransition(R.anim.backin, R.anim.backout); 
        }
    });

    button5 = (ImageButton)findViewById(R.id.imageButton6);
    button5.setOnClickListener(new OnClickListener()  
    {
        @Override          
        public void onClick(View Button1) {
            Intent intent = new Intent(ShopActivity.this, MapActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.animationin, R.anim.animationout);
        }
    });

    button6 = (ImageButton)findViewById(R.id.feuilletez);
    button6.setOnClickListener(new OnClickListener()  
    {
        @Override          
        public void onClick(View Button1) {
            Intent intent = new Intent(ShopActivity.this, PdfReader.class);
            startActivity(intent);
            overridePendingTransition(R.anim.animationin, R.anim.animationout);
            intent.putExtra("shopurl", thebooketurl);
        }
    });





    // Add fonts

    //     Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/HelveticaNeueBold.ttf");

    // View's items



    // Calling async task to get json
    new GetJson().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetJson extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();


        // Showing progress dialog
        pDialog = new ProgressDialog(ShopActivity.this);
        pDialog.setMessage("Mise à jour...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        JSONArray array = null;
        try {
            array = new JSONArray(jsonStr);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {


            JSONObject jsonObject = array.getJSONObject(0);
            String id = jsonObject.getString("id");
            System.out.println("id --->" + id);
            String url = jsonObject.getString("url");
            System.out.println("url --->" + url);
            String created_at = jsonObject.getString("created_at");
            System.out.println("created_at --->" + created_at);
            String updated_at = jsonObject.getString("updated_at");
            System.out.println("updated_at --->" + updated_at);
            String name = jsonObject.getString("name");
            //.setText(jsonObject.getString("name"));
            System.out.println("name --->" + name);
            String phone = jsonObject.getString("phone");
        /*  if(phone == "null")
            //  shopPhoneTextView.setText("-");
            else
            //  shopPhoneTextView.setText(jsonObject.getString("phone"));
        */  System.out.println("phone --->" + phone);
            String fax = jsonObject.getString("fax");
            if(fax == "null")
        /*  //  shopFaxTextView.setText("-");
            else
            //  shopFaxTextView.setText(jsonObject.getString("fax"));
        */  System.out.println("fax --->" + fax);

            final String email = jsonObject.getString("email");

            emailButton = (Button)findViewById(R.id.buttonEmail);   
            emailButton.setOnClickListener(new OnClickListener()
            {
                @Override          
                public void onClick(View Button4) {
                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setType("message/rfc822");
                    if(email == "null")
                        i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"contact@mail.com"});
                    else
                        i.putExtra(Intent.EXTRA_EMAIL  , new String[]{email});
                    i.putExtra(Intent.EXTRA_SUBJECT, "");
                    i.putExtra(Intent.EXTRA_TEXT   , "");
                    try {
                        startActivity(Intent.createChooser(i, "Send mail..."));
                    } catch (android.content.ActivityNotFoundException ex) {
                        Toast.makeText(ShopActivity.this, "Pas de client de messagerie installé sur cet appareil.", Toast.LENGTH_SHORT).show();
                    }
                }
            });


            //shopEmailTextView.setText(jsonObject.getString("email"));
            System.out.println("email --->" + phone);
            String website_url = jsonObject.getString("website_url");
            System.out.println("website_url --->" + phone);
            String detail = jsonObject.getString("detail");
            System.out.println("detail --->" + detail);
            String logo_url = jsonObject.getString("logo_url");
            System.out.println("logo_url --->" + logo_url);
            String logo_thumbnail_url = jsonObject.getString("logo_thumbnail_url");
            System.out.println("logo_thumbnail_url --->" + logo_thumbnail_url);
            JSONArray photos_urls = jsonObject.getJSONArray("photos_urls");
            System.out.println("photos_urls --->" + photos_urls);

            image1 = photos_urls.getString(0);

            if(image1 != null){
                new DownloadImageTask((ImageView) findViewById(R.id.firstImage))
                .execute(image1);
            }

            image2 = photos_urls.getString(0);

            if(image2 != null){
                new DownloadImageTask((ImageView) findViewById(R.id.secondImage))
                .execute(image2);
            }


            JSONArray opening_hours = jsonObject.getJSONArray("opening_hours");

            String hoursTitle = "Horaires d'ouverture :";
            String lundi = opening_hours.getString(0);
            if(lundi==null)
                lundi = "NC";
            String mardi = opening_hours.getString(1);
            String mercredi = opening_hours.getString(2);
            String jeudi = opening_hours.getString(3);
            String vendredi = opening_hours.getString(4);
            String samedi = opening_hours.getString(5);

    //      shopHoursTextView.setText(hoursTitle+"\nLundi : "+lundi+"\nMardi : "+mardi+"\nMercredi : "+mercredi+"");
    //      shopHoursTextView2.setText("Jeudi : "+jeudi+"\nVendredi : "+vendredi+"\nSamedi : "+samedi);




            System.out.println("opening_hours --->" + opening_hours);
            String address_string = jsonObject.getString("address_string");
            //shopAddressTextView.setText(jsonObject.getString("address_string"));
            System.out.println("address_string --->" + address_string);

            JSONObject contact = jsonObject.getJSONObject("contact");
            String title = contact.getString("title");
            System.out.println("title --->" + title);
            String first_name = contact.getString("first_name");
            System.out.println("first_name --->" + first_name);
            String last_name = contact.getString("last_name");
            System.out.println("last_name --->" + last_name);

            JSONObject address = jsonObject.getJSONObject("address");
            String id_address = address.getString("id");
            System.out.println("id --->" + id_address);
            String url_address = address.getString("url");
            System.out.println("url --->" + url_address);
            String created_at_address = address.getString("created_at");
            System.out.println("created_at_address --->" + created_at_address);
            String updated_at_address = address.getString("updated_at");
            System.out.println("updated_at_address --->" + updated_at_address);
            String street_address = address.getString("street_address");
            System.out.println("street_address --->" + street_address);
            String extended_address = address.getString("extended_address");
            System.out.println("extended_address --->" + extended_address);
            String postal_code = address.getString("postal_code");
            System.out.println("postal_code --->" + postal_code);
            String locality = address.getString("locality");
            System.out.println("locality --->" + locality);
            String country_code_alpha2 = address.getString("country_code_alpha2");
            System.out.println("country_code_alpha2 --->" + country_code_alpha2);
            JSONArray coordinates = address.getJSONArray("coordinates");
            System.out.println("coordinates --->" + coordinates);

            latitude = coordinates.getLong(0);
            longitude = coordinates.getLong(1);



            JSONObject booklet = jsonObject.getJSONObject("booklet");
            String id_booklet = booklet.getString("id");
            System.out.println("id_booklet --->" + id_booklet);
            String url_booklet = booklet.getString("url");
            System.out.println("url_booklet --->" + url_booklet);
            String created_at_booklet = booklet.getString("created_at");
            System.out.println("created_at_booklet --->" + created_at_booklet);
            String updated_at_booklet = booklet.getString("updated_at");
            System.out.println("updated_at_booklet --->" + updated_at_booklet);
            String title_booklet = booklet.getString("title");
            System.out.println("title_booklet --->" + title_booklet);
            String thumbnail_url = booklet.getString("thumbnail_url");
            System.out.println("thumbnail_url --->" + thumbnail_url);
            String document_url = booklet.getString("document_url");
            System.out.println("document_url --->" + document_url);
            thebooketurl = document_url;
            String presented = booklet.getString("presented");

            System.out.println("presented --->" + presented);


        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return null;

    }

    }

private void updateShop(){
    TextView shopAddressTextView=(TextView) findViewById(R.id.shopAddress);
    // shopAddressTextView.setTypeface(typeFace);
    TextView shopNameTextView=(TextView) findViewById(R.id.shopName);
    TextView shopPhoneTextView=(TextView) findViewById(R.id.shopPhone);
    TextView shopFaxTextView=(TextView) findViewById(R.id.shopFax);
    TextView shopHoursTextView=(TextView) findViewById(R.id.shopHours);
    TextView shopHoursTextView2=(TextView) findViewById(R.id.shopHours2);
    ImageView firstImage=(ImageView) findViewById(R.id.firstImage);
    ImageView secondImage=(ImageView) findViewById(R.id.secondImage);

    // string just to test
    shopNameTextView.setText("name");
    shopAddressTextView.setText("name");
    shopPhoneTextView.setText("name");
    shopFaxTextView.setText("name");
    shopHoursTextView.setText("name");
    shopHoursTextView2.setText("name");
}

private void updatePlaces(){

    // Check status of Google Play Services
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    // Check Google Play Service Available
    try {
        if (status != ConnectionResult.SUCCESS) {
        }
    } catch (Exception e) {
        Log.e("Error: GooglePlayServiceUtil: ", "" + e);
    }

    // Google Maps

    userIcon = R.drawable.blue_point;
    jewelleryIcon = R.drawable.pointeur;

    if(theMap==null){
        //map not instantiated yet
    }
    theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
    if(theMap != null){
        //ok - proceed
    }
    theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    // Map
    LatLng BIJOUTERIE = new LatLng(latitude, longitude); 
    bijouterie = theMap.addMarker(new MarkerOptions()
    .position(BIJOUTERIE)
    .title("Bijouterie")
    .icon(BitmapDescriptorFactory.fromResource(jewelleryIcon))
    .snippet("35 rue du Gateau, Mer"));

    theMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 7.5f), 4000, null);             

}


@Override
public void onBackPressed() {
    finish();//go back to the previous Activity
    overridePendingTransition(R.anim.backin, R.anim.backout);  
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap myImage = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            myImage = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        myImage = Bitmap.createScaledBitmap(myImage, 300, 200, false);;
        return myImage;


    }

    protected void onPostExecute(Bitmap result) {
           bmImage.setImageBitmap(result);
           updatePlaces();
           updateShop();
    }
}
}

我的日志(设备上的进度对话框不停地加载):

01-01 19:34:04.502: W/System.err(9164):     at org.json.JSONObject.get(JSONObject.java:354)
01-01 19:34:04.502: W/System.err(9164):     at org.json.JSONObject.getString(JSONObject.java:510)
01-01 19:34:04.502: W/System.err(9164):     at com.begital.votrebijoutier.ShopActivity$GetJson.doInBackground(ShopActivity.java:235)
01-01 19:34:04.502: W/System.err(9164):     at com.begital.votrebijoutier.ShopActivity$GetJson.doInBackground(ShopActivity.java:1)
01-01 19:34:04.502: W/System.err(9164):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-01 19:34:04.502: W/System.err(9164):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-01 19:34:04.502: W/System.err(9164):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-01 19:34:04.502: W/System.err(9164):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-01 19:34:04.502: W/System.err(9164):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-01 19:34:04.502: W/System.err(9164):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)

【问题讨论】:

    标签: android json asynchronous


    【解决方案1】:
    The method must return a result type of Void
    

    错误说明了一切。只需要doInbackground末尾有return语句即可

    改成

     @Override
     protected Void doInBackground(Void... arg0) {
         // rest of the code
       return null;
     } 
    

    编辑:

    Only the original thread that created a view hierarchy can touch its views.
    

    无法从后台线程更新 ui。更新uionPostExecute

    shopPhoneTextView.setText("-"); 无法在 doInbackground 中执行此操作。删除所有更新 ui 的类似语句。我不能全部提及,因为您的代码很大。

    【讨论】:

    • 我这样做了,但现在我有一个例外,我在我的问题中添加了我的日志。
    • @Xavier 再提出一个建议,将所有变量声明为实例变量,并在 onCreate 而不是 doInBackground 中初始化您的视图
    • 好的,我开始理解这个问题了。我会尝试你们都建议的。我要回去重新开始。感谢您的帮助。
    【解决方案2】:

    doInBackground 方法的末尾添加return null..

    你也在更新你的 Ui 意味着你在另一个线程中的视图..这不被接受..

    所以将该代码移至onPostExecuteonPreExecte

    【讨论】:

      【解决方案3】:

      只需将您的updatePlaces(); 放到onPostExecute,如果您需要更多时间,可以使用延迟。 如果onPostExecute 你没有找到,那么你已经覆盖了它。

      【讨论】:

        【解决方案4】:

        您正在更新doInBackground 中的视图,将updatePlaces(); 移动到onPostExecute

        你不能在后台更新视图,将所有更新的视图移动到onPostExecute, 示例shopNameTextView.setText(jsonObject.getString("name"));

        全局声明 jsonObject 以获取参考。

        【讨论】:

        • 还是不行。 onPostExecute 已经将位图作为参数。也许这就是它无法工作的原因?
        猜你喜欢
        • 2015-01-01
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-07
        • 2012-03-18
        相关资源
        最近更新 更多