【问题标题】:getText() toString() method not working on method parametersgetText() toString() 方法不适用于方法参数
【发布时间】:2018-01-02 18:34:29
【问题描述】:

在我的 android 应用程序中的 EditText 字段上引入输入(字符串,例如:A、B 等)后,我按下了我的应用程序停止的按钮。我是android应用程序的新手。当我尝试调用方法“在空对象引用上” 时出现空指针异常,但我不明白为什么我的对象为空... 如果我将值写入变量

weight = Main.callMethod("A", "B");

它工作得很好,但是如果我让应用程序中的值像行中一样

weight = Main.callMethod(source, destination);

应用程序停止。

这是我使用的 2 个类:

public class MainActivity extends Activity {

private Button b;
public static EditText currentLoc, selectDestination;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    currentLoc = (EditText)findViewById(R.id.editText);
    selectDestination = (EditText)findViewById(R.id.editText2);
    tv = (TextView) findViewById(R.id.textView);
    // this.tv.setMovementMethod(new ScrollingMovementMethod());

    currentLoc.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //tv.setText(s);
            source = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    selectDestination.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //tv.setText(s);
            destination = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    //source = currentLoc.getText().toString(); //getHint() instead og getText()
    //destination = selectDestination.getText().toString();

    final Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Code here executes on main thread after user presses button

            int weight; //= 0;

            Log.d("Source", "Current loc:" + source + " END");
            Log.d("Destination", "Select destination:" + destination + " END");

            Log.d("Compare", "2 strings " + source.equals("A"));

            Log.d("Source length" ,"is: " + source.length());
            Log.d("Destination length", "is: " + destination.length());

            //weight = Main.callMethod("A", "B");
            weight = Main.callMethod(source, destination); //not working !!!
            tv.setText("" + weight);

            //tv.setText("Your Input: \n" + source + "\n" + destination + "\nEnd.");
        }
    });
}

}

另一个类的方法是这样的:

public class Main {

public static int callMethod (String source, String destination) {

    List<Path> list = new ArrayList();
    list.add(new Path("A", "C", 4));
    list.add(new Path("A", "B", 6));
    list.add(new Path("B", "C", 2));
    list.add(new Path("B", "D", 2));
    list.add(new Path("C", "D", 1));
    list.add(new Path("C", "E", 2));
    list.add(new Path("E", "D", 1));
    list.add(new Path("E", "F", 3));
    list.add(new Path("D", "F", 7));

    DijkstraAlgorithm object = new DijkstraAlgorithm(list);
    list = object.compute(source, destination);

    int weight = 0;
    for (Path path : list) {

        weight = path.getWeight();
        //System.out.println(path.getSource() + " -> " + path.getDestination() + " (" + path.getWeight() + ")");
    }

    return weight;
}
}

Logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.nicoleta.trafficappfinal.Pair.getSource()' on a null object reference
                                                                                      at com.example.nicoleta.trafficappfinal.DijkstraAlgorithm.generateShortestPath(DijkstraAlgorithm.java:112)
                                                                                      at com.example.nicoleta.trafficappfinal.DijkstraAlgorithm.compute(DijkstraAlgorithm.java:28)
                                                                                      at com.example.nicoleta.trafficappfinal.Main.callMethod(Main.java:45)
                                                                                      at com.example.nicoleta.trafficappfinal.MainActivity$1.onClick(MainActivity.java:42)
                                                                                      at android.view.View.performClick(View.java:5675)
                                                                                      at android.view.View$PerformClick.run(View.java:22651)
                                                                                      at android.os.Handler.handleCallback(Handler.java:836)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:103)
                                                                                      at android.os.Looper.loop(Looper.java:208)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:6267)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

DijkstraAlgorithm - 在这个类中,问题似乎是,Path,Pair 类: 编辑:

public class DijkstraAlgorithm {
private final List<Path> graph;
private List<Path> shortestPath;
private Map distance;

public DijkstraAlgorithm(List<Path> graph)
{
    this.graph = graph;
}

public List<Path> compute(String start, String end)
{
    List<Path> list = new ArrayList();
    list.addAll(graph);
    shortestPath = new ArrayList();
    distance = new HashMap();
    distance.put(start, new Pair(0, "\0"));
    compute(start, end, list);
    generateShortestPath(start, end);

    return shortestPath;
}

private void compute(String source, String destination, List<Path> graph)
{
    Path bestPath = null;

    for (Path path : graph)
    {
        if (path.getSource() == source)
        {
            int pathVal = path.getWeight() + ((Pair) distance.get(source)).getValue();

            if (!distance.containsKey(path.getDestination()))
            {
                distance.put(path.getDestination(), new Pair(pathVal, path.getSource()));
            }
            else
            {
                if (((Pair) distance.get(path.getDestination())).getValue() > pathVal)
                {
                    distance.remove(path.getDestination());
                    distance.put(path.getDestination(), new Pair(pathVal, path.getSource()));
                }
            }

            if (bestPath == null)
            {
                bestPath = path;
            }
            else
            {
                if (((Pair) distance.get(bestPath.getDestination())).getValue() > ((Pair) distance.get(path.getDestination())).getValue())
                {
                    bestPath = path;
                }
            }
        }
    }

    List<Path> remove = new ArrayList();

    for (Path path : graph)
    {
        if (path.getSource() == source || path.getDestination() == source)
        {
            remove.add(path);
        }
    }

    graph.removeAll(remove);

    if (bestPath != null)
    {
        if (bestPath.getDestination() != destination)
        {
            boolean check = false;

            for (Path path : graph)
            {
                if (path.getSource() == bestPath.getDestination())
                {
                    check = true;
                }
            }

            if (check)
            {
                compute(bestPath.getDestination(), destination, graph);
            }
            else if (!graph.isEmpty())
            {
                compute(graph.get(0).getSource(), destination, graph);
            }
        }
    }
}

private void generateShortestPath(String start, String end)
{
    Pair pair = (Pair) distance.get(end);

    Log.d("Start", "is " + start); //this is now visible
    Log.d("End", "is " + end); //this is also visible
    Log.d("Msg1", "is " + "source " + pair.getSource() +   //at this line is the error !!!
                                    " value " + pair.getValue() +"\n");

    shortestPath.add(new Path(pair.getSource(), end, pair.getValue())); 

    while (pair.getSource() != start)
    {
        String c = pair.getSource();
        pair = (Pair) distance.get(pair.getSource());
        shortestPath.add(new Path(pair.getSource(), c, pair.getValue()));
    }

    Collections.reverse(shortestPath);
}
}



public class Pair {
private int value;
private String source;

public Pair(int value, String source)
{
    this.value = value;
    this.source = source;
}

public int getValue()
{
    return value;
}

public String getSource()
{
    return source;
}

public void setValue(int value)
{
    this.value = value;
}

public void setSource(String source)
{
    this.source = source;
}
}


public class Path {
private String source;
private String destination;
private int weight;

public Path(String source, String destination, int weight)
{
    this.source = source;
    this.destination = destination;
    this.weight = weight;
}

public String getSource()
{
    return source;
}

public String getDestination()
{
    return destination;
}

public int getWeight()
{
    return weight;
}

public void setSource(String source)
{
    this.source = source;
}

public void setDestination(String destination)
{
    this.destination = destination;
}

public void setWeight(int weight)
{
    this.weight = weight;
}
}

【问题讨论】:

  • source 和 destination 有什么价值?
  • 请分享您的堆栈跟踪
  • 贴出logcat的错误..
  • 提供你的 logcat
  • 字符串@luk2302

标签: java android tostring


【解决方案1】:

确保 EditTexts currentLoc 和 selectDestination 不是 final。并在 button.setOnClickListener() 之外初始化它们,这意味着,在状态之后初始化它们

final Button button = findViewById(R.id.button);

或更多。

并且始终检查source 和destinition 的length 是否明显大于0,在声明之前

weight = Main.callMethod(source, destination);

【讨论】:

  • 感谢您的帮助!这就是问题!源和目标的长度始终为 0。希望我能弄清楚原因。
  • 您是否将 currentLoc 和 selectDestination 声明为 final?如果它们是最终的,则不会为它们设置新值。
  • 不不,它们不是最终的(只有公共静态),我已经按照你说的移动了初始化。
  • .xml 文件会是问题吗?
  • 我解决了长度为 0 的问题。问题出在代码行 112 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 2012-08-30
  • 2015-12-20
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多