对我来说一定有很多问题。但我无法找到一个好的解决方案,所以这就是我发帖的原因。
我使用REST web-service
框架创建了yii
。以下是我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
。
我一定错过了一些我不知道的东西
任何帮助都将受到高度赞赏。
答案 0 :(得分:1)
请更改您的代码。希望它有所帮助
<ListBox ItemsSource="{Binding ListBoxItemsSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="PreviewMouseDown"
Handler="ItemOnPreviewMouseDown" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
private void ItemOnPreviewMouseDown(
object sender, MouseButtonEventArgs e)
{
((ListBoxItem) sender).IsSelected = true;
}