I'm working on an Android app with some API i made on my own. I'm almost done but i can't find the way to put the data i get inside my async task (the one who's getting my json data) inside my dynamic spinner.
Here is my code :
String example;
static final String API_URL2 = "https://xxxxxxxx.xx";
//Start Used for spinner with different value and display
String[] textfordropdown = { "A",
"B",
"C",
};
String[] valueofdropdowtext =
{ "1",
"2",
"3",
};
Spinner spinnerdynamic;
OnCreate i've called my async task to see if i get something displayed so yeah it works :
new GetList().execute();
and i also create my spinner here
spinnerdynamic = (Spinner)findViewById(R.id.dynamic_spinner);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, textfordropdown);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerdynamic.setAdapter(adapter1);
spinnerdynamic.setOnItemSelectedListener(onItemSelectedListener1);
Here is the function onItemSelectedListener1:
OnItemSelectedListener onItemSelectedListener1 =
new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
example = String.valueOf(valueofdropdowtext[position]);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
And here my async task :
class GetList extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL2);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "Une erreur c'est produite";
}
Log.i("INFO", response);
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
JSONArray prestationlist = object.getJSONArray("WhatIWant");
//Permet de compter le nombre d'éléments dans le json array
int arrSize = prestationlist.length();
ArrayList<String> value = new ArrayList<String>(arrSize);
ArrayList<String> name = new ArrayList<String>(arrSize);
for(int i=0;i<arrSize;i++) {
object = prestationlist.getJSONObject(i);
value.add(object.getString("Value"));
name.add(object.getString("Text"));
//Here i've made some display to see if it works, i get the data.
responseView.setText(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So how can i put my data inside the String[] textfordropdown or valueofdropdowntext ?
Thanks a lot !
Create a string array list and initialize it at the top of file
And use that arraylist in your spinner
adapter1 =
new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, yourarraylist);
And add your values into that array list in your onPostExecute method
for(int i=0;i<arrSize;i++) {
object = prestationlist.getJSONObject(i);
value.add(object.getString("Value"));
name.add(object.getString("Text"));
//Here i've made some display to see if it works, i get the data.
yourarraylist.add(object.getString("Text"));
responseView.setText(value.toString());
}
adapter1.notifyDataSetChanged();
Note: You need to initialize spinner adapter also at the top of the file
Related
I tried many ways but I got blank layout.I changed lots of lines but the result is always the same. Should I rewrite the code and try something different. I followed some videos on youtube but nobody has the proper solution.I don't think it is caused because array got null result. Anybody knows what might be wrong:
AirportTransportActivity
public class AirportTransportActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data = new String[0];
JSONObject jsonObject = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
//Adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}
In your original post you have set the adapter before you have added the data. But I also suspect that you are having issues with:
String[] data = new String[0];
So I changed it to
ArrayList<String> data = new ArrayList<>();
I also changed your AsyncTask a bit. Now you can do most of your parsing in the background thread. When the doInBackground is successful just notify the adapter of the changes in onPostExecute.
You will also need to check if the ArrayList<String> fits to your Adapter class. If not just change it as needed.
Do this instead:
public class AirportTransportActivity extends AppCompatActivity {
private static final String TAG = AirportTransportActivity.class.getSimpleName();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return toString();
}
#Override
protected void onPostExecute(String result) {
if(result.isEmpty()) return;
try{
ArrayList<String> data = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
JSONArray jsonArray = new JSONArray(result);
int len = jsonArray.length();
Log.e(TAG, "Lenth of json array = " + len)
for (int i = 0; i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// I add the optString variation just in case the data is corrupt
String s = jsonObject.optString("airporttransportname", "?");
data.add(s);
}
listView.setAdapter(adapter);
}
catch(JSONException e){
e.printStackTrace();
}
}
}
Disclaimer I did this in a text editor and wasn't able to count on "auto-correct" for some of the syntax or method names--so you will need to check it.
There are some other things I would change in your code, but I wanted to leave it as close to the original as I could.
You're setting the data array and calling notifyDataSetChanged() before your async task has a chance to finish. You need to set your adapter and notifyDataSetChanged() from within the onPostExecute() method in your async task.
Just to be clear, when you call asyncTask.execute(), it starts the async task and then immediately keeps executing the rest of the code. So when you set your data array in your list view adapter, the asyncTask hasn't even finished and your array items are still null.
No need to change anything just add adapter.notifyDataSetChanged(); after storing all values into your array
Remove this line adapter.notifyDataSetChanged();in Oncreate ,You
have to use notifyDataSetChanged() when your arraylist values is getting
changed.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
I have a spinner that gets populated from a text file stored on a web server. The contents of this text file are then stored in an ArrayList. My app is going to have the user add an item to this text file that they name themselves and therefore update the spinner. What I need to be able to do is have the spinner do something when an item is selected. As the user can give any name to an item they add, how can my app do something when that particular item is selected from the spinner if it doesn't know what they named it?
Right now I have my app set up so that if spinner item equals "string" do this... but this obviously won't work if the user has named an item themselves. I hope I have explained my question ok! This is my code so far:
public class MainActivity extends AppCompatActivity {
String statusLink = "http://redacted.uk/pmt/status.txt";
String deviceLink = "http://redacted.uk/pmt/devices.txt";
String status;
final String degree = "\u00b0";
ArrayList<String> devicesAL = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Set up connection to device.txt on web server
URL deviceUrl = new URL (deviceLink);
URLConnection deviceConn = deviceUrl.openConnection();
deviceConn.setDoOutput(true);
deviceConn.connect();
InputStream dis = deviceConn.getInputStream();
InputStreamReader disr = new InputStreamReader(dis, "UTF-8");
BufferedReader dbr = new BufferedReader(disr);
String deviceLine;
// Set up connection to status.txt on web server
URL statusUrl = new URL(statusLink);
URLConnection statusConn = statusUrl.openConnection();
statusConn.setDoOutput(true);
statusConn.connect();
InputStream sis = statusConn.getInputStream();
InputStreamReader sisr = new InputStreamReader(sis, "UTF-8");
BufferedReader sbr = new BufferedReader(sisr);
String statusLine;
try {
while ((deviceLine = dbr.readLine()) != null) {
//System.out.println(deviceLine);
devicesAL.add(deviceLine);
for (String str : devicesAL) {
System.out.println(str);
}
}
while ((statusLine = sbr.readLine()) != null) {
System.out.println(statusLine);
status = statusLine;
System.out.println("Status = " + status);
TextView output = (TextView) findViewById(R.id.textView);
System.out.println(status);
}
for (String str : devicesAL) {
System.out.println(str);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//LOAD SPINNER
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adp = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, devicesAL);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
adp.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView output = (TextView) findViewById(R.id.textView);
if (parent.getItemAtPosition(position).equals("Water Cooler")) {
System.out.println("Water cooler selected");
output.setText(status);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
} finally {
sbr.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
Since you say you want to :
If the user then selects "fridge" from the spinner, the data inside fridge.txt gets displayed
So i think you can just get the file name from the spinner then show the content. It will be like this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedFileName = parent.getItemAtPosition(position);
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, selectedFileName+".txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {}
TextView tvText = (TextView)findViewById(R.id.tvText);
tvText.setText(text.toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I'm trying to populate an ArrayList of objects and use those objects to populate a ListView. My Asynctask can get the json data and I can parse it and make the objects I need but my ListView doesn't populate. When I check to see if my ArrayList has any object in it before the adapter runs I can see that it doesn't. I want to know why my ListView isn't populating.
Here's my code: (Sorry if it's messy, some spots I haven't gotten to updating yet)
public class MovieDisplayFragment extends Fragment{
private ArrayList<Movie> movieList = new ArrayList<Movie>();
private MovieAdapter movieAdapter;
ListView listView;
public MovieDisplayFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieAdapter = new MovieAdapter(getActivity(), movieList);
listView = (ListView) rootView.findViewById(R.id.listview_data);
listView.setAdapter(movieAdapter);
if(movieList.size() > 0) {
Log.e("Hello", "1");
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
Movie movie = movieAdapter.getItem(position);
Intent i = new Intent(getActivity(), DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT, "Hello");
startActivity(i);
}
});
return rootView;
}
private void updateMovieData(){
getMovieData movieData = new getMovieData();
movieData.execute();
}
#Override
public void onStart(){
super.onStart();
updateMovieData();
}
public class getMovieData extends AsyncTask<Void, Void, List<Movie>> {
private final String LOG_CAT = getMovieData.class.getSimpleName();
private List<Movie> getMovieData(String movieJsonStr) throws JSONException {
final String MOV_ITEMS = "results";
final String MOV_TITLE = "original_title";
final String MOV_DATE = "release_date";
final String MOV_SYNOPSIS = "overview";
final String MOV_VOTE = "vote_average";
final String MOV_POSTER_URL = "poster_path";
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieArray = movieJson.getJSONArray(MOV_ITEMS);
Log.e("Hello", "2");
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
movieList.add(new Movie(movie.getString(MOV_TITLE), movie.getString(MOV_DATE),
movie.getString(MOV_SYNOPSIS), movie.getString(MOV_VOTE), movie.getString(MOV_POSTER_URL)));
}
return movieList;
}
protected List<Movie> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr = null;
try {
final String BASE_URL = "http://api.themoviedb.org/3/genre/10751/movies?api_key=358f3b44734f7e6404f2d01a62d3c176&include_all_movies=true&include_adult=true";
Uri builtUri = Uri.parse(BASE_URL).buildUpon().build();
URL url = new URL(builtUri.toString());
Log.v(LOG_CAT, "Built URI " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null){
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0){
movieJsonStr = buffer.toString();
}
movieJsonStr = buffer.toString();
Log.v(LOG_CAT, "Movie String: " + movieJsonStr);
} catch (IOException e) {
Log.e("Fragment", "Error", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
return getMovieData(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG_CAT, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Movie> movies){
if(movies != null){
movieAdapter.clear();
for(Movie movieData : movies){
movieAdapter.add(movieData);
}
}
}
}
}
Put these 2 lines inside your onPostExecute() in Async.
movieAdapter = new MovieAdapter(getActivity(), movieList);
listView.setAdapter(movieAdapter);
AsyncTask runs in Background Thread. It gets the data from json after few seconds. But your adapter is called few milli seconds after your fragment is created.
So the data from the Json will not be there when you are setting the adapter.
Calling it in onPostExecute solves this problem as the adatpter is set after Json data is retrieved from the server!
Hope it helps a bit.
You are printing size of movieList (movieList.size()) much before movieList() is getting populated. It will never print "Hello" "1" in debugger. The asynctask will fill data in movieList much later than your movieList.size() check code in OnCreateView()
Anyways, after the below code
for(Movie movieData : movies)
{
movieAdapter.add(movieData);
}
you need to insert this bit:
listView.setAdapter(movieAdapter);
You are populating the adapter but not setting it to your listView in your onPostExecute() in your getMovieData Asynctask.
It looks like on post execute you are clearing the List that your adapter is using to populate the listview, then adding in new items to the list. However, in order to update the view after that happens, you need to call notifyDataSetChanged(); after updating the list
#Override
protected void onPostExecute(List<Movie> movies){
if(movies != null){
movieAdapter.clear();
for(Movie movieData : movies){
movieAdapter.add(movieData);
}
movieAdapter.notifyDataSetChanged();
}
}
I'm trying to load JSON from a URL in an Android app (the URL only links to JSON data, there is nothing else).
For now I'm only trying to load the content of the URL into a String.
The problem I have is that I need to handle the Exceptions, but I'm not too familiar with that.
Here is the relevant part of my 'Functions' class:
static public String loadURL(String inputURL) throws Exception {
String fullString = "";
URL url = new URL(inputURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
This is what I'm currently using (in a different class) for testing purposes:
Toast.makeText(Setup.this, Functions.loadURL("http://www.exampleJSON.com"), Toast.LENGTH_LONG).show();
I'm planning on using the output to extract JSON data for if-statements, saving in sharedPreferences and displaying.
EDIT
Here what I'm using to call the method:
public class Setup extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
final SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final EditText editText = (EditText) findViewById(R.id.editText);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.setup_region_spinner, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//BUTTON PRESS
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("Server", String.valueOf(spinner.getSelectedItem()));
if (String.valueOf(spinner.getSelectedItem()).equals("EUW")) {
}
else if (String.valueOf(spinner.getSelectedItem()).equals("NA")) {
try {
Toast.makeText(Setup.this, Functions.loadURL("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" +
editText.getText().toString().replaceAll("\\s", "") +
"?api_key=cbc50791-3c4d-45e6-b0c1-8aa204ced475"), Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
}
//ERROR
else {
Toast.makeText(Setup.this, "Server selection error", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
The try-block was just added after reading through the answers. Another one was added in my loadURL method. It seems to work for now.
I'm now getting errors because I was trying to run this on the main thread. I'll have to read more about that.
Put your code inside try block and catch the exception:
try {
String fullString = "";
URL url = new URL(inputURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
First, go through the basic JSON format. There are basically two things to look at :
JSONObject
JSONArray
Once you are comfortable with these two, try parsing the response using :
try{
JSONObject jsonObject = new JSONObject(<your_response_string_here>);
//Your parsing logic here
}catch(JSONException ex){
ex.printStackTrace();
}
Lets say your json was :
{
"some_status": 200,
"my_data": {
"param1": "value1",
"param2": "value2"
},
"my_array": ["arrayvalue1", "arrayvalue2"]
}
Your code should look somehting like this:
try{
JSONObject jsonObject = new JSONObject(<your_response_string_here>);
//Your parsing logic here
int status = jsonObject.optString("some_status");
JSONObject my_data = jsonObject.optJSONObject("my_data");
//Here parse your "my_data" object to get "param1" and "param2"
JSONArray my_array = jsonObject.optJSONArray("my_array");
//Here parse your "my_array" array to get "arrayvalue1" and "arrayvalue2"
}catch(JSONException ex){
ex.printStackTrace();
}
Please go through Android DOCS: http://developer.android.com/reference/org/json/JSONObject.html
And some examples like : http://www.tutorialspoint.com/android/android_json_parser.htm
I hope this helps.
I am a beginner in Android programming. I'm trying to put an ID identifier coming from MySQL database using JSON to my listview items but I can't make it work. When i click on an item it should probably give the id of the item I clicked but it is not working and all I can get is a false.
public class MessagingListFragment extends Fragment {
private String jsonResult;
private String url = "http://10.0.2.2/mobile/get_my_ins.php";
private ListView listView;
List<NameValuePair> nameValuePairs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.messaging_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listView1);
accessWebService();
return rootView;
}
// Async Task to access the web
#SuppressLint("NewApi")
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("stud_id",MainActivity.user_id));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
}
}// end async task
public void accessWebService() {
try{
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}catch(Exception e){
Toast.makeText(getActivity(), e.getMessage().toString() + " 3", Toast.LENGTH_LONG).show();
}
}
// build hash set for list view
public void ListDrawer() {
List<Map<String, String>> classList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("recipient");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String friend = jsonChildNode.optString("last_name") + ", " + jsonChildNode.optString("first_name");
String outPut = friend;
classList.add(createMsgList("recipient", outPut));
}
} catch (JSONException e) {
Toast.makeText(getActivity(), e.getMessage().toString() + " 1", Toast.LENGTH_LONG).show();
}
try{
SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity() , classList,
android.R.layout.simple_list_item_1, new String[] { "recipient" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int i,
long l) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();
}
});
}catch(Exception e){
Toast.makeText(getActivity(), e.getMessage().toString() + " 2", Toast.LENGTH_LONG).show();
}
}
private HashMap<String, String> createMsgList(String name, String subject) {
HashMap<String, String> friendList = new HashMap<String, String>();
friendList.put(name, subject);
return friendList;
}
}
You are popping up a Toast with listView.getId() as the textual content. This will always give you the ID of the listview that is containing your list items.
If you want to grab the data for the view, you will either need to use the position parameter (int i in the onItemClick method), or you can try to grab the data from the View v if it is a custom view.
For example, instead of passing in a String array into your adapter, you can keep a reference to the array and find the data you are looking for with myArray[i].
by calling listView.getId() you requested the listview id not the item inside listview
change
Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();
to
Toast.makeText(getActivity(), "my id and position = "+i, Toast.LENGTH_LONG).show();
i is the item position inside listview and JSONArray
hope this information helpful to you