Android - 在继续下一个活动时强制关闭

时间:2015-02-02 20:32:23

标签: android

来自MySQL数据库的数据正确加载。但是,每当我单击按钮以继续下一个活动时,应用程序将关闭。

它说错误在这一行:

tvRName.setText(restaurantList.get(0).get(TAG_R_NAME));

一直在努力调试,但我没有运气。你能来看看吗?非常感谢你。


logcat的

02-03 04:23:01.628: E/AndroidRuntime(1601): FATAL EXCEPTION: main
02-03 04:23:01.628: E/AndroidRuntime(1601): java.lang.NullPointerException
02-03 04:23:01.628: E/AndroidRuntime(1601):     at com.capstone.restosnapp.RestoActivity$LoadAllRestaurant.onPostExecute(RestoActivity.java:167)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at com.capstone.restosnapp.RestoActivity$LoadAllRestaurant.onPostExecute(RestoActivity.java:1)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at android.os.AsyncTask.finish(AsyncTask.java:602)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at android.os.Looper.loop(Looper.java:137)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at android.app.ActivityThread.main(ActivityThread.java:4340)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at java.lang.reflect.Method.invokeNative(Native Method)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at java.lang.reflect.Method.invoke(Method.java:511)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-03 04:23:01.628: E/AndroidRuntime(1601):     at dalvik.system.NativeStart.main(Native Method)

RestoActivity.java

public class RestoActivity extends Activity {

Button btnViewMenu;

int loader;
String image_url;
ImageView image;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> restaurantList;

// url to get all restaurant list
private static String url_all_appetizer = "http://10.0.2.2/restosnapp_android/get_all_restaurant.php";

// private static String url_all_appetizer =
// "http://webitprojects.com/restaurant/android/get_all_restaurant.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_RESTAURANT = "restaurant";
private static final String TAG_RID = "rid";
private static final String TAG_R_NAME = "r_name";
private static final String TAG_R_DESC = "r_desc";
private static final String TAG_R_ADDR = "r_addr";
private static final String TAG_R_CONTACT = "r_contact";
private static final String TAG_R_EMAIL = "r_email";
private static final String TAG_R_WEBSITE = "r_website";
private static final String TAG_R_LOGO = "r_logo";

// restaurant JSONArray
JSONArray restaurant = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_resto);

    // Imageview to show
    image = (ImageView) findViewById(R.id.imgResto);

    // Hashmap for ListView
    restaurantList = new ArrayList<HashMap<String, String>>();

    // Loading restaurant in Background Thread
    new LoadAllRestaurant().execute();

    btnViewMenu = (Button) findViewById(R.id.btnViewMenu);
    btnViewMenu.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showMenuActivity();
        }

    });

}

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

    /**
     * getting All restaurant details from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_appetizer, "GET",
                params);

        // Check your log cat for JSON response
        Log.d("Restaurant: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // restaurant found
                // Getting Array of restaurant
                restaurant = json.getJSONArray(TAG_RESTAURANT);

                // looping through restaurant
                for (int i = 0; i < restaurant.length(); i++) {
                    JSONObject c = restaurant.getJSONObject(i);

                    // Storing each json item in variable
                    String r_id = c.getString(TAG_RID);
                    String r_name = c.getString(TAG_R_NAME);
                    String r_desc = c.getString(TAG_R_DESC);
                    String r_addr = c.getString(TAG_R_ADDR);
                    String r_contact = c.getString(TAG_R_CONTACT);
                    String r_email = c.getString(TAG_R_EMAIL);
                    String r_website = c.getString(TAG_R_WEBSITE);
                    String r_logo = c.getString(TAG_R_LOGO);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_RID, r_id);
                    map.put(TAG_R_NAME, r_name);
                    map.put(TAG_R_DESC, r_desc);
                    map.put(TAG_R_ADDR, r_addr);
                    map.put(TAG_R_CONTACT, r_contact);
                    map.put(TAG_R_EMAIL, r_email);
                    map.put(TAG_R_WEBSITE, r_website);
                    map.put(TAG_R_LOGO, r_logo);

                    // adding HashList to ArrayList
                    restaurantList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        // ImageLoader class instance
        Lazy_ImageLoader imgLoader = new Lazy_ImageLoader(
                getApplicationContext());

        image_url = restaurantList.get(0).get(TAG_R_LOGO);
        imgLoader.DisplayImage(image_url, image);

        TextView tvRName = (TextView) findViewById(R.id.tvResto);
        TextView tvRAddr = (TextView) findViewById(R.id.tvAddr);
        TextView tvRDesc = (TextView) findViewById(R.id.tvDesc);
        TextView tvRContact = (TextView) findViewById(R.id.tvPhone);
        TextView tvREmail = (TextView) findViewById(R.id.tvEmail);
        TextView tvRWebsite = (TextView) findViewById(R.id.tvWeb);

        tvRName.setText(restaurantList.get(0).get(TAG_R_NAME));
        tvRDesc.setText(restaurantList.get(0).get(TAG_R_DESC));
        tvRAddr.setText(restaurantList.get(0).get(TAG_R_ADDR));
        tvRContact.setText(restaurantList.get(0).get(TAG_R_CONTACT));
        tvREmail.setText(restaurantList.get(0).get(TAG_R_EMAIL));
        tvRWebsite.setText(restaurantList.get(0).get(TAG_R_WEBSITE));

        super.onPostExecute(result);
    }

}

private void showMenuActivity() {
    Intent i = new Intent(this, MenuListActivity.class);
    startActivity(i);
}}

编辑:

JSON

02-03 18:41:14.507: D/Restaurant:(3242): {"restaurant":[{"r_contact":"(082) 301-6065 \/ 0917-309-6008","r_addr":"4L TP 16 The Peak, 4th Level Gaisano Mall of Davao, Davao City","r_logo":"http:\/\/webitprojects.com\/restaurant\/images\/logo\/2_zabadani.jpg","r_website":"http:\/\/zabadanicafe.com\/","rid":"2","r_email":"zabadanicafe@hotmail.com","r_name":"Zabadani Cafe","r_desc":"Zabadani Cafe is a Halal Middle Eastern Restaurant serving authentic dishes fused with Filipino taste in a semi-fine dining set-up; served generously at affordable prices."}],"success":1}

restaurantList

02-03 18:41:39.127: I/System.out(3242): [{r_contact=(082) 301-6065 / 0917-309-6008, r_addr=4L TP 16 The Peak, 4th Level Gaisano Mall of Davao, Davao City, r_logo=http://webitprojects.com/restaurant/images/logo/2_zabadani.jpg, r_website=http://zabadanicafe.com/, rid=2, r_email=zabadanicafe@hotmail.com, r_name=Zabadani Cafe, r_desc=Zabadani Cafe is a Halal Middle Eastern Restaurant serving authentic dishes fused with Filipino taste in a semi-fine dining set-up; served generously at affordable prices.}]

编辑2:

当我将MenuListActivity.class更改为其他活动时,它不会强行关闭。现在我真的很困惑。可能有什么不对?

MenuListActivity.java

@SuppressLint("NewApi")
public class MenuListActivity extends RestoActivity {

Button btnViewAppetizer, btnViewMainCourse, btnViewDessert, btnViewDrinks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menulist);

    // SHOW APPETIZER MENU

    btnViewAppetizer = (Button) findViewById(R.id.btnViewAppetizer);
    btnViewAppetizer.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            showMenuAppetizer();
        }
    });

    btnViewAppetizer.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (v == btnViewAppetizer) {
                    btnViewAppetizer
                            .setBackgroundResource(R.drawable.btn_appetizer);
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (v == btnViewAppetizer) {
                    btnViewAppetizer
                            .setBackgroundResource(R.drawable.btn_appetizer2);
                }
            }
            return false;
        }
    });

    // SHOW MAIN COURSE MENU

    btnViewMainCourse = (Button) findViewById(R.id.btnViewMainCourse);
    btnViewMainCourse.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            showMenuMainCourse();
        }
    });

    btnViewMainCourse.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (v == btnViewMainCourse) {
                    btnViewMainCourse
                            .setBackgroundResource(R.drawable.btn_main_course);
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (v == btnViewMainCourse) {
                    btnViewMainCourse
                            .setBackgroundResource(R.drawable.btn_main_course2);
                }
            }
            return false;
        }
    });

    // SHOW DESSERT MENU

    btnViewDessert = (Button) findViewById(R.id.btnViewDessert);
    btnViewDessert.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            showMenuDessert();
        }
    });

    btnViewDessert.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (v == btnViewDessert) {
                    btnViewDessert
                            .setBackgroundResource(R.drawable.btn_desserts);
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (v == btnViewDessert) {
                    btnViewDessert
                            .setBackgroundResource(R.drawable.btn_desserts2);
                }
            }
            return false;
        }
    });

    // SHOW DRINKS MENU

    btnViewDrinks = (Button) findViewById(R.id.btnViewDrinks);
    btnViewDrinks.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            showMenuDrinks();
        }
    });

    btnViewDrinks.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (v == btnViewDrinks) {
                    btnViewDrinks
                            .setBackgroundResource(R.drawable.btn_drinks);
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (v == btnViewDrinks) {
                    btnViewDrinks
                            .setBackgroundResource(R.drawable.btn_drinks2);
                }
            }
            return false;
        }
    });

}

protected void showMenuAppetizer() {
    // TODO Auto-generated method stub
    Intent i = new Intent(this, Lazy_ListAppetizer.class);
    startActivity(i);
}

protected void showMenuMainCourse() {
    // TODO Auto-generated method stub
    Intent i = new Intent(this, Lazy_ListMainCourse.class);
    startActivity(i);
}

protected void showMenuDessert() {
    // TODO Auto-generated method stub
    Intent i = new Intent(this, Lazy_ListDessert.class);
    startActivity(i);
}

protected void showMenuDrinks() {
    // TODO Auto-generated method stub
    Intent i = new Intent(this, Lazy_ListDrinks.class);
    startActivity(i);
}}

4 个答案:

答案 0 :(得分:1)

<强>解答:

MenuListActivity.java上我应该public class MenuListActivity extends Activity而不是public class MenuListActivity extends RestoActivity

傻傻的我。很抱歉浪费你的时间:3

答案 1 :(得分:0)

您应该在onPostExecute中执行检查,以确保success不是0restuarantList不是null。如果restaurantList.get(0)不是success,则您不应该尝试致电1,因为这意味着restuarantListnull。这解释了您的NullPointerException

答案 2 :(得分:0)

tvRName.setText(restaurantList.get(0).get(TAG_R_NAME));

您在此处调用三个不同对象的方法,其中一个是null。使用调试器跳到此行并找出哪一个是null

  • tvRName;
  • restaurantList;
  • restaurantList.get(0);

答案 3 :(得分:0)

你确定吗? “它说错误就在这一行: tvRName.setText(restaurantList.get(0).get(TAG_R_NAME));

您的错误:com.capstone.restosnapp.Lazy_ImageLoader.DisplayImage(Lazy_ImageLoader.java:49)代码系数为imgLoader.DisplayImage(image_url, image);

imageLoader不为空 - (我没有使用Lazy_ImageLoader,但你确定初始化),你的字符串不能,你的图像也不能 所以问题可能是读/写权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />