- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
肯定有很多关于我的问题。但我找不到一个好的解决方案,所以这就是我发布问题的原因。
我使用 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("");
}
});
}
}}
现在,当我运行应用程序时,预期结果将是
但是实际结果是
在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/
我通过 spring ioc 编写了一些 Rest 应用程序。但我无法解决这个问题。这是我的异常(exception): org.springframework.beans.factory.BeanC
我对 TestNG、Spring 框架等完全陌生,我正在尝试使用注释 @Value通过 @Configuration 访问配置文件注释。 我在这里想要实现的目标是让控制台从配置文件中写出“hi”,通过
为此工作了几个小时。我完全被难住了。 这是 CS113 的实验室。 如果用户在程序(二进制计算器)结束时选择继续,我们需要使用 goto 语句来到达程序的顶部。 但是,我们还需要释放所有分配的内存。
我正在尝试使用 ffmpeg 库构建一个小的 C 程序。但是我什至无法使用 avformat_open_input() 打开音频文件设置检查错误代码的函数后,我得到以下输出: Error code:
使用 Spring Initializer 创建一个简单的 Spring boot。我只在可用选项下选择 DevTools。 创建项目后,无需对其进行任何更改,即可正常运行程序。 现在,当我尝试在项目
所以我只是在 Mac OS X 中通过 brew 安装了 qt。但是它无法链接它。当我尝试运行 brew link qt 或 brew link --overwrite qt 我得到以下信息: ton
我在提交和 pull 时遇到了问题:在提交的 IDE 中,我看到: warning not all local changes may be shown due to an error: unable
我跑 man gcc | grep "-L" 我明白了 Usage: grep [OPTION]... PATTERN [FILE]... Try `grep --help' for more inf
我有一段代码,旨在接收任何 URL 并将其从网络上撕下来。到目前为止,它运行良好,直到有人给了它这个 URL: http://www.aspensurgical.com/static/images/a
在过去的 5 个小时里,我一直在尝试在我的服务器上设置 WireGuard,但在完成所有设置后,我无法 ping IP 或解析域。 下面是服务器配置 [Interface] Address = 10.
我正在尝试在 GitLab 中 fork 我的一个私有(private)项目,但是当我按下 fork 按钮时,我会收到以下信息: No available namespaces to fork the
我这里遇到了一些问题。我是 node.js 和 Rest API 的新手,但我正在尝试自学。我制作了 REST API,使用 MongoDB 与我的数据库进行通信,我使用 Postman 来测试我的路
下面的代码在控制台中给出以下消息: Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child el
我正在尝试调用一个新端点来显示数据,我意识到在上一组有效的数据中,它在数据周围用一对额外的“[]”括号进行控制台,我认为这就是问题是,而新端点不会以我使用数据的方式产生它! 这是 NgFor 失败的原
我正在尝试将我的 Symfony2 应用程序部署到我的 Azure Web 应用程序,但遇到了一些麻烦。 推送到远程时,我在终端中收到以下消息 remote: Updating branch 'mas
Minikube已启动并正在运行,没有任何错误,但是我无法 curl IP。我在这里遵循:https://docs.traefik.io/user-guide/kubernetes/,似乎没有提到关闭
每当我尝试docker组成任何项目时,都会出现以下错误。 我尝试过有和没有sudo 我在这台机器上只有这个问题。我可以在Mac和Amazon WorkSpace上运行相同的容器。 (myslabs)
我正在尝试 pip install stanza 并收到此消息: ERROR: No matching distribution found for torch>=1.3.0 (from stanza
DNS 解析看起来不错,但我无法 ping 我的服务。可能是什么原因? 来自集群中的另一个 Pod: $ ping backend PING backend.default.svc.cluster.l
我正在使用Hibernate 4 + Spring MVC 4当我开始 Apache Tomcat Server 8我收到此错误: Error creating bean with name 'wel
我是一名优秀的程序员,十分优秀!