我是android开发的新手。我在android studio
工作。我有一些json
个文件放在我的assets
文件夹中。现在我想将json文件中的数据填充到微调器中。我知道如何使用微调器并使用web service
填充数据,但我不知道如何使用json
文件。此外,我找不到任何教程,但是我确实找到how to read data from json file,但我想在微调器中填充它。以下是我的json
文件数据之一。
ref.json
{"reference":
[
{"ref_no":"11111111111111","Name":"Faisal"},
{"ref_no":"22222222222222","Name":"Salman"},
{"ref_no":"33333333333333","Name":"Asim"},
{"ref_no":"44444444444444","Name":"Asad"},
{"ref_no":"55555555555555","Name":"Mateen"},
{"ref_no":"66666666666666","Name":"Omar"},
{"ref_no":"77777777777777","Name":"Usama"}
]}
以下是spinner
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/dd_ref"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
我想从JSON文件中获取ref_no
并将它们显示在微调器中。
更新1
在阅读了我已完成以下的答案和建议之后
ArrayList<String> refList;
public static final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
loadData();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void loadData() throws JSONException {
JSONArray jsonArray;
JSONObject jobj;
try
{
jobj = new JSONObject(loadJSONFromAssest());
jsonArray = jobj.getJSONArray("reference");
for(int i = 0; i<jsonArray.length();i++)
{
jobj = jsonArray.getJSONObject(i);
Log.d("Details-->", jobj.getString("ref_no"));
String ref = jobj.getString("ref_no");
refList.add(ref);
}
} catch (JSONException e)
{
e.printStackTrace();
}
dd_ref.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, refList));
dd_ref.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
refr_no = String.valueOf(refList.get(position));
Log.i(LOG_TAG,refr_no);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public String loadJSONFromAssest() {
String json = " ";
try{
InputStream is = getAssets().open("ref.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
当我运行应用程序时,我收到以下错误
FATAL EXCEPTION: main
Process: com.example.accurat.application, PID: 7336
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.accurat.application/com.example.accurat.application.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2506)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5491)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.example.accurat.application.MainActivity.loadData(MainActivity.java:59)
at com.example.accurat.application.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:6270)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2506)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5491)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
以下是我调试的图片
错误位于refList.add(ref);
,因为它告诉refList
为空。
我坚持不懈,不知道怎么做。
任何帮助都将受到高度赞赏。
答案 0 :(得分:1)
试试这个
public void methodName() throws JSONException {
ArrayList<String> spinnerArray =new ArrayList<String>();
final JSONArray ja = new JSONObject(loadJSONFromAsset()).getJSONArray("reference");
for (int q = 0; q < ja.getJSONArray(0).length(); q++) {
//String name = ja.getJSONArray(0).getJSONObject(q).getString("Name");
String refNo = ja.getJSONArray(0).getJSONObject(q).getString("ref_no");
spinnerArray.add(refNo);
}
//set spinnerArray in spinner adapter
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = context_.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
答案 1 :(得分:1)
您可以通过将Gson Library添加到build.gradle
compile 'com.google.code.gson:gson:2.8.0'
//Create a model class
public class Reference
{
@SerializedName ("ref_no")
public String ref_no;
@SerializedName ("ref_no")
public String ref_no;
}
public void getListFromJsonFile()
{
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader("file_name.json"));
List<Reference> data = gson.fromJson(reader, new TypeToken<List<Review>>() {}.getType());
}
答案 2 :(得分:1)
要从assets
文件夹加载json文件,您可以使用以下方法:
public static JSONObject loadJsonObjectFromAsset(String assetName) {
try {
String json = loadStringFromAsset(assetName);
if (json != null)
return new JSONObject(json);
} catch (Exception e) {
Log.e("JsonUtils", e.toString());
}
return null;
}
private static String loadStringFromAsset(String assetName) throws Exception {
InputStream is = CraveApplication.getContext().getAssets().open(assetName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
然后致电:
JSONObject json = loadJsonObjectFromAsset("ref.json");
第二步是解析这个json对象并创建一个列表:
JSONObject json = loadJsonObjectFromAsset("ref.json");
List<String> refList = new ArrayList<>();
try {
JSONArray refArray = json.getJSONArray("reference");
for(int i = 0; i< refArray.length(); i++){
String ref = refArray.getJSONObject(i).getString("ref_no");
refList.add(ref);
}
} catch (JSONException e) {
e.printStackTrace();
}
最后一步是使用我们创建的新列表填充微调器:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_spinner_dropdown_item,
refList);
spinner.setAdapter(arrayAdapter);