简体   繁体   English

Android无法在应用程序中连接我的网络服务

[英]Android unable to connect my web-service in app

There must be a lot of questions regarding to mine. 关于我的肯定有很多问题。 But i couldn't find a good solution for it, so that's why i am posting a question. 但是我找不到一个好的解决方案,所以这就是为什么我要发布一个问题。

I have created a REST web-service using yii framework. 我已经使用yii框架创建了一个REST web-service Below is my code for the api 以下是我的api代码

class UsersController extends ActiveController
{
public $modelClass = 'app\models\Users';
public function actions()
{
    $actions = parent::actions();
    unset($actions['index']);
 return $actions;

}
public function actionIndex()
{
    $users = Users::find()->all();
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $users1['users'] = $users;
    return $users1;
}}

The result of my api is 我的api的结果是

{
"users": [
    {
        "Id": 1,
        "Name": "Faisal"
    },
    {
        "Id": 2,
        "Name": "Salman"
    },
    {
        "Id": 3,
        "Name": "Asim"
    },
    {
        "Id": 4,
        "Name": "Asad"
    },
    {
        "Id": 5,
        "Name": "Mateen"
    },
    {
        "Id": 6,
        "Name": "Omar"
    },
    {
        "Id": 7,
        "Name": "Usama"
    }
]}

For android part see below 对于android部分,请参见下文

Users.java Users.java

public class Users {

private String Id;
private String Name;

public String getId() {
    return Id;
}

public void setId(String id) {
    this.Id = id;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    this.Name = name;
}}

JSONfunctions.java JSONfunctions.java

public class JSONfunctions {


public static JSONObject getJSONfromURL(String url)
{
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity httpEntity = response.getEntity();
        is = httpEntity.getContent();
    } catch (ClientProtocolException e) {

        Log.e("log_tag", "Error in http connection " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Convert response to string

    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();
        result = sb.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("log_tag", "Error converting result " + e.toString());
        e.printStackTrace();
    }

    try {
        jArray = new JSONObject(result);

    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
        e.printStackTrace();
    }

    return jArray;
}}

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity {

JSONObject jsonObject;
JSONArray jsonArray;
ProgressDialog progressDialog;
ArrayList<String> userList;
ArrayList<Users> users;

TextView textViewResult;


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

    // Download JSON file AsyncTask
    new DownloadJSON().execute();
}


// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{

    /*@Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching Users....!");
        progressDialog.setCancelable(false);
        progressDialog.show();

    }*/
    @Override
    protected Void doInBackground(Void... params) {

        // Locate the Users Class
        users = new ArrayList<Users>();

        // Create an array to populate the spinner
        userList = new ArrayList<String>();
        // http://localhost:8000/app/web/users/
        // JSON file URL address
        jsonObject = JSONfunctions.getJSONfromURL("http://10.0.2.2:8000/app/web/users/");

        try
        {
            // Locate the NodeList name
            jsonArray = jsonObject.getJSONArray("users");

            for(int i=0; i<jsonArray.length(); i++)
            {
                jsonObject = jsonArray.getJSONObject(i);

                Users user = new Users();

                user.setId(jsonObject.optString("Id"));
                user.setName(jsonObject.optString("Name"));
                users.add(user);

                userList.add(jsonObject.optString("Name"));

            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void args)
    {
        // Locate the spinner in activity_main.xml
        Spinner spinner = (Spinner)findViewById(R.id.spinner);

        // Spinner adapter
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));

        // Spinner on item click listener

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                textViewResult = (TextView)findViewById(R.id.textView);

                // Set the text followed by the position

                textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                textViewResult.setText("");
            }
        });
    }


}}

Now when i run the app the expected result would be 现在,当我运行该应用程序时, 预期结果将是

在此处输入图片说明

But the actual result is 但是实际结果是

在此处输入图片说明

At logcat i am getting following warning logcat我得到以下警告

 org.json.JSONException: No value for users
 02-15 17:11:58.672 2158-2197/com.example.accurat.myapp W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:584)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at com.example.accurat.myapp.MainActivity$DownloadJSON.doInBackground(MainActivity.java:70)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at com.example.accurat.myapp.MainActivity$DownloadJSON.doInBackground(MainActivity.java:42)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.lang.Thread.run(Thread.java:818)

Hitting at the point jsonArray = jsonObject.getJSONArray("users"); 击中点jsonArray = jsonObject.getJSONArray("users");

Note: I am testing the results on emulator for now. 注意:我现在正在模拟器上测试结果。

Update 1 更新1

Sorry i forgot to mention, first i use a simple php file the code is bellow 对不起,我忘了提,首先我使用一个简单的php文件,代码如下

{"users":[{"Id":"1","Name":"Faisal"},{"Id":"2","Name":"Salman"},{"Id":"3","Name":"Asim"},{"Id":"4","Name":"Asad"},{"Id":"5","Name":"Mateen"},{"Id":"6","Name":"Omar"},{"Id":"7","Name":"Usama"}]}

My address was http://10.0.2.2:8000/MobileApp/index.php and it was working fine. 我的地址是http://10.0.2.2:8000/MobileApp/index.php ,它工作正常。 For security and easiness of mine i choose yii . 为了我的安全和方便,我选择yii

I must be missing something that i don't know 我一定想念我不知道的东西

Any help would be highly appreciated. 任何帮助将不胜感激。

Please change your code. 请更改您的代码。 Hope it helps 希望能帮助到你

 private class Task extends AsyncTask<JSONObject, Void, JSONObject>{
    @Override
    protected JSONObject doInBackground(JSONObject... params) {
        try {
            JSONParser json_parser = new JSONParser();
            json_object = json_parser.getJson(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json_object;
    }

    @Override
    protected void onPostExecute(JSONObject result){
        LoadEmployee(result);
    }
}

private class JSONParser {
    .....
    public JSONObject getJson(String url) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpget);
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            StringBuffer hasil = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                hasil.append(line);
            }
            json = hasil.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jObj;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM