Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get only one restaurant when I press click button one click

Status
Not open for further replies.

ahm1985

Programmer
Dec 6, 2012
138
0
0
EG
I have app in side it only one activity (main activity) and layout XML of main activity have only
list view .this app get restaurants near from my location and display it in list view
What i need to do is add button to the main activity layout when i press on button get to me list of restaurant item by item
from json file and display it in list view but not display all restaurants in one click but show item by item
every click get restaurant
suppose i have 3 restaurant in json file
when i click on button for first click get me first restaurant
when i click on button for second click get me second restaurant
when i click on button for third click get me third restaurant
How to customize this code to accept get item by item restaurant from json file
My code include class and activity and code is working success
my class is FoursquareVenue
package com.foodsmap_project_app.foodsmap_project_app;
public class FoursquareVenue
{
private String name;
private String city;

private String category;

public FoursquareVenue() {
this.name = "";
this.city = "";
this.setCategory("");
}

public String getCity() {
if (city.length() > 0) {
return city;
}
return city;
}

public void setCity(String city) {
if (city != null) {
this.city = city.replaceAll("\\(", "").replaceAll("\\)", "");
;
}
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

}
MainActivity.java
public class MainActivity extends ListActivity {
ArrayList<FoursquareVenue> venuesList;
final String CLIENT_ID = "SVIBXYYXOEARXHDI4FWAHXGO5ZXOY204TCF1QJFXQLY5FPV4";
final String CLIENT_SECRET = "BAAJO1KXRWESGTJJGVON4W3WUFHAQDAJPLRIYJJ5OPHFQ5VI";
final String latitude = "30.435665153239377";
final String longtitude = "31.3280148";
ArrayAdapter <String> myAdapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new fourquare().execute();

}
private class fourquare extends AsyncTask<View, Void, String> {

String temp;

@Override
protected String doInBackground(View... urls) {


temp = makeCall(" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&v=20130815&ll=30.435665153239377,31.144435908398464" + "&query=resturant");


return "";
}

@Override
protected void onPreExecute() {

}

@Override
protected void onPostExecute(String result) {
if (temp == null) {

} else {

venuesList = (ArrayList<FoursquareVenue>) parseFoursquare(temp);

List<String> listTitle = new ArrayList<String>();

for (int i = 0; i < venuesList.size(); i++) {

listTitle.add(i, venuesList.get(i).getName() + ", " + venuesList.get(i).getCategory() + "" + venuesList.get(i).getCity());
}


myAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.row_layout, R.id.listText, listTitle);
setListAdapter(myAdapter);
}
}
}
public static String makeCall(String url) {


StringBuffer buffer_string = new StringBuffer(url);
String replyString = "";


HttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet(buffer_string.toString());

try {

HttpResponse response = httpclient.execute(httpget);
InputStream is = response.getEntity().getContent();


BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}

replyString = new String(baf.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}

return replyString.trim();
}
private static ArrayList<FoursquareVenue> parseFoursquare(final String response) {

ArrayList<FoursquareVenue> temp = new ArrayList<FoursquareVenue>();
try {


JSONObject jsonObject = new JSONObject(response);


if (jsonObject.has("response")) {
if (jsonObject.getJSONObject("response").has("venues")) {
JSONArray jsonArray = jsonObject.getJSONObject("response").getJSONArray("venues");

for (int i = 0; i < jsonArray.length(); i++) {
FoursquareVenue poi = new FoursquareVenue();
if (jsonArray.getJSONObject(i).has("name")) {
poi.setName(jsonArray.getJSONObject(i).getString("name"));

if (jsonArray.getJSONObject(i).has("location")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("address")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("city")) {
poi.setCity(jsonArray.getJSONObject(i).getJSONObject("location").getString("city"));
}
if (jsonArray.getJSONObject(i).has("categories")) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").length() > 0) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).has("icon")) {
poi.setCategory(jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).getString("name"));
}
}
}
temp.add(poi);
}
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
return new ArrayList<FoursquareVenue>();
}
return temp;

}

}
 
I am not going to try going through your code to examine what you are doing.
But based on what you say...
when i press on button get to me list of restaurant item by item from json file
you will need to go beyond your single Activity and single XML Layout approach.

Typically when you select a single item from your ListView you need to set up a setOnItemClickListener to identify which item you selected and then act appropriately on it.

Based on what you initially describe, the ListView layout for the Restaurants will not support the "item-by-item" listing you want to show for that selected Restaurant - and depending on the complexity of each 'item' you might need to use a CustomListAdapter.

There are a lot of tutorials on the web for this type of thing.
Do a Google Search for Android ListView Tutorial and you will find many

Good Luck,
JRB-Bldr


 
How can i make button sort the result displayed in listview
 
I am not clear on your layout.
You have a Listview which is displaying the Restaurants.
Typically you just click on the individual Listview item to make the selection and then do whatever via the setOnItemClickListener

But you mention a Button.
Do you also have a Button in addition to the Listview on your Layout?
If you do, I don't see where you define it to your onCreate() method.

Before you begin worrying about sorting the Listview, you need to get the other elements working.
Do as I said before - do a Google Search for Android ListView Tutorial

Good Luck,
JRB-Bldr



 
Yes I need to customize code above and i have button
And list view in code above working and get data without any proplem
I dont need to show all items in one time
i need to show item by item(restaurant)
depend on how many time you click button
if you click button three time
i must get list view with three item
 
This is Mainactivity.java with button
and i need to allow button to show item by item based on button click
public class MainActivity extends ListActivity {
ArrayList<FoursquareVenue> venuesList;
Button btn;
int clickCount;

// ArrayList<FoursquareVenue> allResults;

List<String> shownResults = new ArrayList<String>();

//final String CLIENT_ID = "1CO3ZGVRFHXUIKWGFGDJBLJS4DNKX25EBR1TVEYSEUOFKCJD";
//final String CLIENT_SECRET = "P24DH3AUZUW4Q3Q1WHLG4HED0WPPMHT4P30TOKG2EFWAJPIJ";
// final String latitude = "30.435665153239377";
// final String longtitude = "31.144435908398464";
final String CLIENT_ID = "SVIBXYYXOEARXHDI4FWAHXGO5ZXOY204TCF1QJFXQLY5FPV4";
final String CLIENT_SECRET = "BAAJO1KXRWESGTJJGVON4W3WUFHAQDAJPLRIYJJ5OPHFQ5VI";
final String latitude = "30.435665153239377";
final String longtitude = "31.3280148";
ArrayAdapter <String> myAdapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new fourquare().execute();
btn=(Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{

String name = venuesList.get(clickCount).getName();

String cat = venuesList.get(clickCount).getCategory();

String city = venuesList.get(clickCount).getCity();

shownResults.add(name + "," + "cat" + "" + city);

clickCount++;

myAdapter.notifyDataSetChanged();
new fourquare().execute();

}
});

}
private class fourquare extends AsyncTask<View, Void, String> {

String temp;

@Override
protected String doInBackground(View... urls) {

//temp = makeCall(" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&v=20130815&ll=30.435665153239377,31.144435908398464");
temp = makeCall(" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&v=20130815&ll=30.435665153239377,31.144435908398464" + "&query=resturant");
//public static String URL_GET_Place = "
return "";
}

@Override
protected void onPreExecute() {

}

@Override
protected void onPostExecute(String result) {
if (temp == null) {

} else {

venuesList = (ArrayList<FoursquareVenue>) parseFoursquare(temp);

List<String> listTitle = new ArrayList<String>();

for (int i = 0; i < venuesList.size(); i++) {

listTitle.add(i, venuesList.get(i).getName() + ", " + venuesList.get(i).getCategory() + "" + venuesList.get(i).getCity());
}


myAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.row_layout, R.id.listText, listTitle);
setListAdapter(myAdapter);
}
}
}
public static String makeCall(String url) {


StringBuffer buffer_string = new StringBuffer(url);
String replyString = "";


HttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet(buffer_string.toString());

try {

HttpResponse response = httpclient.execute(httpget);
InputStream is = response.getEntity().getContent();


BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}

replyString = new String(baf.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}

return replyString.trim();
}
private static ArrayList<FoursquareVenue> parseFoursquare(final String response) {

ArrayList<FoursquareVenue> temp = new ArrayList<FoursquareVenue>();
try {


JSONObject jsonObject = new JSONObject(response);


if (jsonObject.has("response")) {
if (jsonObject.getJSONObject("response").has("venues")) {
JSONArray jsonArray = jsonObject.getJSONObject("response").getJSONArray("venues");

for (int i = 0; i < jsonArray.length(); i++) {
FoursquareVenue poi = new FoursquareVenue();
if (jsonArray.getJSONObject(i).has("name")) {
poi.setName(jsonArray.getJSONObject(i).getString("name"));

if (jsonArray.getJSONObject(i).has("location")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("address")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("city")) {
poi.setCity(jsonArray.getJSONObject(i).getJSONObject("location").getString("city"));
}
if (jsonArray.getJSONObject(i).has("categories")) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").length() > 0) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).has("icon")) {
poi.setCategory(jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).getString("name"));
}
}
}
temp.add(poi);
}
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
return new ArrayList<FoursquareVenue>();
}
return temp;

}

}
 
ahm1985 said:
And list view in code above working and get data without any problem

And that ListView is showing ALL Restaurants? Correct?
With most ListViews, the individual selection is not done by a separate button, unless you want to do something totally unrelated to the individual contents of the ListView.

Instead doing something related to a single ListView item is done as I indicated - by clicking directly on that Listview item and having the setOnItemClickListener launch the subsequent work.

ahm1985 said:
I don't need to show all items in one time. i need to show item by item(restaurant). depend on how many time you click button

Typically your setOnItemClickListener might launch a new Activity with a different Layout.

One way (of many ways) to do what you want would be to have that new layout contain a Button and a EditText (whose Width is set to android:layout_width="wrap_content" & android:editable="false").

When the Button's onClick method was launched it would put an Item's text into the EditText with setText().
When the Button was clicked a 2nd time it would do a EditText.getText() and then add:
1. A CrLf = "\n"; to separate the item lines
2. then a 2nd item to the results
3. and write it back out again with a setText().

And on each subsequent Button clicks it would repeat the process until all items had been displayed.

Note - as I indicated there are a wide variety of ways to display the individual Restaurant's Items on the 2nd layout. This is merely one of them that seems like it corresponds to what you are asking it to do.
Personally I'd have the 2nd layout have its own Listview and show ALL of the selected Restaurant's items, but you indicated that you wanted to incorporate a one-by-one button selection.

Good Luck,
JRB-Bldr
 
I should add that typically what you are describing involved 2 JSON requests.
1. Get ALL Restaurants​
2. Get ALL Item info for the single Selected Restaurant​

The process does not require that it be done that way, but it is pretty easy if it is.
In that way the 2nd activity works pretty much like the first one, but only getting info on the selected restaurant.

As I indicated, if that is not possible there are a number of other ways to deal with the data.

Good Luck,
JRB-Bldr
 
Thank you for reply
I get the idea but i try to implementing that but something need to modify in code to work
my code as following
You could storage the parsed ArrayList, make a global variable for counting the number of times that the button has been clicked.

ArrayList<FoursquareVenue> venuesList;
Button btn;
int clickCount;
// ArrayList<FoursquareVenue> allResults;
List<String> shownResults = new ArrayList<String>();
ArrayAdapter <String> myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new fourquare().execute();
btn=(Button) findViewById(R.id.button);
btn.setonclickListener(new View.onclickListener() {
@Override
public void onclick(View v)
{

String name = venuesList.get(clickCount).getName();
String cat = venuesList.get(clickCount).getCategory();
String city = venuesList.get(clickCount).getCity();
shownResults.add(name + "," + "cat" + "" + city);
clickCount++;

myAdapter.notifyDataSetChanged();

}
});
}

This is my idea only i need to see what wrong in code above
 
I have tried to let you know that your approach is Not going to get you what you want.
You should not be using a Button to get the selected item from your ListView.
Your Button has no way of 'knowing' what ListView item was selected.

Please consider starting over.
Do as I suggest and look at the web references on how to use a ListView to make individual selections. ( do a Google Search for: Android ListView Tutorial )

If you do that you will find something similar to the following:
Code:
   listLocations = (ListView)findViewById(R.id.listLocations);	
   listLocations.setOnItemClickListener(new OnItemClickListener() {
	public void onItemClick(AdapterView<?> parent, View view,
		int position, long id)   // Individual Selected Item (Restaurant)
		{
                //  Do whatever you want with that individual selected item

                // Now go to a new Activity to get info for selected item
                // In that new Activity use new Layout to display the selected item's info
                Intent myIntent = new Intent(view.getContext(), RestaurantInfo.class);
	            startActivityForResult(myIntent, 0);  
	            finish();
	            overridePendingTransition(0, 0);				
		}
	});

Note - there are a couple of ways to pass data from Activity to Activity
1. Pass the data as an "EXTRA" to the launch of the new Activity ( Google for: android activity extra )
2. Put data into a Shared Preference ( Google for: android sharedpreferences tutorial )

Good Luck,
JRB-Bldr
 
Well I have to admit that what I am suggesting is the ONLY way I have gotten things to work as I wanted with ListViews. And I have used it many times.

However I have found a few web references that might address the approach you are trying to take.

And if you do a Google search for: android listview button onclick
you might find what you want.

Good Luck,
JRB-Bldr
 
Thank you for reply and corporate
I solved the problem
1- I declare to global variable
int clickCount=0;
List<String> shownResults = new ArrayList<String>();
2- under button click listener i put
//execute async task
new fourquare().execute();
3- I modify onPostExecute function
protected void onPostExecute(String result) {
if (temp == null) {

} else {

venuesList = (ArrayList<FoursquareVenue>) parseFoursquare(temp);


String name = venuesList.get(clickCount).getName();

String cat = venuesList.get(clickCount).getCategory();

String city = venuesList.get(clickCount).getCity();

shownResults.add(name + "," + "cat" + "" + city);
clickCount++;
myAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.row_layout, R.id.listText, shownResults);

setListAdapter(myAdapter);

}
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top