doInBackground方法出错

时间:2014-01-01 18:10:02

标签: android json asynchronous

我下课时有错误。 错误在以下方法:doinbackground。它说:'该方法必须返回结果类型的Void'。我不能因为它而建造。

我不知道如何修复它。我是android和java的新手,我没有看到在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)

4 个答案:

答案 0 :(得分:4)

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。更新ui onPostExecute

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

答案 1 :(得分:1)

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

你也在更新你的Ui意味着你在另一个线程中的观点......不接受..

将代码移至onPostExecuteonPreExecte

答案 2 :(得分:0)

您正在doInBackground移动updatePlaces();更新您的观点至onPostExecute

您无法在后台更新视图,将所有视图更新为onPostExecute,  示例shopNameTextView.setText(jsonObject.getString("name"));

全局声明jsonObject以获取参考。

答案 3 :(得分:0)

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