使用json查询和php填充android微调器

时间:2016-04-26 08:11:22

标签: php android json android-spinner

我正在尝试用一些数据(不同位置的名称)填充一个微调器,我已经存储在phpMyAdmin数据库中。

主要活动是:

    package com.example.transgoods;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class StartActivity extends Activity implements OnItemSelectedListener {

    private Button btnPopulate, btnNext;
    private Spinner pointSpinner;

    private ArrayList<POI> POIList;
    ProgressDialog pDialog;

    private String url_list_poi ="http://10.0.2.2/listpoi.php";

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

        Button btnNext = (Button) findViewById(R.id.btnStartNext);
        Button btnPopulate = (Button) findViewById(R.id.btnPopulate);

        final Intent endActivity= new Intent(this, EndActivity.class);


        pointSpinner = (Spinner) findViewById(R.id.point_spinner);

        POIList = new ArrayList<POI>();

        pointSpinner.setOnItemSelectedListener(this);
        btnPopulate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new GetPOI().execute();

            }
            /** async tast to get all poi
             * 
             * @author pavloselp
             *
             */
            class GetPOI extends AsyncTask<Void, Void, Void>{

                protected void onPreExecute(){
                    super.onPreExecute();
                    pDialog = new ProgressDialog(StartActivity.this);
                    pDialog.setMessage("fetching poi list");
                    pDialog.setCancelable(false);
                    pDialog.show();
                }

                @Override
                protected Void doInBackground(Void... arg0) {
                    // TODO Auto-generated method stub
                    ServiceHandler jsonParser = new ServiceHandler();
                    String json = jsonParser.makeServiceCall(url_list_poi, ServiceHandler.GET);

                    Log.e("Response: ",">"+json );

                    if(json != null){
                        try{
                            JSONObject jsonObj = new JSONObject(json);
                            if (jsonObj != null){
                                JSONArray poiArray = jsonObj.getJSONArray("POI");

                                for(int i=0;i<poiArray.length();i++){
                                    JSONObject poiObj = (JSONObject) poiArray.get(i);
                                    POI poi = new POI (poiObj.getInt("poiID"), poiObj.getString("poiName"));
                                    POIList.add(poi);
                                    Log.i( "POI List is:", POIList.toString());}
                            }
                        }catch(JSONException e){
                            e.printStackTrace();
                        }
                    }else{
                        Log.e("JSON data", "didnt receive any data from server!");
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    populateSpinner();
                }

                //adding spinner data

                private void populateSpinner(){
                    List<String> lables = new ArrayList<String>();

                    for(int i = 0;i < POIList.size(); i++){
                        lables.add(POIList.get(i).getName());
                    }

                    //creating adapter for spinner
                    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(StartActivity.this , android.R.layout.simple_spinner_item, lables);
                    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                    pointSpinner.setAdapter(spinnerAdapter);
                }
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub
        Toast.makeText(
                getApplicationContext(),
                        parent.getItemAtPosition(position).toString() + " Selected" ,
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
}

php文件:

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password="root"; //replace with database password 
$db_name="TransGoods"; //replace with database name

$mysqli = new mysqli($host, $username, $password,$db_name);
if (mysqli_connect_error()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
        }       

        $mysqli->query("SET NAMES 'utf8'");
        $sql="SELECT poiID, poiName FROM POI";
        $result=$mysqli->query($sql);
        while($e=mysqli_fetch_assoc($result)){
        $output[]=$e; 
        }   

        print(json_encode($output)); 
        $mysqli->close();
?>

我收到此错误

    04-26 04:00:35.012: W/System.err(2371): org.json.JSONException: Value [{"poiName":"Limassol old port","poiID":"2"},{"poiName":"larnaca 

port","poiID":"7"},{"poiName":"paphos port","poiID":"8"}] of type 

org.json.JSONArray cannot be converted to JSONObject

1 个答案:

答案 0 :(得分:0)

从服务器获取JsonArray,但解析为对象。

我修改了你的代码,现在就试试。

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                ServiceHandler jsonParser = new ServiceHandler();
                String json = jsonParser.makeServiceCall(url_list_poi, ServiceHandler.GET);

                Log.e("Response: ",">"+json );

                if(json != null){
                    try{
                        JSONArray poiArray = new JSONArray (json);
                        if (poiArray!= null){
                            for(int i=0;i<poiArray.length();i++){
                                JSONObject poiObj = (JSONObject) poiArray.get(i);
                                POI poi = new POI (poiObj.getInt("poiID"), poiObj.getString("poiName"));
                                POIList.add(poi);
                                Log.i( "POI List is:", POIList.toString());
                               }
                        }
                    }catch(JSONException e){
                        e.printStackTrace();
                    }
                }else{
                    Log.e("JSON data", "didnt receive any data from server!");
                }



                return null;
            }