我想创建一个e dialog / alertDialog,其中显示了谷歌地图。我创建了一个对话框,并在有地图视图但是应用程序崩溃的情况下给布局充气,并给我以下错误:
06-15 10:56:32.436: E/AndroidRuntime(1716): FATAL EXCEPTION: main
06-15 10:56:32.436: E/AndroidRuntime(1716): Process: it.sii.android.jobaroundu, PID: 1716
06-15 10:56:32.436: E/AndroidRuntime(1716): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@52d5318c is not valid; is your activity running?
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.view.ViewRootImpl.setView(ViewRootImpl.java:536)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.app.Dialog.show(Dialog.java:286)
06-15 10:56:32.436: E/AndroidRuntime(1716): at it.sii.android.jobaroundu.PaginaRisultati$MyExpandableListAdapter$2.onClick(PaginaRisultati.java:300)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.view.View.performClick(View.java:4438)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.view.View$PerformClick.run(View.java:18422)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.os.Handler.handleCallback(Handler.java:733)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.os.Handler.dispatchMessage(Handler.java:95)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.os.Looper.loop(Looper.java:136)
06-15 10:56:32.436: E/AndroidRuntime(1716): at android.app.ActivityThread.main(ActivityThread.java:5017)
06-15 10:56:32.436: E/AndroidRuntime(1716): at java.lang.reflect.Method.invokeNative(Native Method)
06-15 10:56:32.436: E/AndroidRuntime(1716): at java.lang.reflect.Method.invoke(Method.java:515)
06-15 10:56:32.436: E/AndroidRuntime(1716): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-15 10:56:32.436: E/AndroidRuntime(1716): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-15 10:56:32.436: E/AndroidRuntime(1716): at dalvik.system.NativeStart.main(Native Method)
这是我的活动:
public class PaginaRisultati extends ExpandableListActivity {
//Initialize variables
private static final String STR_CHECKED = " has Checked!";
private static final String STR_UNCHECKED = " has unChecked!";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
private ArrayList<Parent> parents;
private String username;
private static final int RECOVERY_DIALOG_REQUEST = 1;
private String regione;
private String provincia;
private String[] tag;
private final static int MAP_MESSAGE_ID = 1;
private final static int PROGRESS_DIALOG_ID = 1;
private String posizione;
private String azienda;
final Context context = this;
MapView mMapView;
GoogleMap mMap;
Marker mark;
Bundle bundle;
double lat;
double lng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle=savedInstanceState;
//setContentView(R.layout.prova_risultati);
MyDBHelper dbHelper2 = new MyDBHelper(this,"JobAroundU_DB", null, 1);
final SQLiteDatabase db2;
Intent dati = getIntent();
String pkg = getPackageName();
regione = dati.getStringExtra(pkg+".Regione");
provincia = dati.getStringExtra(pkg+".Provincia");
tag = dati.getStringArrayExtra(pkg+".Tag");
username=dati.getStringExtra(pkg+".Username");
GetAnnunciThread gat= new GetAnnunciThread(regione, provincia, tag);
gat.run();
gat.start();
try {
gat.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//controllo se risultati esistono --> se non esistono stampo messaggio di errore
Resources res = this.getResources();
Drawable devider = res.getDrawable(R.drawable.transparent);
Drawable group_indicator = res.getDrawable(R.drawable.group_indicator);
// Set ExpandableListView values
getExpandableListView().setGroupIndicator(group_indicator);
getExpandableListView().setDivider(devider);
getExpandableListView().setChildDivider(devider);
getExpandableListView().setDividerHeight(15);
registerForContextMenu(getExpandableListView());
//Creating static data retrived from the result of the thread in arraylist
parents = gat.annuncitrovati;
if (parents.isEmpty()) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.immagine);
image.setImageDrawable(getResources().getDrawable(R.drawable.icon_25761));
TextView text = (TextView) layout.findViewById(R.id.ToastTV);
text.setText("La ricerca non ha prodotto risultati!!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
//richiamo activity precedente (la pagina di ricerca del lavoro)
}
db2=dbHelper2.getWritableDatabase();
//metto nella view e stampo a video
// Check for ExpandableListAdapter object
if (this.getExpandableListAdapter() == null) {
//Create ExpandableListAdapter Object
final MyExpandableListAdapter mAdapter = new MyExpandableListAdapter();
// Set Adapter to ExpandableList Adapter
this.setListAdapter(mAdapter);
}
else
{
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
}
}
private class MyExpandableListAdapter extends BaseExpandableListAdapter
{
private LayoutInflater inflater;
protected SQLiteOpenHelper dbHelper2 =new MyDBHelper(PaginaRisultati.this,"JobAroundU_DB", null, 1);
public MyExpandableListAdapter()
{
// Create Layout Inflator
inflater = LayoutInflater.from(PaginaRisultati.this);
}
// This Function used to inflate parent rows view
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parentView)
{
final Parent parent = parents.get(groupPosition);
// Inflate grouprow.xml file for parent rows
convertView = inflater.inflate(R.layout.grouprow, parentView, false);
// Get grouprow.xml file elements and set values
((TextView) convertView.findViewById(R.id.text1)).setText(parent.getPosizione());
((TextView) convertView.findViewById(R.id.TVData)).setText(parent.getAzienda());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.icon_21039);
//ImageView rightcheck=(ImageView)convertView.findViewById(R.id.rightcheck);
final ImageButton imgbtt = (ImageButton)convertView.findViewById(R.id.imageButton1);
imgbtt.setFocusable(false);
//metto stellina colorata se l'annuncio tra i preferiti e se lo metto a false la possibilità di inseririlo tra di essi, evitando cosi' doppioni
SQLiteDatabase db2=dbHelper2.getWritableDatabase();
String sqlPref = "SELECT idDBJobs FROM MyPreferences";
Cursor cursor = db2.rawQuery(sqlPref, null);
boolean prefAnn=false;
while (cursor.moveToNext()){
if(cursor.getString(0).equals(parent.getId())){
imgbtt.setImageResource(R.drawable.yellow_star);
prefAnn=true;
}
}
if(prefAnn==false){
imgbtt.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Log.i("preferred job announce", "aggiungi ai preferiti INIZIO ");
//preferiti e ricerche recenti sono nel DB SQLite dell'app
int num = Integer.parseInt(parent.getId());
String sqlMyPreference="INSERT INTO MyPreferences (Position, Firm, Description, idDBJobs ) VALUES ('"+parent.getPosizione()+"', '"+parent.getAzienda()+"', '"+parent.getChildren().get(0).getDescrizione()+"', "+num+");";
SQLiteDatabase db2=dbHelper2.getWritableDatabase();
db2.execSQL(sqlMyPreference);
db2.close();
Log.i("preferred job announce", "Aggiunto " +parent.getPosizione()+" nell'azienda "+parent.getAzienda()+" ai preferiti");
imgbtt.setImageResource(R.drawable.yellow_star);
}
});
}
return convertView;
}
// This Function used to inflate child rows view
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parentView)
{
final Parent parent = parents.get(groupPosition);
final Child child = parent.getChildren().get(childPosition);
// Inflate childrow.xml file for child rows
convertView = inflater.inflate(R.layout.childrow, parentView, false);
// Get childrow.xml file elements and set values
/***INDIRIZZO***/
((TextView) convertView.findViewById(R.id.TVTags)).setText(child.getIndirizzo());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.icon_14236);
Button b0 = (Button) convertView.findViewById(R.id.button1);
if(child.getIndirizzo().equals("Indirizzo NON presente")){
b0.setVisibility(View.INVISIBLE);
}
b0.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
//recupero indirizzo
String indirizzodaconvertire= ""+child.getIndirizzo();
azienda=""+parent.getAzienda();
posizione = ""+parent.getPosizione();
LayoutInflater inflater = getLayoutInflater();
//final View view =inflater.inflate(R.layout.main_mapview, null);
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.main_mapview);
mMapView = (MapView) dialog.findViewById(R.id.mymapview);
mMapView.onCreate(bundle);
MapsInitializer.initialize(context);
if (mMap == null) {
mMap = mMapView.getMap();
if (mMap != null) {
}
}
TextView tv= (TextView) dialog.findViewById(R.id.addressName);
tv.setText(indirizzodaconvertire);
searchPlace(indirizzodaconvertire);
dialog.setTitle("MAPPA!!!");
dialog.show();
//}
// });
/* Intent i = new Intent(PaginaRisultati.this, SeeAddress.class);
i.putExtra(getPackageName()+".Address", indirizzodaconvertire);
i.putExtra(getPackageName()+".Azienda",azienda);
i.putExtra(getPackageName()+".Posizione", posizione);
i.putExtra(getPackageName()+".Regione", regione);
i.putExtra(getPackageName()+".Provincia", provincia);
i.putExtra(getPackageName()+".Tag", tag);
i.putExtra(getPackageName()+".Username", username);
startActivity(i);*/
//replaceContentView("aa", i);
}
});
/***LUOGO LAVORO ****/
((TextView) convertView.findViewById(R.id.TVLoc_prov)).setText(child.getLuogoLavoro());
/***DESCRIZIONE ****/
((TextView) convertView.findViewById(R.id.TVLoc_regione)).setText(child.getDescrizione());
ImageView image2=(ImageView)convertView.findViewById(R.id.ImageLoc);
image2.setImageResource(R.drawable.icon_16301);
/***STIPENDIO ****/
((TextView) convertView.findViewById(R.id.TWStipendio)).setText(child.getStipendio());
ImageView image3=(ImageView)convertView.findViewById(R.id.ImageStipendio);
image3.setImageResource(R.drawable.icon_21213);
/***CANDIDATURA CELLULARE ****/
((TextView) convertView.findViewById(R.id.TWCandCell)).setText(child.getCandidaturaCellulare());
ImageView image4=(ImageView)convertView.findViewById(R.id.ImageCandCell);
image4.setImageResource(R.drawable.icon_14583);
/**** EMAIL ****/
TextView tv= (TextView) convertView.findViewById(R.id.TWMail);
tv.setText(child.getEmail());
ImageView image5=(ImageView)convertView.findViewById(R.id.ImageMail);
image5.setImageResource(R.drawable.icon_98);
Linkify.addLinks(tv, Linkify.EMAIL_ADDRESSES);
/*** BOTTONE YOUTUBE ***/
Button b1 = (Button) convertView.findViewById(R.id.Button01);
b1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if(child.getYT().equals("Video non presente")){
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.immagine);
image.setImageDrawable(getResources().getDrawable(R.drawable.youtube_notfind));
TextView text = (TextView) layout.findViewById(R.id.ToastTV);
text.setText("Video non presente!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}else{
//Intent i = new Intent(PaginaRisultati.this, YTActivity.class);
Intent i = new Intent(PaginaRisultati.this, YouTubeDialogActivity.class);
i.putExtra(getPackageName()+".YTV", child.getYT());
i.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
startActivity(i);
}
}
});
/***BOTTONE visibile solo se possible inviare candidatura via cell****/
Button b = (Button) convertView.findViewById(R.id.candidati);
if(child.getCandidaturaCellulare().equals("Candidatura via cellulare possibile")==false){
//nascondo bottone se non e' possibile inviare candidatura
b.setVisibility(View.INVISIBLE);
}
//CODICE PER INVIARE LA MAIL --> apre nuova activity con dati del lavoro--> email destinatario gia' inserita, allegato da scegliere e messaggio da editare
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
PersonalDataThread t3 = new PersonalDataThread(username);
t3.run();
t3.start();
try {
t3.join();
} catch (InterruptedException e) {
Log.e("ERROR -PERSONALDATA", ""+e.toString());
}
Intent ii= new Intent (PaginaRisultati.this, MailActivity.class);
ii.putExtra(getPackageName()+".EmailReceiver", child.getEmail());
ii.putExtra(getPackageName()+".Posizione", parent.getPosizione());
ii.putExtra(getPackageName()+".NomeUser", t3.nomeDB);
ii.putExtra(getPackageName()+".CognomeUser", t3.cognomeDB);
ii.putExtra(getPackageName()+".EmailSender", t3.mailDB);
ii.putExtra(getPackageName()+".Azienda", parent.getAzienda());
startActivity(ii);
}
});
return convertView;
}
@Override
public Object getChild(int groupPosition, int childPosition)
{
//Log.i("Childs", groupPosition+"= getChild =="+childPosition);
return parents.get(groupPosition).getChildren().get(childPosition);
}
//Call when child row clicked
@Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
}
return childPosition;
}
@Override
public int getChildrenCount(int groupPosition)
{
int size=0;
if(parents.get(groupPosition).getChildren()!=null)
size = parents.get(groupPosition).getChildren().size();
return size;
}
@Override
public Object getGroup(int groupPosition)
{
Log.i("Parent", groupPosition+"= getGroup ");
return parents.get(groupPosition);
}
@Override
public int getGroupCount()
{
return parents.size();
}
//Call when parent row clicked
@Override
public long getGroupId(int groupPosition)
{
ParentClickStatus=groupPosition;
if(ParentClickStatus==0)
ParentClickStatus=-1;
return groupPosition;
}
@Override
public void notifyDataSetChanged()
{
// Refresh List rows
super.notifyDataSetChanged();
}
@Override
public boolean isEmpty()
{
return ((parents == null) || parents.isEmpty());
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
/******************* Checkbox Checked Change Listener ********************/
private final class CheckUpdateListener implements OnCheckedChangeListener
{
private final Parent parent;
private CheckUpdateListener(Parent parent)
{
this.parent = parent;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Log.i("onCheckedChanged", "isChecked: "+isChecked);
parent.setChecked(isChecked);
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
final Boolean checked = parent.isChecked();
}
}
/***********************************************************************/
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
}
public void searchPlace(String inputName) {
final String s = inputName;
Thread searchThread = new Thread("SerachThread") {
@Override
public void run() {
Message message = mapHandler.obtainMessage();
String addressToSearch = s;
addressToSearch = addressToSearch.replace(" ", "%20");
JSONObject addressInfo = getAddressInfo(addressToSearch);
try
{
if (addressInfo != null && addressInfo.getString("status").equals("OK")) {
message.obj = addressInfo;
mapHandler.sendMessage(message);
}
else
mapHandler.sendEmptyMessage(MAP_MESSAGE_ID);
}
catch(JSONException e){
mapHandler.sendEmptyMessage(MAP_MESSAGE_ID);
}
//dismissDialog(PROGRESS_DIALOG_ID);
}
};
//showDialog(PROGRESS_DIALOG_ID);
//searchThread.run();
searchThread.start();
while(searchThread.isAlive()){
}
}
private final Handler mapHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg!=null && msg.obj!=null){
JSONObject addressInfo = (JSONObject)msg.obj;
try{
lng = ((JSONArray)addressInfo.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
lat = ((JSONArray)addressInfo.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
MarkerOptions mo= new MarkerOptions();
mo.position(new LatLng(lat,lng))
.title(posizione)
.snippet(azienda)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat,lng), 16.0f));
mark = mMap.addMarker(mo);
//onMarkerClick(mark);
mMap.setOnMarkerClickListener(new OnMarkerClickListener(){
@Override
public boolean onMarkerClick(final Marker marker){
// This causes the marker to bounce into position when it is clicked.
if (marker.equals(mark)) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(new LatLng(lat,lng));
startPoint.offset(0, -100);
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 2000;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng1 = t * lng + (1 - t) * startLatLng.longitude;
double lat1 = t * lat + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat1, lng1));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 10);
}
}
});
}
// We return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
});
}
catch(JSONException e){
Toast.makeText(context, "Found nothing. Retry!",
Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(context, "Found nothing. Retry!",
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG_ID:
ProgressDialog progressDialog = new ProgressDialog(this,
ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setTitle("GeocodingTest");
progressDialog.setMessage("Searching...");
return progressDialog;
default:
return null;
}
}
public static JSONObject getAddressInfo(String sAddress) {
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address=" + sAddress + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
Log.d("Google Geocoding Response", stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
//CARICO LA NUOVA ACTIVITY ALL'INTERNO DEL CORPO DEL TAB
public void replaceContentView(String id, Intent newIntent) {
this.getApplicationContext()
View view =this.getApplication().getLocalActivityManager().startActivity("ff",
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
}
*/
}
这是布局膨胀
<?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="fill_parent"
android:orientation="vertical" android:id="@+id/mainLayout">
<LinearLayout android:layout_height="wrap_content"
android:id="@+id/buttonLayout" android:layout_width="fill_parent">
<TextView android:id="@+id/addressName"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:layout_weight="1" android:inputType="text"></TextView>
<!-- <Button android:layout_height="wrap_content" android:id="@+id/searchButton"
android:text="Search" android:layout_width="fill_parent"
android:onClick="searchPlace"
android:layout_weight="3"></Button> -->
</LinearLayout>
<com.google.android.gms.maps.MapView
android:id="@+id/mymapview"
android:layout_width="500dp"
android:layout_height="500dp"
xmlns:map="http://schemas.android.com/apk/res-auto"
map:cameraTargetLat="45.070139"
map:cameraTargetLng="7.6700892"
map:cameraZoom="5"
map:mapType="normal"
map:uiRotateGestures="false"
map:uiScrollGestures="true"
map:uiTiltGestures="false"
map:uiZoomControls="true"
map:uiZoomGestures="false"
>
</com.google.android.gms.maps.MapView>
</LinearLayout>
错误在哪里?拜托,你能帮助我并纠正我的代码吗?
由于
中号
答案 0 :(得分:1)
android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@52d5318c is not valid; is your activity running?
你需要
Context context; //declare it as an instance variable
然后在onCreate
context = this; // initialize in onCreate. this refers to activity context
一旦创建了活动,就可以使用活动上下文。
对于地图,您可以使用DialogFragment