我目前正在从事我的高级项目,该项目涉及从数据库中获取数据并进行存储,然后将其显示在App上。 所以最近我遇到了一些问题,这些代码主要返回两个错误:

  1. RuntimeException:不确定是什么原因
  2. NullPointerException:由于busList数组返回空

这是我的代码:

活动:ShowResults.java

public class ShowResults extends ActionBarActivity {
private static Connection connection = null;
private static String[] busList;
public double lat=24.197910, lon=55.678712;
public static double[][] locCoords = {{24.214649, 55.705841},
        {24.340635, 55.477802}, {24.221663, 55.692266},
        {24.195968, 55.682879}, {24.196066, 55.679534}, {24.197910, 55.678712}, {24.198966, 55.677567}, {24.199936, 55.677314}, {24.200635, 55.677801}};
public static String[] BldNames = {"Saih Bin Ammar Hostel", "Kowaitat Hostel", "Markhaniah Hostel",
        "F3 Building", "F1 Building/The labs", "CIT Building",
        "H4 Building", "Crescent Building",
        "H2/H3 Buildings", "User Current Location"};

//1.jdbc driver name
private static String SQL_JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 2. Database URL, V_UDAY\FRAMEWORK is ServerName and JSF is DataBase name
private static String URL
        = "jdbc:sqlserver://NCMSVTRNSDB.aa.uaeu.ac.ae;databaseName=busTable";
//3.Database credentials
private static String USERNAME = "username";//UserName
private static String PASSWORD = "pass";//Password
public static String[] arr;
public static Connection getLocalConnection(double cLat,double cLon) {
    //   PrintWriter writer = new PrintWriter("l.txt");
    Statement stmt = null;
    try {
        Class.forName(SQL_JDBC_DRIVER);// Register jdbc driver
        //4. open a connection
        connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        stmt = connection.createStatement();
        String sql;
        sql = "Select ID, NAME, DT_UPDATE,LON,LAT From mobile";
        ResultSet rs = stmt.executeQuery(sql);
        //STEP 5: Extract data from result set
        String result = "";
        busList = new String[128];//
        int i = 0;
        double dist;
        double l,l2;
        while (rs.next()) {
            //Retrieve by column name
            String id = rs.getString("ID");
            String name = rs.getString("NAME");
            String first = rs.getString("DT_UPDATE");
            String lat = rs.getString("LAT");
            String lon = rs.getString("LON");
            Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            String current = sdf.format(c.getTime());
            if (isCurrent(first) == true) {
                if (name.contains("Hyundai") || name.contains("Coaster")) {
                    result = "Bus:" + name + "\nTime:" + first + "\n" + calcTime(first, current);
                    l = Double.parseDouble(lat);
                    l2 = Double.parseDouble(lon);
                    dist = calcDist(cLat, cLon, l, l2);
                    result += "\nDistance: " + dist;
                    result += "\nClosest Building: " + closestBldg(l, l2);
                    result += "\n On/Off Campus: " + onOffCampus(l, l2);
                    busList[i] = result;
                }
                i++;
            }
            else{
                result = "Bus:" + name + "\nTime:" + first + "\n" + calcTime(first, current);
                l = Double.parseDouble(lat);
                l2 = Double.parseDouble(lon);
                dist = calcDist(24.197910, 55.678712, l, l2);
                result += "\nDistance: " + dist;
                result += "\nClosest Building: " + closestBldg(l, l2);
                result += "\n Om/Off Campus: " + onOffCampus(l, l2);
                busList[i] = result;
            }
        }
        //STEP 6: Clean-up environment
        rs.close();
        stmt.close();

        setConnectionClose();
        System.out.println("Database Connection Closed");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Exception in getLocalConeection() " + e.getMessage());
    }
    return connection;
}

public static void setConnectionClose() throws SQLException {
    if (connection != null) {
        connection.close();
    }
}
public static boolean isCurrent(String busTime) {
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    String current = sdf.format(c.getTime());
    Date d1 = null;
    Date d2 = null;

    try {
        d1 = sdf.parse(current);
        d2 = sdf.parse(busTime);

        //in milliseconds
        long diff = d1.getTime() - d2.getTime();

        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);

        if (diffDays == 0 && diffHours <= 1 && (diffMinutes <= 59 && diffMinutes >= 0) && diffSeconds >= 0) {
            return true;
        } else {
            return false;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}
public static String[] getBusList(){
    return busList;
}
public static double calcDist(double lat1, double lon1, double lat2, double lon2) {
    double R = 6371000;
    double theta1 = Math.toRadians(lat1);
    double theta2 = Math.toRadians(lat2);
    double thetaDiff = Math.toRadians(theta2 - theta1);
    double lambdaDiff = Math.toRadians(lon2 - lon1);
    double a = Math.pow(Math.sin(thetaDiff / 2),2)
            + Math.cos(theta1) * Math.cos(theta2)
            * Math.sin(lambdaDiff / 2) * Math.pow(Math.sin(lambdaDiff / 2),2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = R * c;
    return d;
}

public static String calcTime(String time1, String time2) throws ParseException {
    String result;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    Date date1 = null,date2=null;
    try {
        date1 = format.parse(time1);
        date2 = format.parse(time2);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    long diff = date2.getTime() - date1.getTime();
    long secs = diff / 1000 % 60;
    long mins = diff / (60 * 1000) % 60;
    long hrs = diff / (60 * 60 * 1000) % 24;
    long days = diff / (24 * 60 * 60 * 1000);
    if (hrs > 0 && mins > 0 && secs >= 0) {
        result = "ETA: " + hrs + " Hours, " + mins + " Minutes" + " and " + secs + " Seconds";
    } else if (mins > 0 && secs >= 0) {
        result = "ETA: " + mins + " Minutes" + " and " + secs + " Seconds";
    } else if (secs >= 0.01) {
        result = "ETA: " + secs + " Seconds";
    } else {
        result = "ETA: " + "The bus should be here";
    }
    return result;
}


public static String onOffCampus(double busLat, double busLon) {
    double uniLat1 = 24.197690, uniLon1 = 55.677708;
    double uniLat2 = 24.198316, uniLon2 = 55.685948;
    double distToUni1 = calcDist(uniLat1, uniLon1, busLat, busLon);
    System.out.println(distToUni1);

    double distToUni2 = calcDist(uniLat2, uniLon2, busLat, busLon);
    System.out.println(distToUni2);
    if (distToUni1 <= 0.639822725733094 || distToUni2 <= 0.588121032252993) {
        return "On";
    }
    return "Off";
}
public static String closestBldg(double busLat, double busLon) {
    double dist, lat1, lon1, min;
    int mi = 0;
    lat1 = locCoords[0][0];
    lon1 = locCoords[0][1];
    min = calcDist(lat1, lon1, busLat, busLon);

    for (int k = 1; k < locCoords.length; k++) {

        lat1 = locCoords[k][0];
        lon1 = locCoords[k][1];
        dist = calcDist(lat1, lon1, busLat, busLon);
        if (dist < min) {
            min = dist;
            mi = k;
        }
    }

    return BldNames[mi];
}
public void populateListView(){

    //build adapter
    ArrayAdapter<String> adapter;
    adapter = new ArrayAdapter<>(this, R.layout.activity_show_results, busList);

    //config the list view
    ListView list = (ListView) findViewById(R.id.listView5);
    list.setAdapter(adapter);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle b = getIntent().getExtras();
    if (b != null) {
        if (b.containsKey("lat1")) {
            lat = b.getDouble("lat1");
        }
        if (b.containsKey("lon1")) {
            lon = b.getDouble("lon1");
        }}
    else{
        lat = 24.197910;
        lon=55.678712;
    }
    getIntent().removeExtra("lat1");
    getIntent().removeExtra("lon1");
    getLocalConnection(lat,lon);
    populateListView();
 }
 }

活动ShowResults XML:activity_show_results.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="ae.ac.uaeu.bustrackerapp.ShowResults">

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView5"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />
 </RelativeLayout>

TextView的XML:dat_item.xml

<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>

我确信每当我调用busList并尝试对其进行修复时,它都是空的,但是不能。 这是最有可能是我的NullPointerExcpetion的原因,但不知道是什么原因导致RuntimeException的,这是崩溃报告:

         --------- beginning of crash
05-16 21:09:15.373    1927-1927/ae.ac.uaeu.bustrackerapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: ae.ac.uaeu.bustrackerapp, PID: 1927
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ae.ac.uaeu.bustrackerapp/ae.ac.uaeu.bustrackerapp.ShowResults}: java.lang.NullPointerException: storage == null
            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.NullPointerException: storage == null
            at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
            at java.util.Arrays.asList(Arrays.java:155)
            at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
            at ae.ac.uaeu.bustrackerapp.ShowResults.populateListView(ShowResults.java:235)
            at ae.ac.uaeu.bustrackerapp.ShowResults.onCreate(ShowResults.java:260)
            at android.app.Activity.performCreate(Activity.java:5933)
            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) 

任何帮助/建议/反馈表示赞赏

===============>>#1 票数:0 已采纳

您应该调用populateListView(); 当您完成填充busList时的方法,如果不是,则此方法可以为null。 您应该将其放在getLocalConnection方法的末尾。

也改变

public void populateListView(){

   ArrayAdapter<String> adapter= new ArrayAdapter<>(this, R.layout.dat_item, busList);

   //config the list view
   ListView list = (ListView) findViewById(R.id.listView5);
   list.setAdapter(adapter);

}

 @Override
  protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_show_results);
      //All your stuff here
    }

我测试了上面的代码,它可以正常工作,我认为您的listView为空的原因是因为busList为空。 这是在我的测试中工作的populateListView()中的代码。

public void populateListView() {
    busList = new String[2];
    busList[0] = "test";
    busList[1] = "test1";

    // build adapter
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.dat_item, busList);

    // config the list view
    ListView list = (ListView) findViewById(R.id.listView5);
    list.setAdapter(adapter);
}

  ask by Wrix789 translate from so

未解决问题?本站智能推荐:

3回复

Android-NullPointerException

我收到一个NullPointerException,它破坏了这一行的代码: 这是代码块: 我猜想它与MarkerOptions变量有关,但是我不确定它是否因为未初始化而中断? 任何帮助将不胜感激。
1回复

ProGuard Android-JDBC错误-NullPointerException

我正在尝试使用Proguard混淆我的Android应用程序。 但是我遇到了一个奇怪的问题,希望你们中的一个能够帮助我。 如您所见,我已经将mysql JDBC lib添加为libary和应保留的类。 但是,当我尝试将项目编译为.apk文件时,我最终遇到了这个奇怪的错误。 根据我的
1回复

PostgreSQL JDBC和Android-NullPointerException

我在Android上的PostgreSQL JDBC驱动程序遇到问题。 我使用的是postgresql-9.2-1002.jdbc4.jar JDBC驱动程序。 这是我的代码: 当我运行此方法时,我得到了NullPointerException: 我不知道怎么了 我
2回复

setText上的android-NullPointerException为textView

我已经发布了一个应用程序,该应用程序已被下载约5000次。 我已经在4种不同的设备上对其进行了测试,尽管有一些用户为其应用缓存,但很多人表示它可以正常工作。 这是代码: 当有人单击ActionBar上的imageButton并打开一个对话框并为其中的textview设置文本时调用。
1回复

NullPointerException:对空对象引用的Connection.createStatement()

我在Android的学校项目中使用JDBC( 我知道这不是一件好事 ),而且我不明白为什么createStatement会返回null。 我正在AsyncTask中执行jdbc代码: 192.168.137.1是运行Xampp的计算机的IP(已打开Apache和MySQL),端口为33
1回复

Android-JDBC登录

这是我的登录屏幕。 顶部的editText是“ txtbxStudentUsername”,底部的editText是“ txtbxStudentLunchID”。 我正在使用jdbc连接到局域网上的phpadmin wamp mysql服务器,因此没有通过Internet的SQL问题。
2回复

Android Studio JDBC MySQL

我试图解决这个问题达四个小时,但我完全没有希望。 我正在使用android studio对此应用程序进行编码。 我创建了一个简单的活动,其中包含用于用户名和密码的编辑字段,接下来有一个按钮,该按钮旨在从这两个编辑字段中提交数据。 我正在使用mysql connector / j并且
1回复

Android JDBC连接问题

我试图连接到我的网站的MySQL数据库,并且我不了解PHP,所以决定使用JDBC。 我遵循了一些视频教程(非JDBC),并使用了它们的步骤。 我跳过了MAMP步骤,因为我没有从PC托管服务器。 它正在本地托管,因为它将是一个更大的网站。 因此,我在“登录活动”中输入了以下代码(您看到
1回复

通过Android的MySQL连接错误

我的Android项目有一个小问题。 我想用我的MySQL数据库中的数据填充列表,但是android无法连接到它。 这是我的代码: MySQLConnector: SQLManager: 而Class构成了Android活动: 我的探究是A
1回复

有时与Android的JDBC连接不起作用

几天前,我开始开发一个Android应用程序,我决定使用JDBC进行数据库连接(数据库在云中),而且我知道使用php Web服务更安全。 这是我的问题: 直到昨天,我仍然能够建立连接并获取查询结果并登录到该应用程序,但是不知何故我现在无法做到这一点。 我正在为数据库使用Google C