我收到错误:不幸的是应用程序已停止
通过使用下面的代码,我试图通过单击餐厅按钮来调用 RestaurantActivity。
AndroidDashboardDesignActivity.java:
public class AndroidDashboardDesignActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard_layout);
/**
* Creating all buttons instances
* */
// Dashboard News feed button
Button btn_restaurant = (Button) findViewById(R.id.btn_news_feed);
// Dashboard Friends button
Button btn_friends = (Button) findViewById(R.id.btn_friends);
// Dashboard Messages button
Button btn_messages = (Button) findViewById(R.id.btn_messages);
// Dashboard Places button
Button btn_places = (Button) findViewById(R.id.btn_places);
// Dashboard Events button
Button btn_events = (Button) findViewById(R.id.btn_events);
// Dashboard Photos button
Button btn_photos = (Button) findViewById(R.id.btn_photos);
/**
* Handling all button click events
* */
// Listening to News Feed button click
btn_restaurant.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching Near Restaurant Screen
Intent i = new Intent(AndroidDashboardDesignActivity.this, com.androidhive.googleplacesandmaps.RestaurantActivity.class);
startActivity(i);
}
});
// Listening Friends button click
btn_friends.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(AndroidDashboardDesignActivity.this, com.androidhive.googleplacesandmaps.FriendsActivity.class);
startActivity(i);
}
});
// Listening Messages button click
btn_messages.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(AndroidDashboardDesignActivity.this, com.androidhive.googleplacesandmaps.MessagesActivity.class);
startActivity(i);
}
});
// Listening to Places button click
btn_places.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(AndroidDashboardDesignActivity.this, com.androidhive.googleplacesandmaps.PlacesActivity.class);
startActivity(i);
}
});
// Listening to Events button click
btn_events.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(AndroidDashboardDesignActivity.this, com.androidhive.googleplacesandmaps.EventsActivity.class);
startActivity(i);
}
});
// Listening to Photos button click
btn_photos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(AndroidDashboardDesignActivity.this, com.androidhive.googleplacesandmaps.PhotosActivity.class);
startActivity(i);
}
});
}
仪表板布局.java:
package com.androidhive.googleplacesandmaps;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Custom layout that arranges children in a grid-like manner,
optimizing for even horizontal and
* vertical whitespace.
*/
public class DashboardLayout extends ViewGroup {
private static final int UNEVEN_GRID_PENALTY_MULTIPLIER = 10;
private int mMaxChildWidth = 0;
private int mMaxChildHeight = 0;
public DashboardLayout(Context context) {
super(context, null);
}
public DashboardLayout(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public DashboardLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mMaxChildWidth = 0;
mMaxChildHeight = 0;
// Measure once to find the maximum child size.
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
mMaxChildWidth = Math.max(mMaxChildWidth, child.getMeasuredWidth());
mMaxChildHeight = Math.max(mMaxChildHeight, child.getMeasuredHeight());
}
// Measure again for each child to be exactly the same size.
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
mMaxChildWidth, MeasureSpec.EXACTLY);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
mMaxChildHeight, MeasureSpec.EXACTLY);
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
setMeasuredDimension(
resolveSize(mMaxChildWidth, widthMeasureSpec),
resolveSize(mMaxChildHeight, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
final int count = getChildCount();
// Calculate the number of visible children.
int visibleCount = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
++visibleCount;
}
if (visibleCount == 0) {
return;
}
// Calculate what number of rows and columns will optimize for even horizontal and
// vertical whitespace between items. Start with a 1 x N grid, then try 2 x N, and so on.
int bestSpaceDifference = Integer.MAX_VALUE;
int spaceDifference;
// Horizontal and vertical space between items
int hSpace = 0;
int vSpace = 0;
int cols = 1;
int rows;
while (true) {
rows = (visibleCount - 1) / cols + 1;
hSpace = ((width - mMaxChildWidth * cols) / (cols + 1));
vSpace = ((height - mMaxChildHeight * rows) / (rows + 1));
spaceDifference = Math.abs(vSpace - hSpace);
if (rows * cols != visibleCount) {
spaceDifference *= UNEVEN_GRID_PENALTY_MULTIPLIER;
}
if (spaceDifference < bestSpaceDifference) {
// Found a better whitespace squareness/ratio
bestSpaceDifference = spaceDifference;
// If we found a better whitespace squareness and there's only 1 row, this is
// the best we can do.
if (rows == 1) {
break;
}
} else {
// This is a worse whitespace ratio, use the previous value of cols and exit.
--cols;
rows = (visibleCount - 1) / cols + 1;
hSpace = ((width - mMaxChildWidth * cols) / (cols + 1));
vSpace = ((height - mMaxChildHeight * rows) / (rows + 1));
break;
}
++cols;
}
// Lay out children based on calculated best-fit number of rows and cols.
// If we chose a layout that has negative horizontal or vertical space, force it to zero.
hSpace = Math.max(0, hSpace);
vSpace = Math.max(0, vSpace);
// Re-use width/height variables to be child width/height.
width = (width - hSpace * (cols + 1)) / cols;
height = (height - vSpace * (rows + 1)) / rows;
int left, top;
int col, row;
int visibleIndex = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
row = visibleIndex / cols;
col = visibleIndex % cols;
left = hSpace * (col + 1) + width * col;
top = vSpace * (row + 1) + height * row;
child.layout(left, top,
(hSpace == 0 && col == cols - 1) ? r : (left + width),
(vSpace == 0 && row == rows - 1) ? b : (top + height));
++visibleIndex;
}
}
}
RestaurantActivity.java:
public class RestaurantActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Places List
PlacesList nearPlaces;
// GPS Location
GPSTracker gps;
// Button
Button btnShowOnMap;
// Progress dialog
ProgressDialog pDialog;
// Places Listview
ListView lv;
// ListItems data
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurants);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alert.showAlertDialog(RestaurantActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// creating GPS Class object
gps = new GPSTracker(this);
// check if GPS location can get
if (gps.canGetLocation()) {
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
} else {
// Can't get user's current location
alert.showAlertDialog(RestaurantActivity.this, "GPS Status",
"Couldn't get location information. Please enable GPS",
false);
// stop executing code by return
return;
}
// Getting listview
lv = (ListView) findViewById(R.id.list);
// button show on map
btnShowOnMap = (Button) findViewById(R.id.btn_show_map);
// calling background Async task to load Google Places
// After getting places from Google all the data is shown in listview
new LoadPlaces().execute();
/** Button click event for shown on map */
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
/**
* ListItem click event
* On selecting a listitem SinglePlaceActivity is launched
* */
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SinglePlaceActivity.class);
// Sending place refrence id to single place activity
// place refrence id used to get "Place full details"
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadPlaces extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RestaurantActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"
// If you want all types places make it as null
// Check list of types supported by google
//
String types = "cafe|restaurant"; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
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 Places into LISTVIEW
* */
// Get json response status
String status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter
ListAdapter adapter = new SimpleAdapter(RestaurantActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
alert.showAlertDialog(RestaurantActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(RestaurantActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(RestaurantActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(RestaurantActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(RestaurantActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(RestaurantActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
AndroidManifest.xml:
<activity
android:name="com.androidhive.googleplacesandmaps.AndroidDashboardDesignActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- MainActivity -->
<activity android:name="com.androidhive.googleplacesandmaps.RestaurantActivity" android:label="Nearest Places">
</activity>
<!-- SinglePlaceActivity -->
<activity android:name="com.androidhive.googleplacesandmaps.SinglePlaceActivity" android:label="Place Details">
</activity>
<!-- PlacesMapActivity -->
<activity android:name="com.androidhive.googleplacesandmaps.PlacesMapActivity" android:label="Near Places Map View">
</activity>
Logcat 说:
01-31 17:42:17.352: E/AndroidRuntime(981): FATAL EXCEPTION: main
01-31 17:42:17.352: E/AndroidRuntime(981): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.googleplacesandmaps/com.androidhive.googleplacesandmaps.AndroidDashboardDesignActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class com.androidhive.dashboard.DashboardLayout
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.os.Looper.loop(Looper.java:137)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-31 17:42:17.352: E/AndroidRuntime(981): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 17:42:17.352: E/AndroidRuntime(981): at java.lang.reflect.Method.invoke(Method.java:511)
01-31 17:42:17.352: E/AndroidRuntime(981): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-31 17:42:17.352: E/AndroidRuntime(981): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-31 17:42:17.352: E/AndroidRuntime(981): at dalvik.system.NativeStart.main(Native Method)
01-31 17:42:17.352: E/AndroidRuntime(981): Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class com.androidhive.dashboard.DashboardLayout
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:698)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:807)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
01-31 17:42:17.352: E/AndroidRuntime(981): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.Activity.setContentView(Activity.java:1881)
01-31 17:42:17.352: E/AndroidRuntime(981): at com.androidhive.googleplacesandmaps.AndroidDashboardDesignActivity.onCreate(AndroidDashboardDesignActivity.java:15)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.Activity.performCreate(Activity.java:5104)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-31 17:42:17.352: E/AndroidRuntime(981): ... 11 more
01-31 17:42:17.352: E/AndroidRuntime(981): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.androidhive.dashboard.DashboardLayout" on path: /system/framework/com.google.android.maps.jar:/data/app/com.androidhive.googleplacesandmaps-1.apk
01-31 17:42:17.352: E/AndroidRuntime(981): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
01-31 17:42:17.352: E/AndroidRuntime(981): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
01-31 17:42:17.352: E/AndroidRuntime(981): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.createView(LayoutInflater.java:552)
01-31 17:42:17.352: E/AndroidRuntime(981): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
01-31 17:42:17.352: E/AndroidRuntime(981): ... 22 more