【问题标题】:How can I fix this error with location, adapters and ListView in Android?如何在 Android 中使用位置、适配器和 ListView 修复此错误?
【发布时间】:2014-10-28 10:07:17
【问题描述】:

大家好,我有一个无法解决的棘手错误。我正在处理列表视图,当位置服务处于活动状态时,我希望如果打开位置,我会看时间去某个地方,而当位置服务关闭时,我会显示一条消息而不是时间。没什么特别的。但是我有一个棘手的错误,例如,如果我有 GPS,那么很好的位置,工作,如果我关闭所有位置,工作,但如果我有粗略的位置活动,应用程序崩溃......这真的很棘手。在我的代码和我的 logcat 下方。谢谢大家。

全类代码:

package com.example.findmyclients;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;


import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListviewActivity extends Activity{

private ListView lista;
private ListView listaNOGPS;
private List<InterestPoint> listaInteressPoint;
private List<InterestPoint> listaInteressPointNOGPS;
private InterestPoint ip;
private CustomListAdapter adapter;
private CustomListAdapter adapterNOGPS;

public String [][]ArrayTime = new String[1000][6];  //La matrice che conterrà tutti i dati relativi alla lista

public String [][]Dati_history = new String[100][10];
public String [][]Dati_restaurant = new String[100][10];
public String [][]Dati_hotel = new String[100][10];
public String [][]Dati_souvenir = new String[100][10];
public String pathdirectory = "/sdcard/PredappioLiving/";

String[]file_names={"markers_history.xml", "markers_hotel.xml", "markers_restaurant.xml", "markers_souvenir.xml"};
String[]Array_Cat={"Monumenti","Alloggi","Ristoranti","Negozi"};

int nome_luogo = 0;
int categoria = 1;
int auto = 2;
int piedi = 3;
int latitude = 4;
int longitude = 5;

int gps_on= 0;



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

        final Activity thiz = this;

        //Get ListView Object from xml
        lista = (ListView) thiz.findViewById(R.id.lista);
        listaNOGPS = (ListView) thiz.findViewById(R.id.lista);

        GPSTracker gpstrack = new GPSTracker(this);
        if (gpstrack.canGetLocation() ) {
            gps_on = 1;
        }

        /* - - - Costruzione della matrice dall'xml - - - */
        /* - - - - - - - - - - - - - - - - - - - - - - - -*/
        int file_choice=-1;
        int n = 0;  //mi serve per riempire bene tutta la matrice
        for (int i = 0; i<file_names.length; i++)
        {
            String file_path = pathdirectory+file_names[i];
            int indice_riempimento = n;

            int returnhistory = file_names[i].compareTo("markers_history.xml");
            int returnhotel = file_names[i].compareTo("markers_hotel.xml");
            int returnrestaurant = file_names[i].compareTo("markers_restaurant.xml");
            int returnsouvenir = file_names[i].compareTo("markers_souvenir.xml");

            if (returnhistory == 0){
                file_choice = 0;
            }
            if (returnhotel == 0){
                file_choice = 1;
            }
            if (returnrestaurant == 0){
                file_choice = 2;
            }
            if (returnsouvenir == 0){
                file_choice = 3;
            }

            // Inizio lettura da XML e popolazione della matrice

            try
            {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new FileInputStream(file_path));
                doc.getDocumentElement().normalize();

                NodeList nodi = doc.getElementsByTagName("marker");



                for (int c = 0; c<nodi.getLength(); c++)
                {
                    Element item = (Element) nodi.item(c);
                    String nome = item.getAttribute("name");
                    String destLat = item.getAttribute("lat");
                    String destLong = item.getAttribute("long");

                    Double lat = Double.valueOf(destLat);
                    Double lon = Double.valueOf(destLong);

                    GPSTracker gpsTracker = new GPSTracker(this);

                    String stringMyLatitude = String.valueOf(gpsTracker.latitude);
                    String stringMyLongitude = String.valueOf(gpsTracker.longitude);

                    double currentLat = Double.parseDouble(stringMyLatitude);
                    double currentLong = Double.parseDouble(stringMyLongitude);

                    final float[]distanzadouble = new float[3];
                    Location.distanceBetween(currentLat, currentLong, lat, lon, distanzadouble);

                    float metri = distanzadouble[0];
                    float km = Math.round((double)metri/1000);

                    int minuti_persona = (int)Math.round(metri/125);    //125 metri al minuto -> velocità media di 2,5 m/s
                    int minuti_auto = (int)Math.round(km/0.7);          //700 metri al minuto -> velocità media di 42 km/h 

                    String string_min_a_piedi;
                    String string_min_in_auto;

                    if(minuti_persona <=0)          // Stampa tempo per coprire la distanza
                    {
                        string_min_a_piedi="meno di un minuto";
                    }else
                    {
                        string_min_a_piedi=String.valueOf(minuti_persona);
                    }

                    if(minuti_auto <= 0)
                    {
                        string_min_in_auto="meno di un minuto";                                 
                    }else
                    {
                        string_min_in_auto= String.valueOf(minuti_auto);
                    }

                    ArrayTime[c+n][nome_luogo] = nome;
                    ArrayTime[c+n][categoria] = Array_Cat[file_choice];
                    ArrayTime[c+n][auto] = string_min_in_auto;
                    ArrayTime[c+n][piedi] = string_min_a_piedi;


                }

                n = n+nodi.getLength();


            }catch(Exception e)
            {
                e.printStackTrace();
            }


        }

        //Arrays.sort(ArrayTime, new ColumnComparator(0));




        //Stampa dell'array sulla lista - - -

        /*
        for(int i = 0; i<6; i++)
        {   
            ip = new InterestPoint();
            ip.nome = "pippo"+i;
            ip.categoria ="cat pippo"+i;
            ip.apiedi = "25";
            ip.inauto = "10";
            listaInteressPoint.add(ip);
        }
        */



        final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );


        if (gps_on == 1) {

            listaInteressPoint = new ArrayList<InterestPoint>();

            for(int i = 0; i<n;i++)
            {
                ip = new InterestPoint();
                ip.nome = ArrayTime[i][nome_luogo];
                ip.categoria = "Categoria: "+ArrayTime[i][categoria];
                ip.inauto = "In auto: " +ArrayTime[i][auto]+ " minuti";
                ip.apiedi = "A piedi: " +ArrayTime[i][piedi]+ " minuti";
                listaInteressPoint.add(ip);
            }

            //Ordinamento
            Collections.sort(listaInteressPoint, new Comparator<InterestPoint>(){

                @Override
                public int compare(InterestPoint elem1, InterestPoint elem2) {

                    return elem1.inauto.compareTo(elem2.inauto);
                }

            });


        }else
        {

            listaInteressPointNOGPS = new ArrayList<InterestPoint>();

            for(int i = 0; i<n;i++)
            {
                ip = new InterestPoint();
                ip.nome = ArrayTime[i][nome_luogo];
                ip.categoria = "Categoria: "+ArrayTime[i][categoria];
                ip.inauto = "In auto:   Attiva la posizione per la distanza";
                ip.apiedi = "A piedi:   in auto e a piedi";
                listaInteressPointNOGPS.add(ip);
            }

            //Ordinamento
            Collections.sort(listaInteressPointNOGPS, new Comparator<InterestPoint>(){

                @Override
                public int compare(InterestPoint elem1, InterestPoint elem2) {

                    return elem1.nome.compareTo(elem2.nome);
                }

            });
        }

       /* 
      //ListView Item Click Listener
            listaNOGPS.setOnItemClickListener(new OnItemClickListener() {


                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                //ListView Clicked item index
                        int itemPosition = position;

                        InterestPoint item = adapter.getItem(position);

                        Intent piu_info = new Intent(thiz, MoreInfoActivity.class); 
                        piu_info.putExtra("nome", item.nome);
                        startActivity(piu_info);
                        //ListView clicked item value
                        //int itemValue = (int) lista.getItemAtPosition(position);

                        //Show Alert
                        Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();

                }
            });

            */  

        //ListView Item Click Listener
        lista.setOnItemClickListener(new OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                    if (gps_on == 1){
                        //ListView Clicked item index
                        int itemPosition = position;

                        InterestPoint item = adapter.getItem(position);

                        Intent piu_info = new Intent(thiz, MoreInfoActivity.class); 
                        piu_info.putExtra("nome", item.nome);
                        startActivity(piu_info);
                        //ListView clicked item value
                        //int itemValue = (int) lista.getItemAtPosition(position);

                        //Show Alert
                        Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();
                    }else
                    {
                        //ListView Clicked item index
                        int itemPosition = position;

                        InterestPoint item = adapterNOGPS.getItem(position);

                        Intent piu_info = new Intent(thiz, MoreInfoActivity.class); 
                        piu_info.putExtra("nome", item.nome);
                        startActivity(piu_info);
                        //ListView clicked item value
                        //int itemValue = (int) lista.getItemAtPosition(position);

                        //Show Alert
                        Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();
                    }


            }
        });

    }

    @Override
        protected void onResume() {
            super.onResume();

            final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
            adapter = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPoint);
            adapterNOGPS = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPointNOGPS);

            if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {

                lista.setAdapter(adapter);
            }else
            {
                listaNOGPS.setAdapter(adapterNOGPS);
            }
        }
}

Logcat:

10-28 10:53:53.106: E/AndroidRuntime(445): FATAL EXCEPTION: main
10-28 10:53:53.106: E/AndroidRuntime(445): Process: com.example.findmyclients, PID: 445
10-28 10:53:53.106: E/AndroidRuntime(445): java.lang.RuntimeException: Unable to resume activity {com.example.findmyclients/com.example.findmyclients.ListviewActivity}: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3076)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3105)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.access$900(ActivityThread.java:175)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.os.Looper.loop(Looper.java:146)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.main(ActivityThread.java:5602)
10-28 10:53:53.106: E/AndroidRuntime(445):  at java.lang.reflect.Method.invokeNative(Native Method)
10-28 10:53:53.106: E/AndroidRuntime(445):  at java.lang.reflect.Method.invoke(Method.java:515)
10-28 10:53:53.106: E/AndroidRuntime(445):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
10-28 10:53:53.106: E/AndroidRuntime(445):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
10-28 10:53:53.106: E/AndroidRuntime(445):  at dalvik.system.NativeStart.main(Native Method)
10-28 10:53:53.106: E/AndroidRuntime(445): Caused by: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.widget.ListView.setAdapter(ListView.java:486)
10-28 10:53:53.106: E/AndroidRuntime(445):  at com.example.findmyclients.ListviewActivity.onResume(ListviewActivity.java:356)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1198)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.Activity.performResume(Activity.java:5530)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3066)
10-28 10:53:53.106: E/AndroidRuntime(445):  ... 12 more
10-28 10:53:53.161: I/Process(445): Sending signal. PID: 445 SIG: 9

P.S.:粗略位置变量“gps_on”正确设置为“1”

【问题讨论】:

  • 请删除标题的“已解决”标签:meta.stackexchange.com/questions/116101/…
  • 我还看到您编辑代码以将其发布更正。你不应该。有类似问题的人会来这里和你的编辑,没有人会明白答案在说什么。请阅读How to Ask 了解更多信息;)

标签: android listview android-listview location adapter


【解决方案1】:

1.

if (gps_on == 1) {

            listaInteressPoint = new ArrayList<InterestPoint>();  
//rest of the code
} else {  
            listaInteressPointNOGPS = new ArrayList<InterestPoint>();
//rest of the code
}

2. PS:粗略位置变量“gps_on”正确设置为“1”

所以

3.来自您的onResume()

   adapter = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPoint);
            adapterNOGPS = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPointNOGPS);

            if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {

                lista.setAdapter(adapter);
            }else
            {
                listaNOGPS.setAdapter(adapterNOGPS);
            }  

您得到的错误是 listgetCount() 已初始化但为空,未填充。在这种情况下,gps_on==1 所以listaInteressPointNOGPS 不会被访问。

您可以更改onResume() 中的if 并检查或条件可能...在粗略位置特别活跃的情况下。

您的 logcat 中的重要行

10-28 10:53:53.106: E/AndroidRuntime(445): Caused by: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.widget.ListView.setAdapter(ListView.java:486)
10-28 10:53:53.106: E/AndroidRuntime(445):  at com.example.findmyclients.ListviewActivity.onResume(ListviewActivity.java:356)  

从 ListviewActivity.java 中检查哪一行是第 356 行

【讨论】:

  • 你班的第 356 行是哪一行?把它放在 try catch 中,你就会知道
  • 我根据你的建议解决了!!谢谢,我更新了我的问题:D
  • 太棒了,很高兴它有帮助,节省了一些时间:)
猜你喜欢
  • 2016-06-25
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
相关资源
最近更新 更多