来自JSON数组的android spinner选项

时间:2014-09-18 13:39:23

标签: android json spinner android-spinner android-adapter

我试图从从外部URL获取的JSON字符串填充android微调器数据。字符串被正确获取并成功转换为数组。但是微调器输出是空白的。

提前致谢。

以下是代码:

JSON

{"bgroup":[
    {"id":"1","name":"A+"},
    {"id":"2","name":"B+"},
    {"id":"3","name":"AB+"},
    {"id":"4","name":"O+"},
    {"id":"5","name":"A-"},
    {"id":"6","name":"B-"},
    {"id":"7","name":"AB-"},
    {"id":"8","name":"O-"},
]}

布局XML:

<Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bgrp_spinner"
        android:layout_below="@+id/textView4"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp" />

MainActivity.java

package com.example.bapps_v1.b;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import static com.google.android.gms.common.GooglePlayServicesUtil.showErrorDialogFragment;


public class MainActivity extends Activity {
    StrictMode.ThreadPolicy npolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();


    private String URL_GROUP = "http://127.0.0.1/test/blood_api/group.php";
    InputStream is;
    private static String presult = "";
    private static String tempstr = "";
    ArrayList<String> bgrpList;


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

        Intent intent = getIntent();
        Bundle AREQUEST = intent.getExtras();
        StrictMode.setThreadPolicy(npolicy);
        JSONObject jsonResponse;


        bgrpList = new ArrayList<String>();




        try{
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("rmail","blank"));
            nameValuePairs.add(new BasicNameValuePair("rpass","blank"));
            try {
                InetAddress i = InetAddress.getByName(URL_GROUP);
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            }
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL_GROUP);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (ClientProtocolException e) {
            Log.e("log_tag", "Error ClientProtocolException:  "+e.toString());
        } catch (IOException e) {
            Log.e("log_tag", "Error IOException: "+e.toString());
        }


        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();

            presult= sb.toString();

            try{
                jsonResponse = new JSONObject(presult);
                JSONArray jsonMainNode = jsonResponse.optJSONArray("bgroup");
                int lengthJsonArr = jsonMainNode.length();


                for(int i=0; i < lengthJsonArr; i++)
                {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    bgrpList.add(jsonChildNode.optString("name").toString());
                }

                Spinner mySpinner = (Spinner) findViewById(R.id.bgrp_spinner);
                mySpinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        bgrpList));

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item ,bgrpList);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerBlood.setAdapter(adapter);

            }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
                e.printStackTrace();
            }



        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void MapsActivity(View view) {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        try {
            if (status == ConnectionResult.SUCCESS) {
                Intent intent = new Intent(this, MapsActivity.class);
                startActivity(intent);
            } else {
                //boolean errdg= showErrorDialogFragment (status, this, int requestCode);

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Play services not installed/out of date")
                        .setTitle(R.string.alert);


                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked OK button
                    }
                });
                AlertDialog alert11 = builder.create();
                alert11.show();
            }
        }
        catch(Exception e)
        {
            Log.e("Error: GooglePlayServiceUtil: ", "" + e);
        }

    }
}

使用空白微调器的0utput屏幕截图


0utput screenshot with blank spinner

1 个答案:

答案 0 :(得分:0)

这些是问题:

<强> 1。 JSON中没有新的行/标签:(JSONObject失败)

{"bgroup":[{"id":"1","name":"A+"},{"id":"2","name":"B+"},{"id":"3","name":"AB+"},{"id":"4","name":"O+"},{"id":"5","name":"A-"},{"id":"6","name":"B-"},{"id":"7","name":"AB-"},{"id":"8","name":"O-"}]}

<强> 2。本地IP: Ahost中的InetAddress无法使用localhost /本地IP(即使已使用httppost进行检查)