我是android的新手,我的按钮是“myButton”,当我点击此按钮时,我想显示一个从MySQL服务器读取的ListView。我已经完成了如何从MySQL读取并在列表视图中显示的教程,但区别在于我想要一个按钮来激活并在我单击它时显示此列表视图。当我单击myButton时如何打开此列表视图? / p>
我还有一个Courses课,它只是我的设置和吸气剂。这是我尝试过的代码,并向我展示了一个ListView of Courses:
package usp.ac.fj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.Menu;
import android.widget.ArrayAdapter;
public class AndroidHttpActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_http);
String strJsonData = getJsonByHTTP();
// Convert String JSON data to Java class
ArrayList<Courses> arrayCourse= parseJsonData(strJsonData);
//Create an ArrayAdapter which shows the ArrayList data
this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_android_http, menu);
return true;
}
private String getJsonByHTTP() {
InputStream is = null;
try {
URL url = new URL("http://10.0.2.2/sqlWebService.php");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
if (is != null)
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
private ArrayList<Courses> parseJsonData(String strJson) {
ArrayList<Courses> Courses = new ArrayList<Courses>();
try {
// Generate JSONArray object by JSON String data
JSONArray arr = new JSONArray(strJson);
//from the JSONArray, get one element (row) of JSONData
for (int i = 0; i < arr.length(); i++) {
//Get JSON Object which is one element of the array
JSONObject ob = arr.getJSONObject(i);
Courses course = new Courses();
//get the value by key, and set to cour class
course.setCode(ob.optString("code"));
//save courses class to course array list
Courses.add(course);
}
} catch (JSONException e) {
e.printStackTrace();
}
return Courses;
}
}