SetOnCLickListener issue - java

I am having a problem with my setOnClickListener. I can not figure out what the code is i need for it. What i am trying to do is once the item is clicked on in the list view it opens up a new activity. in my code the list view is in the MainActivity. and i want it to open up the Homework activity. So my question is, can anybody help me figure out what i need to put in for it to work correctly and open up Homework.java? when it opens up Homework.java it would show the item clicked in the list view as the header. then nothing in the body.
MainActivity.class:
public class VideoListTask extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
protected void onPreExecute (Void result) {
dialog.getProgress();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params)
{
HttpClient client = new DefaultHttpClient();
//HttpGet getRequest = new HttpGet(feedUrl);
Date now = new Date();
HttpGet getRequest = new HttpGet(canvasUrl + "courses? include[]=term&state=available");
getRequest.setHeader("Authorization","Bearer " + canvasApiKey); //uses your key to access your data
try
{
HttpResponse response = client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode != 200)
{
return null;
}
InputStream jsonStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine())!=null)
{
builder.append(line);
}
String jsonData = builder.toString();
//JSONObject json = new JSONObject(jsonData);
//JSONObject data = json.getJSONObject("data");
//JSONArray items = data.getJSONArray("items");
JSONArray courses = new JSONArray(jsonData);
//for(int i =0; i<items.length(); i++)
//{
// JSONObject video = items.getJSONObject(i);
// videoArrayList.add(video.getString("title"));
//}
for(int i = 0; i<courses.length(); i++)
{
JSONObject course = courses.getJSONObject(i);
JSONObject term = course.getJSONObject("term");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date enddate = format.parse(term.getString("end_at"));
Date startdate = format.parse(term.getString("start_at"));
if (now.after(startdate) && now.before(enddate))
{
videoArrayList.add(course.getString("name"));
}
} catch (Exception e) {
//videoArrayList.add(course.getString("name"));//include if you want undated courses
}
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
THIS IS WHERE I NEED TO PUT THE ONCLICK LISTENER IN.
}

If Homework.java is your second activity you can set a click listener in this way
Main Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
startActivity(new Intent(MainActivity.this, Homework.class));
}
});

start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Class<?> ourClass=Class.forName("com.example.projname.Homework");
Intent ourIntent= new Intent(MainActivity.this,ourClass);
ourIntent.putExtra("matrix", m);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
});
The data you pass using putExtra will be available to you in the Homeactivity.java

Related

How to get one spinner values based on the selected value of another spinner when we are working with services

In my application, I am working with spinners. I want to get values of one spinner based on a selection of an item of another spinner. I searched a lot but I found only custom data. But I am getting those spinner values from services so anybody helps me to solve this.
Here is my code:
//Department spinner
Spinner spinner;
String URL="http://182.18.163.38/def.php?issue=1";
ArrayList<String> Department;
String uid;
//Deficiency category spinner
Spinner spinner2;
String URL2 = "http://182.18.163.38/def.php?issue=2&dept="+uid;
ArrayList<String>Deficiency;
String defid;
//Branch officer spinner
Spinner spinner3;
String URL3 = "http://182.18.163.38/def.php?issue=3";
ArrayList<String> BranchOfficer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_deficiency);
//spinner for department
Department = new ArrayList<>();
spinner=(Spinner)findViewById(R.id.select_department);
loadSpinnerData(URL);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String department = spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),department,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
//spinner for deficiency
Deficiency = new ArrayList<>();
spinner2 = (Spinner)findViewById(R.id.deficiency_category);
loadSpinnerDeficiency(URL2);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String deficiency = spinner2.getItemAtPosition(spinner2.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),deficiency,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
}
private void loadSpinnerData(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String department = jsonobject.getString("Department");
uid = jsonobject.getString("ID");
Department.add(department);
}
spinner.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Department));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadSpinnerDeficiency(String url2) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.38/def.php?issue=2&dept="+uid);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String defcat = jsonobject.getString("Deficiency");
defid = jsonobject.getString("ID");
Deficiency.add(defcat);
}
spinner2.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Deficiency));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
above is my code for getting values from the url's.
Use an asynctask instead of doing network operations in main thread.
First call the web service to load data for the first spinner,populate data in onPostExecute() of the asynctask.
Within the setOnItemSelectedListener of the first spinner,take the input from the first spinner(which i believe you are doing) and call the asynctask to load the 2nd spinner.You are not loading the second spinner in the setOnItemSelectedListener of the first spinner.

Get a variable form onItemListener and use it in another function

private class BackTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
// i want to use httppost in this ligne
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); // close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
// parse json data
try {
result = result.substring(result.indexOf("["));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Prog2 p = new Prog2();
p.setTitre_emission(json_data.getString("titre_emission"));
p.setDesc_emission(json_data.getString("desc_emission"));
p.setHeure_emission(json_data.getString("heure_emission"));
p.setChaine_emission(json_data.getString("titre_chaine"));
records.add(p);
}
}
catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null)
pd.dismiss(); // close dialog
Log.e("size", records.size() + "");
adapter.notifyDataSetChanged(); // notify the ListView to get new
// records
}
}
How can I get a text from onItemListener and use it in an other function for getting an httpost?
When I use getText() I get an error
public class Wataneya1Activity extends AppCompatActivity {
Toolbar mToolbar;
Spinner mSpinner;
String text;
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter1 adapter;
ListView listProg;
ArrayList<Prog1> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wataneya1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageButton mButton = (ImageButton) findViewById(R.id.Button03);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wataneya1Activity.this.finish();
}
});
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
final ActionBar actionBar = getSupportActionBar();
mSpinner = (Spinner) findViewById(R.id.spinner_rss);
String[] items = getResources().getStringArray(R.array.days_array);
List<String> spinnerItems = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
spinnerItems.add(items[i]);
}
SpinnerAdapter adapter1 = new SpinnerAdapter(actionBar.getThemedContext(), spinnerItems);
mSpinner.setAdapter(adapter1);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2, long arg3) {
text = mSpinner.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
context = this;
records = new ArrayList<Prog1>();
listProg = (ListView) findViewById(R.id.prog_list);
adapter = new CustomAdapter1(context, R.layout.list_item, R.id.titre_emission, records);
listProg.setAdapter(adapter);
}
public HttpPost fnt (String text) {
if (text.equals("Mardi")) {
httppost = new HttpPost("http://192.168.:8080/TuniTV/prog_wataneya1_mardi.php");
} else if (text.equals("Mercredi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_mercredi.php");
} else if (text.equals("Jeudi")) {
httppost = new HttpPost("http://192.168/TuniTV/prog_wataneya1_jeudi.php");
} else if (text.equals("Vendredi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_vendredi.php");
} else if (text.equals("Samedi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_samedi.php");
} else if (text.equals("Dimanche")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_dimanche.php");
} else {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_lundi.php");
}
return httppost;
}
You receive the click position ( == index into your data) in the callback method. Use it to find the data in your data array.
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2, long arg3) {
text = spinnerItems.get(arg3);
Toast.makeText(getApplicationContext(), text,
Toast.LENGTH_SHORT).show();
}
Btw... Telling us there is a mistake - is crap.
Telling us what kind of mistake it is or even showing some stacktrace? Great stuff.

Android Studio app show the error message to user

guys I have a problem with implement error handling in my application.
I want to display the error message to the user of my application when the response code from rest is not 200. In other words: If the connection is wrong, I want to display the message, that the user have to check his internet connection and try again. If everything is fine I want to do everything as usual so load the content.
I write something like this:
Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
errorToast.show();
and this:
if(response.getStatusLine().getStatusCode() == 200){}
But i don't know If this is good code and where should I insert it. I will be very grateful for your help and advice.
This is this code:
public class NewsActivity extends Activity {
private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
new FetchItems().execute();
}
private class FetchItems extends AsyncTask<String, Void, JSONArray> {
protected JSONArray doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Content-type", "application/json");
JSONArray json = new JSONArray();
try {
HttpResponse response = httpclient.execute(httpget);
json = new JSONArray(EntityUtils.toString(response.getEntity()));
return json;
}
} catch (Exception e) {
Log.v("Błędne wczytanie", e.getMessage());
}
return json;
}
protected void onPostExecute(JSONArray result) {
ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
ArrayList<String> listItems = new ArrayList<String>();
String contentToEdit;
String titleContainer;
TextView newsHeaderTextView = null;
for (int i = 0; i < result.length(); i++) {
try {
titleContainer = result.getJSONObject(i).getString("title").toString();
listItems.add(titleContainer);
contentToEdit=result.getJSONObject(i).getString("body").toString();
contentToEdit= Html.fromHtml(contentToEdit).toString();
listItems.add(contentToEdit);
} catch (Exception e) {
Log.v("Błędne wczytanie1", e.getMessage());
}
}
ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
lst.setAdapter(ad);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
You can add this in doInBackground method.
runOnUiThread(new Runnable() {
public void run() {
if (response.getStatusLine().getStatusCode() != 200) {
Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
errorToast.show();
}
}
});
/*
I thought Your Code Working Fine Made Some Changes As Per Need
*/
public class NewsActivity extends Activity {
private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";
String jsonArrayString = "";
String message = "Error, pls check your internet connection and try again!";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
new FetchItems().execute(this);
}
private class FetchItems extends AsyncTask<Context,Void,String>{
Context temp;
#Override
protected String doInBackground(Context... params) {
temp = params[0];
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Content-type", "application/json");
JSONArray json = new JSONArray();
try {
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200) {
json = new JSONArray(EntityUtils.toString(response.getEntity()));
jsonArrayString += json.toString();
return jsonArrayString;
}
}
catch (Exception e) {
Log.v("Błędne wczytanie", e.getMessage());
}
return message;
}
#Override
protected void onPostExecute(String s) {
ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
ArrayList<String> listItems = new ArrayList<String>();
String contentToEdit;
String titleContainer;
TextView newsHeaderTextView = null;
if(!message.equals(s))
{
JSONArray result = null;
try {
result = new JSONArray(s);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < result.length(); i++) {
try {
titleContainer = result.getJSONObject(i).getString("title").toString();
listItems.add(titleContainer);
contentToEdit=result.getJSONObject(i).getString("body").toString();
contentToEdit= Html.fromHtml(contentToEdit).toString();
listItems.add(contentToEdit);
} catch (Exception e) {
Log.v("Błędne wczytanie1", e.getMessage());
}
}
ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
lst.setAdapter(ad);
}
else
{
Toast.makeText(temp,message,Toast.LENGTH_LONG).show();
}
}
}
}

Android Search Listview duplicating items from JSON using EditText

I'm creating a simple search activity using EditText, ListView, JSON and Database, Every time i enter text in EditText, the listview must update(I'm using mysql, Select query LIKE), where the ListView that contains Items from Database using JSON, the items must be updated from the given condition using LIKE method, but it keeps in duplicating item in ListView every time i enter text.
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
name = inputSearch.getText().toString();
searcher(name);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
String result;
private void searcher(String searched){
class searching extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramSearched = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://....p.com/searchD.php?name=" + paramSearched);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream is = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
result = stringBuilder.toString();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject obj = new JSONObject(result);
nameslist = obj.getJSONArray("list");
for(int i = 0; i < nameslist.length(); i++){
JSONObject c = nameslist.getJSONObject(i);
String id = c.getString("ID");
String name = c.getString("Name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", id);
map.put("Name", name);
listofnames.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Searching Name. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Search.this, listofnames,
R.layout.list_item1, new String[]{"ID",
"Name"},
new int[]{R.id.pid, R.id.name});
lv.setAdapter(adapter);
}
});
adapter.notifyDataSetChanged();
}
}
searching sh = new searching();
sh.execute(searched);
}
I think you should clear the "listofnames" list before you add new data into it to keep the list data newest and not duplicated.

Android ListView OnItemClickListener()

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

Categories