【问题标题】:Creating a drop down menu from a .json file从 .json 文件创建下拉菜单
【发布时间】:2016-11-07 01:34:40
【问题描述】:
package com.example.root.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button btnCommercial;

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

        final ListView list11 = (ListView) findViewById(R.id.listView1);
        ArrayList<String> authorities = getAuthorities("AuthorityList.json");
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, authorities);
        btnCommercial = (Button) findViewById(R.id.btnCommercial);
        btnCommercial.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        list11.setAdapter(adapter);
                    }
                });
    }

    private ArrayList<String> getAuthorities(String fileName) {
        JSONArray jsonArray = null;
        ArrayList<String> AuthList = new ArrayList<String>();

        try {
            InputStream inputStream = getAssets().open(fileName);       //open the inputStream to the file
            int size = inputStream.available();                         //size of the entire json object
            byte[] data = new byte[size];                               //array that will store all the data
            inputStream.read(data);                                     //reading data into the array for the file
            inputStream.close();                                        //close the input steam
            String json = new String(data, "UTF-8");
            jsonArray = new JSONArray(json);

            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    AuthList.add(jsonArray.getJSONObject(i).getString("description"));
                }
            }
        } catch (IOException e) {
            e.printStackTrace(); return null;
        } catch (JSONException je) {
            je.printStackTrace(); return null;
        }
        return AuthList;
    }
}

我想使用我项目中的 JSON 文件中的数据创建一个下拉菜单。我正在努力通过soapui访问我的远程服务器,所以我将.json文件复制到我的资产下的项目中。该代码没有给我错误,但我的应用程序不会运行。我认为问题在于我如何打开 .json 文件或如何访问对象。

提前谢谢你。

【问题讨论】:

  • 什么意思,应用程序无法运行?它是否因异常而崩溃,或者您的列表未填充?如果崩溃,请发布您的 LogCat。
  • 对不起,我的意思是它不会做我想做的事,即创建下拉菜单并用 .json 文件中的内容填充它。
  • 当我创建一个普通的字符串数组时,当我按下按钮时它会创建下拉菜单。发现在一般的android中调试非常困难..
  • 不确定如何添加我的 logcat..
  • 尝试使用转换器将 json 转换为 POJO 类,然后从中生成一个简单的数组

标签: android json spinner assets


【解决方案1】:

您可以尝试以下函数为您的 JSON 文件获取字符串。

public static String AssetJSONFile (String filename, Context context) throws IOException {
        AssetManager manager = context.getAssets();
        InputStream file = manager.open(filename);
        byte[] formArray = new byte[file.available()];
        file.read(formArray);
        file.close();

        return new String(formArray);
    }

然后解析它。 如果您的数据足够大,我建议使用一些库(如 LoganSquare 或 Jackson)来解析 JSON 数据。

【讨论】:

    【解决方案2】:

    您必须确保您的应用从 Json 文件中正确读取。以下是工作代码:

    package com.example.a386019.spinnerjson;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    
    public class SpinnerActivity extends AppCompatActivity {
    
    String json_string;
    JSONObject jsonObj;
    JSONArray jsonArray;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        json_string= loadJSONFromAsset();
    
        ArrayList<String> messages = new ArrayList<String>();
    
        {
    
            try {
                jsonObj =new JSONObject(json_string);
                jsonArray =jsonObj.getJSONArray("formules");
                String formule,url;
                for (int i = 0; i < jsonArray.length(); i++){
                    JSONObject jObj = jsonArray.getJSONObject(i);
                    formule= jObj.getString("formule");
                    messages.add(formule);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
    
        }
    
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, messages);
    
        Spinner spinner = (Spinner)findViewById(R.id.spinner);
        spinner.setAdapter(adapter);
    
    }
    
    
    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("formules.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;
    }
    }
    

    和布局:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.a386019.spinnerjson.SpinnerActivity">
    
    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42dp" />
    </RelativeLayout>
    

    和资产文件夹中的json文件:

      {
        "formules": [
                {
        "formule": "Linear Motion",
    
    },
    {
      "formule": "Constant Acceleration Motion",
    
    },
    {
      "formule": "Projectile Motion",
    
    },
    {
      "formule": "Force",
    
    },
    {
      "formule": "Work, Power, Energy",
    
    },
    
    ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2012-07-20
      相关资源
      最近更新 更多