我正在尝试从MySql服务器获取数据并将其显示在我的列表视图中。
Parser.java
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
String arr[];
ArrayList<String> players=new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parser");
pd.setMessage("Parsing ....Please wait");
pd.show();
}
@Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter=new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1,players);
//ADAPT TO LISTVIEW
lv.setAdapter(adapter);
//LISTENET
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(c,players.get(position), Toast.LENGTH_LONG).show();
//Snackbar.make(view,players.get(position),Snackbar.LENGTH_LONG).show();;
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray ja=new JSONArray(data);
//CREATE JO OBJ TO HOLD A SINGLE ITEM
JSONObject jo=null;
players.clear();
//LOOP THRU ARRAY
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
//RETRIEVE NAME
String name=jo.getString("Name");
//ADD IT TO OUR ARRAYLIST
players.add(name);
jo = ja.getJSONObject(i);
String pposition = jo.getString("Position");
arr[i] = pposition;
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
MainActivity.java
public class MainActivity extends Activity {
String url="http://bookvilla.esy.es/book.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView lv= (ListView) findViewById(R.id.lv);
final Downloader d=new Downloader(this,url,lv);
d.execute();
}
}
我想提一件事,当我尝试仅取“名称”时,它的工作完美......但是当我添加这些行时:
jo = ja.getJSONObject(i); String pposition = jo.getString(“Position”); arr [i] = pposition;
异常开始出现
请帮助。