将json feed中的项添加到操作栏微调器

时间:2014-02-11 10:18:39

标签: android json android-spinner

我在操作栏微调器上遇到问题。我通过添加静态数组中的项来成功创建了微调器。

现在我想从json feed而不是这个添加动态项到微调器。

我可以将数组中的静态项添加到微调器,但是不知道如何将项添加到我从json feed获取的微调器。我已经成功下载了json,但问题是如何将这个下载的json添加到spinner。

请提供帮助。

MainActivity

public class MainActivity extends Activity implements
        ActionBar.OnNavigationListener {


    private ActionBar actionBar;


    private ArrayList<SpinnerNavItem> navSpinner;


    private TitleNavigationAdapter adapter;

    public MenuItem refreshMenuItem;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        setContentView(R.layout.activity_main);

        actionBar = getActionBar();


        actionBar.setDisplayShowTitleEnabled(false);


        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        navSpinner = new ArrayList<SpinnerNavItem>();
        navSpinner.add(new SpinnerNavItem("News", R.string.color));
        navSpinner.add(new SpinnerNavItem("nate", R.string.color));
        navSpinner.add(new SpinnerNavItem("Home", R.string.color));
        navSpinner.add(new SpinnerNavItem("Admin", R.string.color));
        navSpinner.add(new SpinnerNavItem("Pol", R.string.color));
        navSpinner.add(new SpinnerNavItem("Sunday", R.string.color));


        adapter = new TitleNavigationAdapter(getApplicationContext(),
                navSpinner);


        actionBar.setListNavigationCallbacks(adapter, this);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main_actions, menu);

        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

        case R.id.refresh:
            // refresh
            refreshMenuItem = item;



            new SyncData().execute();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        // Action to be taken after selecting a spinner item
        if (itemPosition == 1) {
            Intent i = new Intent(getApplicationContext(),Test.class);
            startActivity(i);

        }
        return true;
    }


    public class SyncData extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            // set the progress bar view

            refreshMenuItem.expandActionView();

        }

        @Override
        protected String doInBackground(String... params) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            refreshMenuItem.collapseActionView();
            // remove the progress bar view
            refreshMenuItem.setActionView(null);
        }
    };


}

提前致谢。

1 个答案:

答案 0 :(得分:0)

我创建了demo:;)

MainActivity.java

public class MainActivity extends Activity implements OnNavigationListener{

    JSONObject jsonObject = null;

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    class Task extends AsyncTask<Void, Integer, JSONObject> {

        ArrayList<String> stringArray;

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            super.onPostExecute(jsonObject);

            try {
                JSONArray array = jsonObject.getJSONArray("sections");
                ArrayList<String> stringArray = new ArrayList<String>();
                for(int i=0;i<array.length();i++){
                    stringArray.add(array.getJSONObject(i).getString("section_name"));
                    Log.d("msg", ""+array.getJSONObject(i).getString("section_name"));
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, stringArray);
                ActionBar actionBar = getActionBar();
                actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
                actionBar.setDisplayShowTitleEnabled(false);
                actionBar.setListNavigationCallbacks(adapter, MainActivity.this);

            } catch (JSONException e) {
                Log.d("msg", e.getLocalizedMessage());

            }
        }

        @Override
        protected JSONObject doInBackground(Void... params) {
            // TODO Auto-generated method stub
            String url = "http://itk.thehill.com/android/get_sections";
            jsonObject = JSONParser.getJSON(url);
            return jsonObject;
        }

    }


    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        // TODO Auto-generated method stub
        return false;
    }
}

JSONParser.java:

public class JSONParser {

    static InputStream is;
    static String result;
    static JSONObject jsonObject;

    static HttpClient httpClient;
    static HttpPost httpPost;

    static List<NameValuePair> pairs;

    static HttpResponse response;
    static HttpEntity entity;

    public static boolean checkConnection(Context context)
    {

        final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connMgr != null && (connMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) ||(connMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED))
        {
            return true;
        }             
        return false;
    }

    private static void init() {
        // TODO Auto-generated constructor stub
        is = null;
        result = "";
        jsonObject = null;
        httpPost = null;
        httpClient = new DefaultHttpClient();
    }

    private static String getResult(InputStream is)  {
        // TODO Auto-generated method stub
        BufferedReader reader;
        StringBuilder stringBuilder = null;

        try {
            reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

            stringBuilder = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            is.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stringBuilder.toString();    
    }

    public static JSONObject getJSON(String url) {
        // TODO Auto-generated method stub

        try{
            init();

            httpPost = new HttpPost(url.toString());

            Log.d("msg", "post : "+httpPost);

            response = httpClient.execute(httpPost);
            Log.d("msg", "res : "+response.getStatusLine().getStatusCode());

            entity = response.getEntity();
            is = entity.getContent();

            Log.d("msg", ""+is);

            /* Convert response to string */
            result = getResult(is);
            Log.d("msg", "Result : "+result);

            jsonObject = new JSONObject(result);

        }
        catch(ClientProtocolException e){
            Log.e("log_tag", "Error in Client Protocol : "+e.toString());
        }catch(JSONException e){
            Log.e("log_tag", "Error Parsing data "+e.toString());
        }catch(Exception e){
            Log.e("log_tag", "Error in HTTP Connection : "+e.toString());
        }
        return jsonObject;
    }
}

它看起来像:

You output

只需要为ICON做代码:)