0
public void directionSpinner (String directions []) {
        //Does some stuff to assign namedDirections [0] and namedDirections[1] a value.

        dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); //THIS IS LINE 87
        dirSpinner.setOnItemSelectedListener(this);
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adapter.add(namedDirections[0]);
        adapter.add(namedDirections[1]);
        dirSpinner.setAdapter(adapter);

        Log.i(TAG, "spinner populated");
}

日志猫:

12-09 20:50:13.497: E/AndroidRuntime(857): FATAL EXCEPTION: main
12-09 20:50:13.497: E/AndroidRuntime(857): java.lang.NullPointerException
12-09 20:50:13.497: E/AndroidRuntime(857):  at android.app.Activity.findViewById(Activity.java:1839)
12-09 20:50:13.497: E/AndroidRuntime(857):  at com.nicotera.colton.londontransitguide.RoutesActivity.directionSpinner(RoutesActivity.java:87)
12-09 20:50:13.497: E/AndroidRuntime(857):  at com.nicotera.colton.londontransitguide.MyInnerClass.onPostExecute(RoutesActivity.java:142)
12-09 20:50:13.497: E/AndroidRuntime(857):  at com.nicotera.colton.londontransitguide.MyInnerClass.onPostExecute(RoutesActivity.java:1)

无论如何, route_direction_spinner 定义正确。directionSpinner() 在 AsyncTask 完成后运行。

完整代码:

package com.nicotera.colton.londontransitguide;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.*;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class RoutesActivity extends Activity implements OnItemSelectedListener {
    Spinner dirSpinner;
    Spinner routeSpinner;


    static String [] namedDirections = new String [2];
    private static final String TAG = "RoutesActivity";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_routes);
        dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
        routeSpinner = (Spinner) findViewById(R.id.route_name_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
        routeSpinner.setOnItemSelectedListener(this);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.routes_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner
        routeSpinner.setAdapter(adapter);
        Log.i(TAG, "second spinner populated");
    }

    public void onItemSelected(AdapterView<?> parent, View view, 
            int pos, long id) {
        Log.i(TAG, "Item selected");
        //DecimalFormat df = new DecimalFormat("00##");
        int tempPos = pos;
        Log.i(TAG, ("Position of selected item: " + tempPos));
        int routeSelected;
        if (tempPos < 17)
            routeSelected = (tempPos + 1);
        else if (tempPos >= 17 && tempPos < 29)
            routeSelected = (tempPos + 2);
        else
            routeSelected = (tempPos + 3);
        String temp;
        if (routeSelected < 10)
            temp = ("0") + routeSelected;
        else
            temp = ("") + routeSelected;
        String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
        new MyInnerClass().execute(url);

    }

    public void directionSpinner (String directions []) {
        int temp;
        for (int i = 1; i <=2; i++)
        {
            temp = Integer.parseInt(directions[i]);
            if (temp == 1)
                namedDirections[(i-1)] = "Eastbound";
            else if (temp == 2)
                namedDirections[(i-1)] = "Northbound";
            else if (temp == 3)
                namedDirections[(i-1)] = "Southbound";
            else if (temp == 4)
                namedDirections[(i-1)] = "Westbound";               
        }
        //setContentView(R.layout.activity_routes);

        dirSpinner.setOnItemSelectedListener(this);
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adapter.add(namedDirections[0]);
        adapter.add(namedDirections[1]);
        dirSpinner.setAdapter(adapter);
        Log.i(TAG, "spinner populated");
    }



    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }
}

class MyInnerClass extends AsyncTask<String, Void, String> {
    String [] directions = new String [3];
    String [] directionNames = new String [3];
    private static final String TAG = "RoutesActivity";
       @Override
       protected void onPreExecute() {
       super.onPreExecute();

       }

       @Override
       protected void onPostExecute(String result) {
       super.onPostExecute(result);
       RoutesActivity tc = new RoutesActivity();
       tc.directionSpinner(directions);
       }

    @Override
    protected String doInBackground(String... params) {
        try{
            Pattern routeDirPattern = Pattern.compile("\\&d=(\\d{1,2})");
            Connection conn = Jsoup.connect(params[0]);
            Document doc = conn.get();
            int i = 0;
            Elements routeLinks = doc.select("a[href]");
            for (Element routeLink : routeLinks) {
                i = (i + 1);
                String name = routeLink.text();
                Attributes attrs = routeLink.attributes();
                String href = attrs.get("href");
                Matcher m = routeDirPattern.matcher(href);
                if (m.find()) {
                        String number = m.group(1);
                        directions [i] = number;
                        directionNames [i] = name;
                        Log.i(TAG, directionNames [i]);
                }
            }
            }catch(Exception e){Log.d("doinbackground exception", e.toString());}
           return ("Done");
    }
}

基本上,这会从公交网站获取一些值。到目前为止,这部分代码只是根据所选路线获取路线的方向。

4

1 回答 1

1

(您directionSpinner()发布的两个片段中的方法不同,我正在使用稍后添加的那个,但假设问题相同,此解决方案应该适用于两个片段)

您的问题是您没有正确遵循 Activity 生命周期。

你打电话时:

RoutesActivity tc = new RoutesActivity();
tc.directionSpinner(directions);

您实际上是在创建一个全新的RoutesActivity. 而且由于您将其作为标准 Java 类调用,因此它永远不会遵循 Activity 生命周期,这意味着它onCreate()永远不会被调用,这反过来意味着您的两个微调器对象保持为空(当您在 中为它们分配值时onCreate())。

因此,当您使用:

dirSpinner.setOnItemSelectedListener(this);

dirSpinner实际上null导致了一个NullPointerException.

相反,请尝试使用:

RoutesActivity.this.directionSpinner(directions);

代替:

RoutesActivity tc = new RoutesActivity();
tc.directionSpinner(directions);
于 2012-12-09T21:16:29.233 回答