Android线程问题onCreate

时间:2013-12-30 16:32:11

标签: android json

我在尝试显示此活动时遇到异常。我是Android开发人员的新手,任何帮助都会很棒!我无法找出导致坠机的原因。

这是我的活动课程:

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 catalogue;
private Button goToMap;
private String thebooketurl = null;
private String url;
private ProgressDialog pDialog;

/** Called when the activity is first created. 
 * @return */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shop);

    // Get url
    Bundle extras = getIntent().getExtras(); if (extras == null) {
        return;
        }
        String urlshop = extras.getString("shopurl");

    String credentials = "?clientid";
    url = (urlshop+credentials);
    System.out.println("url --->" + url);

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

            // Internet check
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            android.net.NetworkInfo wifi = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo datac = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if ((wifi != null & datac != null)
                    && (wifi.isConnected() | datac.isConnected())) {
                    //connection is OK
                     }else{
                    //no connection
                      Toast toast = Toast.makeText(ShopActivity.this, "Une erreur a été rencontrée. Veuillez vérifier votre connexion à internet",
                    Toast.LENGTH_LONG);

            toast.show();  
                     }

         // 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("rue du Temple, Marseille"));

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



            // 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("Chargement...");
        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);



    // 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.fr"});
                    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);
               }
               });

            catalogue = (ImageButton)findViewById(R.id.feuilletez);
            catalogue.setOnClickListener(new OnClickListener()  
            {
               @Override          
               public void onClick(View Button1) {
                   Intent bookleturl = new Intent(ShopActivity.this, PdfReader.class);
                    bookleturl.putExtra("bookleturl", thebooketurl);
                    startActivity(bookleturl);

                   Intent intent = new Intent(ShopActivity.this, PdfReader.class);
                   startActivity(intent);
                   overridePendingTransition(R.anim.animationin, R.anim.animationout);
               }
               });

    // Add fonts

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

    // View's items
             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);

             /*
            // Reading text file from assets folder
            StringBuffer sb = new StringBuffer();
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(getAssets().open(
                        "test.json")));
                String temp;
                while ((temp = br.readLine()) != null)
                    sb.append(temp);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close(); // stop reading
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String myjsonstring = sb.toString();
            Log.d("string: " , myjsonstring);*/



            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");
                 shopNameTextView.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.fr"});
                         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);
                 String presented = booklet.getString("presented");
                 thebooketurl = presented;
                 System.out.println("presented --->" + presented);


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

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

以下是具有致命异常的日志:

12-30 17:15:43.105: E/AndroidRuntime(25254): FATAL EXCEPTION: main
12-30 17:15:43.105: E/AndroidRuntime(25254): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.begital.votrebijoutier/com.begital.votrebijoutier.ShopActivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.os.Looper.loop(Looper.java:137)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.ActivityThread.main(ActivityThread.java:4745)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at java.lang.reflect.Method.invokeNative(Native Method)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at java.lang.reflect.Method.invoke(Method.java:511)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at dalvik.system.NativeStart.main(Native Method)
12-30 17:15:43.105: E/AndroidRuntime(25254): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
12-30 17:15:43.105: E/AndroidRuntime(25254):    at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:215)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.Activity.requestWindowFeature(Activity.java:3225)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at com.begital.votrebijoutier.ShopActivity.onCreate(ShopActivity.java:108)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.Activity.performCreate(Activity.java:5008)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-30 17:15:43.105: E/AndroidRuntime(25254):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-30 17:15:43.105: E/AndroidRuntime(25254):    ... 11 more

我认为它是由多线程引起的,但我现在对此并不是很满意。

3 个答案:

答案 0 :(得分:0)

日志说明了一切,放

 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
 this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

之前

 setContentView(R.layout.activity_shop);

答案 1 :(得分:0)

你的回调中有答案:

Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content

你必须移动这一行:

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

之前:

setContentView()

来自docs:

http://developer.android.com/reference/android/view/Window.html#requestFeature(int)

  

启用扩展屏幕功能。这必须在之前调用   的setContentView()。可以根据需要多次调用它   在setContentView()之前。如果没有调用,则不会扩展功能   能得到的。请求后,您无法关闭该功能。您   canot使用FEATURE_CUSTOM_TITLE的其他标题功能。

答案 2 :(得分:0)

有两种解决方法。

  1. 您可以在setContentView方法

    之前设置这些行
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    

    对于您的情况,只需设置第二行就可以使代码正常工作。

  2. 您可以在清单的活动中为上述3行设置相关标记。

    <activity
        android:name=".ShopActivity"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:screenOrientation="portrait"
        />
    

    这也可以,你不需要在你的Activity的Java代码中写上面的3行。

  3. 希望它有所帮助。