Data not displayed in Listview in Android - java

I am trying to get google places data from google api and display in listview. I was succeeded in getting data and and setting to adapter, but not able to display in listview.
MainActivity. java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.listView);
StringBuilder sbValue = new StringBuilder(sbMethod());
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
MyAdapter adapter=new MyAdapter(MainActivity.this,R.layout.my_adapter_item,arr);
lv.setAdapter(adapter);
}
public StringBuilder sbMethod() {
//use your current location here
double mLatitude =-33.8670522;
double mLongitude =151.1957362;
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + "restaurant");
sb.append("&sensor=true");
sb.append("&key=AIzaSyC2SaN5I5u2eWw3zr4OZoLwD0qvCU-_uUw");
Log.d("Map", "api: " + sb.toString());
return sb;
}
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParserTask
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception downloading", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
for (int i = 0; i < list.size(); i++) {
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));
}
}
}
public class Place_JSON {
/**
* Receives a JSONObject and returns a list
*/
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for (int i = 0; i < placesCount; i++) {
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/**
* Parsing the Place JSON object
*/
private HashMap<String, String> getPlace(JSONObject jPlace) {
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
map1=new HashMap<String, String>();
map1.put("Name",placeName);
map1.put("Vicinity",vicinity);
arr.add(map1);
Log.w("MainActivity",placeName+";"+vicinity);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
Here i am getting data from HashMap<String, String> getPlace(JSONObject jPlace) and setting to adapter.
This adapter i am setting to listview in Oncreate.
adapter class
public class MyAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> names;
int data;
Context ctxt;
LayoutInflater inflater;
public MyAdapter (Context c, int nes, ArrayList<HashMap<String, String>> enj){
this.ctxt = c;
this.data = nes;
this.names = enj;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return names.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return names.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
// TODO Create the cell (View) and populate it with an element of the array
ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = LayoutInflater.from(ctxt).inflate(data, viewGroup);
holder.nam = (TextView) convertView . findViewById (R.id.name);
holder.vic = (TextView) convertView . findViewById (R.id.vicinity);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView . getTag ();
}
holder.nam.setText(names.get(position).get("Name"));
holder.vic.setText(names.get(position).get("Vicinity"));
return convertView;
}
class ViewHolder {
TextView nam,vic;
}
}
Here i am not able to display the data in listview. Please help me in this.

Once the "arr" has changed we need to notify adapter that dataset has changed. In onPostExecute of ParserTask , add following line
adapter.notifyDataSetChanged();

Try to use :
instead of this
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return names.get(arg0);
}
use
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}

Related

Android how can i get value of ArrayList Hashmap in my baseadapter

I have an Activity called Myprofile and a baseAdapter called Myprofile_CustomView on my activity I get Json data which then I convert into a ArrayList with a hashmap and my question is how can I retrieve the values of the hashmap in the baseadapter ?
This is my activity Myprofile
public class Myprofile extends Activity {
String URI_URL;
Integer page;
ProgressBar pb;
ListView mm;
Myprofile_CustomView BA;
ArrayList<HashMap<String,String>> userslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile);
URI_URL = getResources().getString(R.string.PathUrl) + "/api/myprofile";
page=0;
// Listview for adapter
mm= (ListView)findViewById(R.id.myprofiles);
new Myprofile_Async().execute();
}
public class Myprofile_Async extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
int id;
#Override
protected void onPreExecute() {
super.onPreExecute();
pb=(ProgressBar)findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
id= getIntent().getExtras().getInt("id");
// page Int is used to keep count of scroll events
if(page==0)
{page=1;}
else {page=page+1;}
Toast.makeText(Myprofile.this,""+page,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
// Gets data from api
BufferedReader reader=null;
String cert="id="+id+"&page="+page;
try{
url = new URL(URI_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
System.err.println("cassies" + result);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
HashMap<String,String> map= new HashMap<>();
JSONObject jsonn= new JSONObject(result);
JSONArray jArray = jsonn.getJSONArray("myprofile");
JSONObject jobject=null;
JSONArray sss= new JSONArray();
for(int i=0; i < jArray.length(); i++) {
jobject= jArray.getJSONObject(i);
map.put("fullname",jobject.getString("fullname"));
sss.put(jobject);
}
jsonn.put("myprofile", sss);
// Add values to arrayList
userslist.add(map);
// Send information to BaseAdapter
BA= new Myprofile_CustomView(userslist,Myprofile.this);
mm.setAdapter(BA);
} catch (Exception e) {
System.err.println("mpee: " + e.toString());
}
pb.setVisibility(View.INVISIBLE);
}
}
}
this part above I have no issues with my problem is in the BaseAdapter with the ArrayList userList I don't know how to get HashMap keys from it. I am naming the keys because I have other fields that I will eventually do
public class Myprofile_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
ArrayList<HashMap<String,String>> usersList;
// Have data come in and do a toast to see changes
public Myprofile_CustomView(ArrayList<HashMap<String,String>> arr, Context c) {
notifyDataSetChanged();
ctx = c;
usersList= arr;
myiflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("myprofile");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx, "Error: Please try again", Toast.LENGTH_LONG).show();
return names.length();
}
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
MyViewHolder holder=null;
try {
if(row==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.zmyprofile,parent,false);
holder=new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder=(MyViewHolder)row.getTag();
}
// How can I get HashMap value for fullname here so I can set it to to Text
String fullname= usersList
holder.fullname.setText(fullname);
return row;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
class MyViewHolder{
TextView fullname;
MyViewHolder(View v)
{
fullname= (TextView)v.findViewById(R.id.fullname);
}
}
}
getCount should return the size of your dataset. In your case usersList
public int getCount() {
return usersList == null ? 0 : userLists.size();
}
int getView you want to retrieve the item at position:
HashMap<String, String> item = usersList.get(i);
String fullname = item.get("fullname");
the value of position changes with the scrolling,

Google Places Details search System.err

I'm attempting to locate a restaurant by name using an AutoCompleteTextView which successfully obtains the places id. I've also checked the http request manually in my browser which responds with the correct information. When this code is executed, a system.err is shown in the LogCat console in Eclipse. My code below;
public class AdvancedSearch extends Activity implements OnItemClickListener {
private static final String LOG_TAG = "com.lw276.justdine";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
// ------------ make your specific key ------------
private static final String API_KEY = "MyAPIKEY";
private Activity context = this;
static HashMap<String, String> place;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_search);
final AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this,
R.layout.list_item));
autoCompView.setOnItemClickListener(this);
Button btnAdvancedSearch = (Button) findViewById(R.id.advanced_search_btn);
btnAdvancedSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = autoCompView.getText().toString();
if(place.containsKey(str)){
String placeId = place.get(str);
Log.d("advancedSearchBtn: placeId = ", placeId);
Log.i("advancedSearchBtn", "Search button has been pressed");
Intent i = new Intent(context, GoogleMap.class);
i.putExtra("advancedSearch", placeId);
startActivity(i);
} else {
Toast.makeText(context, "Please select an item from the autocomplete list", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
// String str = (String) adapterView.getItemAtPosition(position);
// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE
+ TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: " + url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
resultList = new ArrayList<String>(predsJsonArray.length());
place = new HashMap<String, String>();
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString(
"description"));
System.out
.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString(
"description"));
String description = predsJsonArray.getJSONObject(i).getString("description");
String placeId = predsJsonArray.getJSONObject(i).getString("place_id");
place.put( description, placeId);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String>
implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context,
int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
// #Override
// public HashMap<String, String> getItem(int index) {
// return resultList.get(index);
// }
#Override
public String getItem(int index){
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
The googlePlaces example =
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJCSWGvY-FdUgRpGdg10FTIIg&key="MY_API_KEY"
Is it obvious to anyone why no markers are being placed on my map fragment?
Errors from LogCat:
http://pastebin.com/T1AFbw3s
Google Maps and Markers class:
http://pastebin.com/hT2XwuE2
The error you are having is due to parsing the Json incorrectly at line 193 of GoogleMap activity:
JSONArray placesArray = resultObject.getJSONArray("results");
I believe the key is result instead of results.
I can give you a better explanation if I could see the json response. Meanwhile,
I would also suggest you to use Gson Library to parse the json responses to objects instead of mapping them manually. It would be alot easier.
Markers need to be added manually:
private void addMarker(String name, double lat, double long){
LatLng latlong = LatLng.newInstance(lat, long);
MarkerOptions markerOptions = MarkerOptions.newInstance();
markerOptions.setIcon(Icon.newInstance("/img/icon.png"));
markerOptions.setTitle(name);
Marker marker = new Marker(latlong, markerOptions);
map.addOverlay(marker);
}
It turns out that because I was using the same code to add markers onto the Map, when the detail search was used to identify a single place, the JSONArray type was incompatible with the result set... If that makes sense.
I had to separate the two by checking if a nearby search was being performed or a details search. Below was the code for the details search only:
resultObject = resultObject.getJSONObject("result"); // <---
places = new MarkerOptions[1];
LatLng placeLL = null;
String placeName = "";
String vicinity = "";
try {
JSONObject placeObject = resultObject;
JSONObject loc = placeObject.getJSONObject(
"geometry").getJSONObject("location");
placeLL = new LatLng(Double.valueOf(loc
.getString("lat")), Double.valueOf(loc
.getString("lng")));
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
} catch (JSONException jse) {
missingValue = true;
jse.printStackTrace();
}
if (missingValue){
result = null;
} else {
places[0] = new MarkerOptions().position(placeLL)
.title(placeName).snippet(vicinity);
}

ArrayList using hashmap not working

I have this code where I get the data from Facebook Graph API which seems working, my problem is when i add the hashmap to my arraylist its not working, i toasted the size of my array and I always get zero. please help. here is the code:
public class PageFeedHome extends Fragment {
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
BaseAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
new LoadPosts().execute();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
Log.i("added" , feedList.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getActivity(), ""+feedList.size(), Toast.LENGTH_LONG).show();
adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author, R.id.id_tv });
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}

I am not able to get the gridview populated with textview in Android Fragment

i am not able to populate the imageview textview inside gridview using fragments.
It is showing blank intead of gridview populating in my project can please anyone see the code below and let me know what i have to change
And the populating the image and text is from the mysql database dynamically
public class StoreHomeFragment extends Fragment {
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_home, container, false);
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
return rootView;
}
//Activity is created
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String url = "http://192.168.1.132/Android/App/good.php"; //url where i am using select query and retrieving it from database
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);//retrieving from db
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
//gridView1.setAdapter(new ImageAdapter(this,MyArrList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//I have used imageAdapter
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageView imageView;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list)
{
context = c;
MyArr = list;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.store_home_gridview_row, null);
}
TextView tv_title = (TextView) convertView.findViewById(R.id.textview_name);
tv_title.setText("Title:"+MyArr.get(position).get("name"));
TextView tv_artist = (TextView) convertView.findViewById(R.id.textview_artist);
tv_artist.setText("Artist:"+MyArr.get(position).get("artist"));
TextView tv_duration = (TextView) convertView.findViewById(R.id.textview_price);
tv_duration.setText("Price:"+MyArr.get(position).get("price"));
String abc = (MyArr.get(position).get("image"));
String abcd = "http://192.168.1.132/images/products/"+abc;
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try
{
URL url3 = null;
try {
url3 = new URL(abcd);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url3.openConnection().getInputStream()); //image is populated
imageView.setImageBitmap(bmp);
}
catch(Exception par)
{
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println ( "status Code : " + statusCode );
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
str.append(line);
}
}
else
{
Log.e("Log", "Failed to download file..");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println ( "str : " + str.toString() );
return str.toString();
}
}
Follow the steps Hope this helps you
1) Remove these lines from onCreateView() method
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
2)Modify onActivityCreated() as follow
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.132/Android/App/good.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
}
}.execute();
}

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