0

Я разрабатываю список в комплекте с базой данных. При нажатии элемента из ListView, приложение закрывается и отображает эту ошибку:Ошибка при нажатии элемента в виде списка

05-25 18:47:59.506 13297-13297/? I/art﹕ Not late-enabling -Xcheck:jni (already on) 
05-25 18:47:59.664 13297-13297/? E/MediaPlayer﹕ Should have subtitle controller already set 
05-25 18:47:59.737 13297-13313/? D/OpenGLRenderer﹕ Render dirty regions requested: true 
05-25 18:47:59.739 13297-13297/? D/﹕ HostConnection::get() New Host Connection established 0xa6caeab0, tid 13297 
05-25 18:47:59.773 13297-13297/? D/Atlas﹕ Validating map... 
05-25 18:47:59.798 13297-13297/? E/MediaPlayer﹕ Should have subtitle controller already set 
05-25 18:47:59.833 13297-13313/? D/﹕ HostConnection::get() New Host Connection established 0xa6cca100, tid 13313 
05-25 18:47:59.876 13297-13313/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4 
05-25 18:47:59.892 13297-13313/? D/OpenGLRenderer﹕ Enabling debug mode 0 
05-25 18:47:59.903 13297-13313/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented 
05-25 18:47:59.903 13297-13313/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6ce2080, error=EGL_SUCCESS 
05-25 18:48:00.192 13297-13313/com.example.mislugares W/EGL_emulation﹕ eglSurfaceAttrib not implemented 
05-25 18:48:00.193 13297-13313/com.example.mislugares W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6ce20a0, error=EGL_SUCCESS 
05-25 18:48:00.956 13297-13297/com.example.mislugares I/Choreographer﹕ Skipped 44 frames! The application may be doing too much work on its main thread. 
05-25 18:48:01.706 13297-13313/com.example.mislugares W/EGL_emulation﹕ eglSurfaceAttrib not implemented 
05-25 18:48:01.706 13297-13313/com.example.mislugares W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6ce20a0, error=EGL_SUCCESS 
05-25 18:48:03.715 13297-13313/com.example.mislugares W/EGL_emulation﹕ eglSurfaceAttrib not implemented 
05-25 18:48:03.715 13297-13313/com.example.mislugares W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6ce20a0, error=EGL_SUCCESS 
05-25 18:48:14.024 13297-13297/com.example.mislugares D/AndroidRuntime﹕ Shutting down VM 
05-25 18:48:14.025 13297-13297/com.example.mislugares E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: com.example.mislugares, PID: 13297 
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mislugares/com.example.mislugares.VistaLugar}: java.lang.ClassCastException: com.example.mislugares.GeoPunto cannot be cast to com.example.mislugares.GeoPuntoAlt 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
      at android.app.ActivityThread.access$800(ActivityThread.java:144) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:135) 
      at android.app.ActivityThread.main(ActivityThread.java:5221) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
    Caused by: java.lang.ClassCastException: com.example.mislugares.GeoPunto cannot be cast to com.example.mislugares.GeoPuntoAlt 
      at com.example.mislugares.Lugares.elemento(Lugares.java:32) 
      at com.example.mislugares.VistaLugar.actualizarVistas(VistaLugar.java:98) 
      at com.example.mislugares.VistaLugar.onCreate(VistaLugar.java:46) 
      at android.app.Activity.performCreate(Activity.java:5937) 
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
            at android.app.ActivityThread.access$800(ActivityThread.java:144) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
            at android.os.Handler.dispatchMessage(Handler.java:102) 
            at android.os.Looper.loop(Looper.java:135) 
            at android.app.ActivityThread.main(ActivityThread.java:5221) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:372) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
05-25 18:48:14.048 13297-13309/com.example.mislugares W/art﹕ Suspending all threads took: 8.680ms 
05-25 18:48:14.068 13297-13309/com.example.mislugares I/art﹕ Background partial concurrent mark sweep GC freed 597(29KB) AllocSpace objects, 0(0B) LOS objects, 21% free, 14MB/18MB, paused 7.947ms total 12.964ms 

Ошибка относится к линии:

lugar.setPosicion((GeoPuntoAlt) new GeoPunto(cursor.getDouble(3), cursor.getDouble(4))); 

Эта строка находится в пределах класса Lugares.class

public class Lugares { 

    private static LugaresBD lugaresBD; 


    protected static List<Lugar> vectorLugares = ejemploLugares(); 

    public Lugares() { 
     vectorLugares = ejemploLugares(); 
    } 

    public static Lugar elemento(int id) { 
     Lugar lugar = null; 
     SQLiteDatabase bd = lugaresBD.getReadableDatabase(); 
     Cursor cursor = bd.rawQuery("SELECT * FROM lugares WHERE _id = " + id, null); 
     if (cursor.moveToNext()){ 
      lugar = new Lugar(); 
      lugar.setNombre(cursor.getString(1)); 
      lugar.setDireccion(cursor.getString(2)); 
      lugar.setPosicion((GeoPuntoAlt) new GeoPunto(cursor.getDouble(3), cursor.getDouble(4))); 
      lugar.setTipo(TipoLugar.values()[cursor.getInt(5)]); 
      lugar.setFoto(cursor.getString(6)); 
      lugar.setTelefono(cursor.getInt(7)); 
      lugar.setUrl(cursor.getString(8)); 
      lugar.setComentario(cursor.getString(9)); 
      lugar.setFecha(cursor.getLong(10)); 
      lugar.setValoracion(cursor.getFloat(11)); 
     } 
     cursor.close(); 
     bd.close(); 
     return lugar; 
    } 

    static void anyade(Lugar lugar){ 
     vectorLugares.add(lugar); 
    } 

    final static String TAG = "MisLugares"; 
    protected static GeoPunto posicionActual = new GeoPunto(0,0); 

    static int nuevo(){ 
     Lugar lugar = new Lugar("1Escuela Politécnica Superior de Gandía", 
       "C/ Paranimf, 1 46730 Gandia (SPAIN)", -0.166093, 38.995656, 1500, 
       TipoLugar.EDUCACION,962849300, "http://www.epsg.upv.es", 
       "Uno de los mejores lugares para formarse.", 3); 
     vectorLugares.add(lugar); 
     return vectorLugares.size()-1; 
    } 

    static void borrar(int id){ 
     vectorLugares.remove(id); 
    } 

    public static int size() { 
     return vectorLugares.size(); 
    } 

    public static ArrayList<Lugar> ejemploLugares() { 
     ArrayList<Lugar> lugares = new ArrayList<Lugar>(); 
     lugares.add(new Lugar("Escuela Politécnica Superior de Gandía", 
       "C/ Paranimf, 1 46730 Gandia (SPAIN)", -0.166093, 38.995656, 800, 
       TipoLugar.EDUCACION,962849300, "http://www.epsg.upv.es", 
       "Uno de los mejores lugares para formarse.", 3)); 

     lugares.add(new Lugar("Al de siempre", 
       "P.Industrial Junto Molí Nou - 46722, Benifla (Valencia)", 
       -0.190642, 38.925857, 150, TipoLugar.BAR, 636472405, "", 
       "No te pierdas el arroz en calabaza.", 3)); 

     lugares.add(new Lugar("androidcurso.com", 
       "ciberespacio", 0.0, 0.0, 2000, TipoLugar.EDUCACION, 
       962849300, "http://androidcurso.com", 
       "Amplia tus conocimientos sobre Android.", 5)); 

     lugares.add(new Lugar("Barranco del Infierno", 
       "Vía Verde del río Serpis. Villalonga (Valencia)", 
       -0.295058, 38.867180, 000, TipoLugar.NATURALEZA, 

       0, "http://sosegaos.blogspot.com.es/2009/02/lorcha-villalonga-via-verde-del-rio.html", 
       "Espectacular ruta para bici o andar", 4)); 

     lugares.add(new Lugar("La Vital", 
       "Avda. de La Vital, 0 46701 Gandía (Valencia)", 
       -0.1720092, 38.9705949, 400, TipoLugar.COMPRAS, 
       962881070, "http://www.lavital.es/", 
       "El típico centro comercial", 2)); 

     return lugares; 

    } 

    static List listaNombres(){ 
     ArrayList resultado = new ArrayList(); 
     for (Lugar lugar:vectorLugares){ 
      resultado.add(lugar.getNombre()); 
     } 
     return resultado; 
    } 

    public static void indicializaBD(Context contexto){ 
     lugaresBD = new LugaresBD(contexto); 
    } 

    public static Cursor listado() { 
     SQLiteDatabase bd = lugaresBD.getReadableDatabase(); 
     return bd.rawQuery("SELECT * FROM lugares", null); 
    } 

} 

Есть еще одна ошибка на линии:

lugar = Lugares.elemento((int) id); 

Эта линия в пределах класса VistaLugar.class

public class VistaLugar extends ActionBarActivity { 
    private long id; 
    private Lugar lugar; 

    private ImageView imageView; 
    final static int RESULTADO_EDITAR= 1; 
    final static int RESULTADO_GALERIA= 2; 
    final static int RESULTADO_FOTO= 3; 
    private Uri uriFoto; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.vista_lugar); 
     Bundle extras = getIntent().getExtras(); 
     id = extras.getLong("id", -1); 
     imageView = (ImageView) findViewById(R.id.foto); 
     actualizarVistas(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.vista_lugar, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch(item.getItemId()) { 
      case R.id.accion_compartir: 
       Intent intent = new Intent(Intent.ACTION_SEND); 
       intent.setType("text/plain"); 
       intent.putExtra(Intent.EXTRA_TEXT, 
         lugar.getNombre() + " - "+ lugar.getUrl()); 
       startActivity(intent); 
       return true; 
      case R.id.accion_llegar: 
       verMapa(null); 
       return true; 
      case R.id.accion_editar: 
       Intent i = new Intent(VistaLugar.this, EdicionLugar.class); 
       i.putExtra("id", id); 
       startActivityForResult(i, RESULTADO_EDITAR); 
       return true; 
      case R.id.accion_borrar: 
       //Lugares.borrar((int) id); 
       //finish(); 
       seVaaBorrar(null); 
       return true; 
      default: 
       return super.onOptionsItemSelected(item); 
     } 
    } 

    public void seVaaBorrar(View view){ 
     new AlertDialog.Builder(this) 
       .setTitle("Confirmación de borrado") 
       .setMessage("¿Seguro que desea borrar el lugar?") 
       .setPositiveButton("Borrar", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         Lugares.borrar((int) id); 
         finish(); 
        } 
       }) 
       .setNegativeButton("Cancelar", null) 
       .show(); 
    } 

    public void actualizarVistas(){ 
     lugar = Lugares.elemento((int) id); 
     TextView nombre = (TextView) findViewById(R.id.nombre); 
     nombre.setText(lugar.getNombre()); 
     ImageView logo_tipo = (ImageView) findViewById(R.id.logo_tipo); 
     logo_tipo.setImageResource(lugar.getTipo().getRecurso()); 
     TextView tipo = (TextView) findViewById(R.id.tipo); 
     tipo.setText(lugar.getTipo().getTexto()); 
     TextView direccion = (TextView) findViewById(R.id.direccion); 
     if (lugar.getDireccion() == ""){ 
      findViewById(R.id.direccion).setVisibility(View.GONE); 
      findViewById(R.id.logo_myplaces).setVisibility(View.GONE); 
     }else{ 
      direccion.setText(lugar.getDireccion()); 
     } 
     //direccion.setText(lugar.getDireccion()); 
     TextView telefono = (TextView) findViewById(R.id.telefono); 
     if (lugar.getTelefono() == 0) { 
      findViewById(R.id.telefono).setVisibility(View.GONE); 
      findViewById(R.id.logo_menucall).setVisibility(View.GONE); 
     } else { 
      telefono.setText(Integer.toString(lugar.getTelefono())); 
     } 
     //telefono.setText(Integer.toString(lugar.getTelefono())); 
     TextView url = (TextView) findViewById(R.id.url); 
     if (lugar.getUrl() == "") { 
      findViewById(R.id.url).setVisibility(View.GONE); 
      findViewById(R.id.logo_mapmode).setVisibility(View.GONE); 
     } else { 
      url.setText(lugar.getUrl()); 
     } 
     //url.setText(lugar.getUrl()); 
     TextView comentario = (TextView) findViewById(R.id.comentario); 
     if (lugar.getComentario() == "") { 
      findViewById(R.id.comentario).setVisibility(View.GONE); 
      findViewById(R.id.logo_infodetails).setVisibility(View.GONE); 
     } else { 
      comentario.setText(lugar.getComentario()); 
     } 
     //comentario.setText(lugar.getComentario()); 
     TextView fecha = (TextView) findViewById(R.id.fecha); 
     fecha.setText(DateFormat.getDateInstance().format(
       new Date(lugar.getFecha()))); 
     TextView hora = (TextView) findViewById(R.id.hora); 
     hora.setText(DateFormat.getTimeInstance().format(
       new Date(lugar.getFecha()))); 
     RatingBar valoracion = (RatingBar) findViewById(R.id.valoracion); 
     valoracion.setRating(lugar.getValoracion()); 
     valoracion.setOnRatingBarChangeListener(
       new RatingBar.OnRatingBarChangeListener() { 
        @Override public void onRatingChanged(RatingBar ratingBar, 
                  float valor, boolean fromUser) { 
         lugar.setValoracion(valor); 
        } 
       }); 

     ponerFoto(imageView, lugar.getFoto()); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == RESULTADO_EDITAR) { 
      actualizarVistas(); 
      findViewById(R.id.scrollView1).invalidate(); 
     }else if (requestCode == RESULTADO_GALERIA 
       && resultCode == Activity.RESULT_OK) { 
      lugar.setFoto(data.getDataString()); 
      ponerFoto(imageView, lugar.getFoto()); 
     }else if(requestCode == RESULTADO_FOTO && resultCode == Activity.RESULT_OK 
       && lugar!=null && uriFoto!=null) { 
      lugar.setFoto(uriFoto.toString()); 
      ponerFoto(imageView, lugar.getFoto()); 
     } 
    } 

    protected void ponerFoto(ImageView imageView, String uri) { 
     /*if (uri != null) { 
      imageView.setImageURI(Uri.parse(uri)); 
     } else{ 
      imageView.setImageBitmap(null); 
     }*/ 
     if (uri != null) { 
      // imageView.setImageURI(Uri.parse(uri)); 
      Bitmap d = null; 
      try { 
       d = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(uri)); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      int nh = (int) (d.getHeight() * (254.0/d.getWidth())); 

      Bitmap scaled = Bitmap.createScaledBitmap(d, 254, nh, true); 
      //imageView.setImageURI(Uri.parse(uri)); 
      imageView.setImageBitmap(scaled); 
      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     } else{ 
      imageView.setImageBitmap(null); 
     } 
    } 

    public void verMapa(View view) { 
     Uri uri; 
     double lat = lugar.getPosicion().getLatitud(); 
     double lon = lugar.getPosicion().getLongitud(); 
     if (lat != 0 || lon != 0) { 
      uri = Uri.parse("geo:" + lat + "," + lon); 
     } else { 
      uri = Uri.parse("geo:0,0?q=" + lugar.getDireccion()); 
     } 
     Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
     startActivity(intent); 
    } 

    public void llamadaTelefono(View view) { 
     startActivity(new Intent(Intent.ACTION_DIAL, 
       Uri.parse("tel:" + lugar.getTelefono()))); 
    } 


    public void pgWeb(View view) { 
     startActivity(new Intent(Intent.ACTION_VIEW, 
       Uri.parse(lugar.getUrl()))); 
    } 

    public void galeria(View view) { 
     /*Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
     intent.addCategory(Intent.CATEGORY_OPENABLE); 
     intent.setType("image/*"); 
     startActivityForResult(intent, RESULTADO_GALERIA);*/ 
     if(Build.VERSION.SDK_INT <19){ 
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
      intent.addCategory(Intent.CATEGORY_OPENABLE); 
      intent.setType("image/*"); startActivityForResult(intent, RESULTADO_GALERIA); 
     }else{ 
      Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 
      intent.addCategory(Intent.CATEGORY_OPENABLE); 
      intent.setType("image/jpeg"); 
      startActivityForResult(intent, RESULTADO_GALERIA); 
     } 
    } 

    public void tomarFoto(View view) { 
     Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); 
     uriFoto = Uri.fromFile(
       new File(Environment.getExternalStorageDirectory() + File.separator 
         + "img_" + (System.currentTimeMillis()/1000) + ".jpg")); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFoto); 
     startActivityForResult(intent, RESULTADO_FOTO); 
    } 

    public void eliminarFoto(View view) { 
     lugar.setFoto(null); 
     ponerFoto(imageView, null); 
    } 

} 

И в том же классе линии:

actualizarVistas(); 
+0

Не могли бы вы указать строку 32 'Lugares.java'? –

+0

lugar.setPosicion ((GeoPuntoAlt) новый GeoPunto (cursor.getDouble (3), cursor.getDouble (4))); – Natlum

+0

В отличие от сайтов на форуме, мы не используем «Спасибо» или «Любая помощь оценена» или подписи на [so]. См. «[Должны ли« Привет »,« спасибо », теги и приветствия удалены из сообщений?] (Http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be –

ответ

1

Это исключение ClassCastException, говорит, что вы сделали неверный кастинг класса.

lugar.setPosicion((GeoPuntoAlt) new GeoPunto(cursor.getDouble(3), cursor.getDouble(4))); 

В этой строке вы отлиты вывод new GeoPunto(...) в GeoPuntoAlt. Убедитесь, что это кастинг действительно.

+0

Я удалил бросок, и проблема решена. Спасибо вам всем. – Natlum