繁体   English   中英

setImageResource在调用时使应用程序崩溃

[英]setImageResource crashes application when invoked

我尝试设置IV_status.setImageResource(R.drawable.red)

但似乎无法正常工作,只要调用上述代码,整个应用

会崩溃。我也尝试过setBackgroundResource(R.drawable.red)但同样的问题是

发生。 它会崩溃,然后才能进入活动屏幕。

public class PhotosActivity extends ListActivity {
// Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    ArrayList<HashMap<String, String>> productsList;
    // url to get all products list
    private static String url_all_products = "http://10.0.8.41/pos/get_all_products.php";

    // JSON Node names

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "tables";
    private static final String TAG_PID = "tableID";
    private static final String TAG_NAME = "tableName";
    private static final String TAG_AREA = "area";
    private static final String TAG_STATUS = "status";
    static ImageView IV_status;
    // products JSONArray
    JSONArray products = null;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photos_layout);
    IV_status = (ImageView) findViewById(R.id.status);

    IV_status.setImageResource(R.drawable.red);
    // Hashmap for ListView
            productsList = new ArrayList<HashMap<String, String>>();

            // Loading products in Background Thread
            new LoadAllProducts().execute();

            // Get listview
            ListView lv = getListView();

            // on seleting single product
            // launching Edit Product Screen



        }

        // Response from Edit Product Activity
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            // if result code 100
            if (resultCode == 100) {
                Intent intent = getIntent();
                finish();
                startActivity(intent);
            }

        }

        /**
         * Background Async Task to Load all product by making HTTP Request
         * */
        class LoadAllProducts extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(PhotosActivity.this);
                pDialog.setMessage("Loading products. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

            /**
             * getting All products from url
             * */
            protected String doInBackground(String... args) {

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

                // Check your log cat for JSON reponse
                Log.d("All Products: ", json.toString());

                try {
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {

                        products = json.getJSONArray(TAG_PRODUCTS);


                        for (int i = 0; i < products.length(); i++) {
                            JSONObject c = products.getJSONObject(i);

                            // Storing each json item in variable
                            String id = c.getString(TAG_PID);
                            String name = c.getString(TAG_NAME);
                            String area = c.getString(TAG_AREA);
                            String status = c.getString(TAG_STATUS);
                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            map.put(TAG_PID, id);
                            map.put(TAG_NAME, name);
                            map.put(TAG_AREA,area);
                            map.put(TAG_STATUS, status);
                            // adding HashList to ArrayList
                            if(area.equals("A")){

                                    productsList.add(map);


                            }



                    } else {
                        // no products found
                        // Launch Add New product Activity
                        Intent i = new Intent(getApplicationContext(),PhotosActivity.class);// Closing all previous activities
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }

            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all products
                pDialog.dismiss();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        /**
                         * Updating parsed JSON data into ListView
                         * */

                        ListAdapter adapter = new SimpleAdapter(
                                PhotosActivity.this, productsList,R.layout.list_item, new String[] { TAG_PID,TAG_NAME},
                                new int[] { R.id.pid, R.id.name });
                        // updating listview
                        setListAdapter(adapter);
                    }
                });

            }

        }
    }

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
    <TextView
        android:id="@+id/pid"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />


    <!-- Name Label -->
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="20dip"
        android:paddingLeft="6dip"
        android:textSize="25dip"
        android:textStyle="bold"
        android:layout_weight="0.5"
         />

    <ImageView
        android:id="@+id/status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="0.5"/>
</LinearLayout>

使用堆栈跟踪记录:

07-26 05:50:49.379: D/dalvikvm(3118): GC_FOR_ALLOC freed 41K, 7% free 2614K/2804K, paused 33ms, total 37ms
07-26 05:50:49.464: D/AndroidRuntime(3118): Shutting down VM
07-26 05:50:49.464: W/dalvikvm(3118): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-26 05:50:49.480: E/AndroidRuntime(3118): FATAL EXCEPTION: main
07-26 05:50:49.480: E/AndroidRuntime(3118): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tabhost/com.example.tabhost.AndroidTabLayoutActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tabhost/com.example.tabhost.PhotosActivity}: java.lang.NullPointerException
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.os.Looper.loop(Looper.java:137)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at java.lang.reflect.Method.invokeNative(Native Method)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at java.lang.reflect.Method.invoke(Method.java:511)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at dalvik.system.NativeStart.main(Native Method)
07-26 05:50:49.480: E/AndroidRuntime(3118): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tabhost/com.example.tabhost.PhotosActivity}: java.lang.NullPointerException
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:2023)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.widget.TabHost.setCurrentTab(TabHost.java:413)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.widget.TabHost.addTab(TabHost.java:240)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at com.example.tabhost.AndroidTabLayoutActivity.onCreate(AndroidTabLayoutActivity.java:40)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.Activity.performCreate(Activity.java:5104)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-26 05:50:49.480: E/AndroidRuntime(3118):     ... 11 more
07-26 05:50:49.480: E/AndroidRuntime(3118): Caused by: java.lang.NullPointerException
07-26 05:50:49.480: E/AndroidRuntime(3118):     at com.example.tabhost.PhotosActivity.onCreate(PhotosActivity.java:54)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.Activity.performCreate(Activity.java:5104)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-26 05:50:49.480: E/AndroidRuntime(3118):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-26 05:50:49.480: E/AndroidRuntime(3118):     ... 21 more
07-26 05:50:49.722: D/dalvikvm(3118): GC_CONCURRENT freed 174K, 11% free 2860K/3180K, paused 128ms+41ms, total 246ms

列表显示

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">


    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

您需要像这样修改Line

IV_status.setImageResource(R.drawable.red)

对此

IV_status.setImageDrawable(getResources().getDrawable(R.drawable.red));

现在运行您的代码,它将起作用

应用程序崩溃的原因是它没有获取资源,因此您需要如上所述对它进行资源跟踪

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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