0

我想要实现的是使用微调器从城镇中选择,然后到城镇,然后检索我在 dist.js 文件中定义的旅行距离和时间。当我在 webview 中使用 html 时效果很好。但我不想使用 webview。因此,我怎样才能让两个微调器来计算呢?


好的,已经尝试过,但仍然没有任何效果。到目前为止,这是我的代码。你能告诉我我做错了什么吗?

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import org.json.JSONArray;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity  extends Activity{ 

Spinner s1; 
Spinner s2; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 


s1  = (Spinner) findViewById(R.id.spinner1);
s2  = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.camp_sites, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
InputStream is = context.getResources().openRawResource(R.raw.dist); 
Writer writer = new StringWriter(is.available()); 
char[] buffer = new char[1024]; 
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); {
try { 
    int n; 
    while ((n = reader.read(buffer)) != -1) { 
        writer.write(buffer, 0, n); 
    } 
} finally { 
    reader.close(); 
} 
String jsonString = writer.toString(); 

JSONArray json = new JSONArray(jsonString);}
}


public void onNothingSelected(AdapterView<?> parent) {

   }
}

谢谢你帮我解决这个问题!!!

4

1 回答 1

0

加载 js 文件,获取城镇名称数组,并将它们放入ArrayAdapter中。然后将适配器传递给您的微调器:

spinner.setAdapter(adapter);

对两个旋转器中的每一个执行一次。

有关微调器的更多信息:http: //developer.android.com/guide/topics/ui/controls/spinner.html

更新

要加载 js 文件(我假设它包含一个 JSON 数组),您可以将其放入resources/raw并执行以下操作:

// open the input stream
InputStream is = context.getResources().openRawResource(R.raw.dist);

// read into a buffer
// NOTE: This is ugly, and there may be a better way, but it works.
Writer writer = new StringWriter(is.available());
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
    int n;
    while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
    }
} finally {
    reader.close();
}
String jsonString = writer.toString();

// load into a JSONArray
// if your file contains a single object, use JSONObject instead
JSONArray json = new JSONArray(jsonString);

如果您的 json 文件真的很大,有一种方法可以将流解析为 JSON,而无需先读取整个内容,但它更复杂。为此,我推荐Jackson,并且真正满足您的所有 JSON 需求。Gson是另一种选择。

于 2012-10-18T20:23:31.263 回答