我想要实现的是使用微调器从城镇选择然后到城镇,然后检索我在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) {
}
}
感谢您帮我解决这个问题!!!
答案 0 :(得分: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是另一种选择。