basically I have some data stories in an API in JSON format.
I have managed to get the data from the JSON, loop through the, put them into a TextView, add onClick() on the textView.
but I want to be able to use the optical button on the phone to scroll, so I been told I need a ListView()
So I put the text I want into an array and added the array to the listView
As the example shows below But how do I add onClick for each Item and pass the ID (intStoryID)?????????
My Code Example
BufferedReader jsonBr = null;
ArrayList arrStoryList = null;
public void onCreate(Bundle savedInstancesState){
super.onCreate(savedInstancesState);
setContentView(R.layout.stories_main);
if(setTopStoryData()){
setStoriesArray();
buildPage();
}else{
// TODO add Error Handling
}
}
public boolean setTopStoryData(){
String strURL = "http://www.example.com/api/index.php?my=params";
JSONConn jsonConn = new JSONConn();
JSONConn.setURL(strURL);
if(jsonConn.setData()){
jsonBr = jsonConn.Br();
return true;
}else{
// my Error Handling
return false;
}
}
public void setStoriesArray(){
String line;
String strAddDate;
String strCurrentStatus;
String strStatusRead;
int intStoryID;
int intNumStories;
arrStoryList = new ArrayList();
JSONObject arrStories;
JSONObject arrAllStories;
JSONObject arrSingleStory;
try{
while((line = jsonBr.readLine()) != null){
arrStories = new JSONObject(line);
intNumStories = Integer.parseInt(arrStories.optString("NumStories"));
arrAllStories = arrStories.getJSONObject("StoryData");
if(intNumStories > 0){
for(int i = 0; i < intNumStories; i++){
arrSingleStory = arrAllStories.getJSONObject("Story"+i);
intStoryID = Integer.parseInt(arrSingleStory.getString("ID"));
strAddDate = arrSingleStory.getString("ADDEDDATE");
strCurrentStatus = arrSingleStory.getString("CURRENTSTATUS");
if(strCurrentStatus.equals("y")){
strStatusRead = "Online";
}else if(strCurrentStatus.equals("n")){
strStatusRead = "Offline";
}else{
strStatusRead = "Pending";
}
开发者_如何学CString strStoryText = strAddDate+" - " +strCurrentStatus;
arrStoryList.add(strStoryText));
} // end FOR loop
}
} //End while loop
} catch (IOException e) {
// TODO Auto-generated catch block
strDEBUG += "Error (2)";
} catch (JSONException e) {
// TODO Auto-generated catch block
strDEBUG += "Error (3) "+e.getLocalizedMessage()+"\n";
}
}
public void buildPage(){
if(this.arrStoryList != null){
ListView lv1 = (ListView)findViewById(R.id.listView1);
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,this.arrStoryList));
}
}
use onItemClickListener()
to the list view to get click event on each item
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
// do whatever you want here
}
});
精彩评论