gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:53:07 25 4
gpt4 key购买 nike

肯定有很多关于我的问题。但我找不到一个好的解决方案,所以这就是我发布问题的原因。

我使用 yii 框架创建了一个 REST Web 服务。下面是我的 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;
}}

我的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"
}
]}

Android部分见下文

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

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

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("");
}
});
}


}}

现在,当我运行应用程序时,预期结果将是

enter image description here

但是实际结果是

enter image description here

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)

击中点jsonArray = jsonObject.getJSONArray("users");

注意:我现在正在模拟器上测试结果。

更新1

抱歉我忘了提及,首先我使用一个简单的 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"}]}

我的地址是http://10.0.2.2:8000/MobileApp/index.php并且工作正常。为了安全和方便,我选择 yii

我一定错过了一些我不知道的东西

任何帮助将不胜感激。

最佳答案

请更改您的代码。希望对您有帮助

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

关于java - Android 无法在应用程序中连接我的网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42249328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com