android - json generated listview onClick only shows last item - android

I have a map which shows markers from json file from web.
I made a search listview from the same file.
What I want to do is after click on any result map zooms on the marker associated with that result.
But now when I click on any result it only zoom on ONE marker which is the last item in my json file.
Here's my code:
public class MapAcWithMarker extends FragmentActivity
implements OnMapReadyCallback {
static final LatLng TEHRAN = new LatLng(35.697291, 51.392378);
private GoogleMap mMap;
public ArrayList<Locations> locationsList;
public ListView listView;
private View parentView;
public DataAdapter adapter;
ArrayList<Locations> arrayListTemp=new ArrayList<>();
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_recyc);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// AsyncTaskGetMarker asyncTaskGetMareker= new AsyncTaskGetMarker();
new AsyncTaskGetMarker().execute();
locationsList = new ArrayList<>();
parentView = findViewById(R.id.parentLayout);
inputSearch = (EditText) findViewById(R.id.inputSearch);
listView = (ListView) findViewById(R.id.listView);
listView.setVisibility(View.INVISIBLE);
inputSearch.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if(keyCode== KeyEvent.KEYCODE_DEL){
listView.setVisibility(View.GONE);
}
return true;
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int count) {
listView.setVisibility(View.VISIBLE);
if(count==0){
listView.setVisibility(View.INVISIBLE);
}
String searchString= inputSearch.getText()
.toString().toLowerCase(Locale.getDefault());
int realText= searchString.length();
arrayListTemp.clear();
for (int i =0 ; i <locationsList.size(); i++){
try {
String pname= locationsList.get(i).getPname()
.toString();
String bicycleno= locationsList.get(i).getBicycleno()
.toString();
if(realText<=pname.length() && realText<= bicycleno.length())
if (searchString.equalsIgnoreCase(pname.substring(0,
realText)) ||
searchString.equalsIgnoreCase(bicycleno.substring(0, realText))
) {
arrayListTemp.add(locationsList.get(i));
} else {
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Log.d("#w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
RequestInterface api = JsonClient.getApiService();
/**
* Calling JSON
*/
Call<StopList> call = api.getJSON();
/**
* Enqueue Callback will be call when get response...
*/
call.enqueue(new Callback<StopList>() {
#Override
public void onResponse(Call<StopList> call, Response<StopList> response) {
//Dismiss Dialog
// dialog.dismiss();
if (response.isSuccessful()) {
/**
* Got Successfully
*/
locationsList = response.body().getLocations();
/**
* Binding that List to Adapter
*/
adapter = new DataAdapter(MapAcWithMarker.this,
locationsList);
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<StopList> call, Throwable t) {
Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(TEHRAN, 10));
new AsyncTaskGetMarker().execute();
}
class AsyncTaskGetMarker extends
AsyncTask<String, String, JSONArray> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... params) {
String json = null;
JSONArray jsonarray = null;
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("https://api.myjson.com/bins/1879ab.json");
conn = (HttpsURLConnection) url.openConnection();
conn.connect();
InputStream in = new BufferedInputStream(conn.getInputStream());
reader = new BufferedReader
(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
String response = builder.toString();
JSONObject jsonObject = new JSONObject(response);
jsonarray = jsonObject.getJSONArray("stops");
// jsonarray = new JSONArray(response);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonarray;
}
protected void onPostExecute(final JSONArray jsonarray) {
try {
final SparseArray<LatLng> positions =
new SparseArray<>();
mMap.clear();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String pname = obj.getString("pname");
String bicycleno = obj.getString("bicycleno");
Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");
final LatLng position = new LatLng(lat, lang);
String title = "name: " + name;
mMap.addMarker(new MarkerOptions()
.position(position).title(title));
positions.put(i, position);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (positions.get(position) != null)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position), 15));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

inside onPostExecute you have:
position = new LatLng(lat, lang);
String title = "name: " + name;
mMap.addMarker(new MarkerOptions()
.position(position).title(title));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position,15));
}
});
so under position you have always last called position. This variable is used by every onClick set (in line: newLatLngZoom(position,15))
for fix this create position only locally inside method, you dont need globalLatLng position` variable declared on top of file
final LatLng position = new LatLng(lat, lang);
//rest of code as above
edit: also these
lat = obj.getDouble("lat");
lang = obj.getDouble("lang");
keep them local only inside one loop of for inside onPostExecute
Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");
you should remove these declarations inside MapAcWithMarker class (on top)
//below to remove
public Double lat;
public Double lang;
public LatLng position;
//these are not used anywhere
public int selectionId= -1;
Marker markers;
next edit:
whole code of postExecute method
protected void onPostExecute(final JSONArray jsonarray) {
try{
final SparseArray<LatLng> positions = new SparseArray<>();
mMap.clear();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String pname = obj.getString("pname");
String bicycleno = obj.getString("bicycleno");
Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");
final LatLng position = new LatLng(lat, lang);
String title = "name: " + name;
mMap.addMarker(new MarkerOptions()
.position(position).title(title));
positions.put(i, position);
}
// set once, outside for loop
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if(positions.get(position)!=null)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position),15));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
I've inspected your code more carefully and... is a mess. you are not notifying adapter about new data/json (even if data in adapter matching parsed json on positions, titles etc. you should refresh layout). also every objects parsed from JSON are added to map as a Marker with mMap.addMarker(...) method, but I don't see any mMap.clear(); method called, so points may duplicate, when JSON is downloaded again (added this line above)
another edit - you have only one item drawn on list because you have inside onTextChanged method
for (int i =0 ; i <locationsList.size(); i++){
...
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);
...
}
creation of adapter should be done once, outside for loop. check after loop but before initiation that arrayListTemp have more items
for (int i =0 ; i <locationsList.size(); i++){
...
}
Log.d("#w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);
lot of bugs...

Related

Adding parsed JSON to a ListView and displaying it

public class GithubTab extends Fragment implements AdapterView.OnItemClickListener {
ListView repoListView;
private ListAdapter adapter;
private List<RepositoryItem> repoListItems;
private List<String> repoNameList;
private List<String> userNameList;
private List<String> descriptionList;
private TextView tvData;
private static final String TAG = "Github Tab";
Button buttonHit;
TextView resultText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.github_tab, container, false);
repoListView = (ListView) view.findViewById(R.id.repoList);
repoListItems = new ArrayList<>();
repoNameList = new ArrayList<>();
userNameList = new ArrayList<>();
descriptionList = new ArrayList<>();
adapter = new ListAdapter(getContext(), repoListItems);
repoListView.setAdapter(adapter);
tvData = (TextView) view.findViewById(R.id.tvJsonItem);
// Clickable: able to open the GitHub webpage of the re
repoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "Clicked id" + view.getTag(), Toast.LENGTH_SHORT).show();
}
});
new JSONTask().execute("https://api.github.com/users/whyjay17/repos");
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i, repoNameList.get(i), userNameList.get(i), "ddd"));
}
return view;
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
// Any non-UI thread process is running in this method. After completion, it sends the result to OnPostExecute
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
.... Code Hidden ....
return retreivedJson;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//cant close null
if (connection != null) {
// close both connection and the reader
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
//tvData.append(jsonObject.getString("name"));
repoNameList.add(jsonObject.getString("name"));
//Toast.makeText(getContext(), "1 " + repoNameList.get(1), Toast.LENGTH_SHORT).show();
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
//tvData.append(ownerObject.getString("login"));
userNameList.add(ownerObject.getString("login"));
//ownerObject.append(ownerObject.getString("avatar_url"));
}
}
}
}catch (JSONException jsonException){
}
}
/*
* Called after the background computation finishes. Result of doInBackground is passed in as a parameter.
*
* */
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* for JSONArray data*/
if(result!=null && !result.isEmpty()) {
formatJSONArray(result);
}
}
}
}
The code above basically tries to parse a JSON data from https://api.github.com/users/famous/repos, adds some certain info (repo name, id, description) to the corresponding lists, and tries to display that on the listView that I created.
The listView works when I hard code the information (meaning that there is no problem with the listView itself), but when I try to put in the data inside the list (which has the parsed JSON info and I tested that it is actually inside the list), it gives me an empty list.
How can I make this work?
The data come asynchronous so inside onCreateView() the list data may not be ready yet for adding to adapter.
You need to move the code that add elements to ListView adapter into onPostExecute(), after formatJSONArray() method, then call notifyDatasetChange() to invalidate the ListView
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* for JSONArray data*/
if(result!=null && !result.isEmpty()) {
formatJSONArray(result);
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i,
repoNameList.get(i), userNameList.get(i), "ddd"));
}
adapter.notifyDatasetChanged();
}
}
You can call adapter.notifiDatasetchange() in your formatJSONArray method:
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
//tvData.append(jsonObject.getString("name"));
repoNameList.add(jsonObject.getString("name"));
//Toast.makeText(getContext(), "1 " + repoNameList.get(1), Toast.LENGTH_SHORT).show();
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
//tvData.append(ownerObject.getString("login"));
userNameList.add(ownerObject.getString("login"));
//ownerObject.append(ownerObject.getString("avatar_url"));
}
}
}
adapter.notifiDatasetchange();
}catch (JSONException jsonException){
}
}
If it don't work , you can set adapter again in your formatJSONArray method
adapter = new ListAdapter(getContext(), repoListItems);
repoListView.setAdapter(adapter);
It worked for me. I hope it can help your problem!
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i,repoNameList.get(i),userNameList.get(i), "ddd"));
}
adapter.notifyDataSetChanged();
`
add this line before
}catch (JSONException jsonException){

Passing Data from Fragment listview item to Activity string variable onitemclicklistener

I am trying to pass a ListView item from a fragment to a String variable "url" in activity, The intent successfully creates the activity however I run issues into it when I try passing data.
the fragment class has a listview with json data that brings up the list of picture,title and name. when a user selects an item it brings them to the activity. I want their selection transfer the name from the listview to the url variable in the other activity. so the url changed from "https://.....id=" to "https://.....id="+name from the fragment.
thats will make the recyclerview changed with the new url for any listview item clicked.
my fragment:
public class Accueil extends Fragment {
ArrayList<articles> arrayList;
ListView lv;
public static String URL1=null;
class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(content);
} catch (JSONException e1) {
e1.printStackTrace();
}
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("articles");
} catch (JSONException e1) {
e1.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articlesobject = null;
try {
articlesobject = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
arrayList.add(new articles(
articlesobject.getString("picture"),
articlesobject.getString("title"),
articlesobject.getString("name")
));
} catch (JSONException e1) {
e1.printStackTrace();
}
CustomListAdaper adaper = new CustomListAdaper(
getActivity().getApplicationContext(),
R.layout.custom_list_layout, arrayList
);
lv.setAdapter(adaper);
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
arrayList = new ArrayList<>();
View rootView = inflater.inflate(R.layout.accueil, container, false);
lv = (ListView) rootView.findViewById(R.id.ListView1);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
new Accueil.ReadJSON().execute("http://wach.ma/mobile/home.php");
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList =
(lv.getItemAtPosition(position).toString());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;
}
}
my activity:
public class Test extends AppCompatActivity {
public String URL_DATA="http://wach.ma/mobile/category.php?id=";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
Intent i = getIntent();
String s1 = i.getStringExtra("name");
URL_DATA=URL_DATA+s1;
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("articles");
for(int i = 0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("picture"),
o.getString("name"),
o.getString("city"),
o.getString("add_time"),
o.getString("price")
);
listItems.add(item);
}
adapter = new Myadapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(),
volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Thank you in advance, and i'm very sorry for my bad English
Your problem comes from this I think : String selectedFromList =
(lv.getItemAtPosition(position).toString());
lv.getItemAtPosition(position) returns an Object which is an item of the listView Adapter !
Calling toString() on this object will return nothing good :)
The OnClickListener has a View in parameter which is the parent View, in your case, the Item View you clicked.
You can retrieve the TextView holding the name field in the OnClickListener and get the string of this TextView like this :
#Override
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
String name = ((TextView) view.findViewById(R.id.myNameField)).getText().toString();
}
Hope that will help you :)
PS : Post your XML code as well next time ;)
I fix it, just change this:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList =
(lv.getItemAtPosition(position).toString());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;
to this:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList=
String.valueOf(arrayList.get(position).getIdd());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;

How do i get the right content in Single Item View

After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}

Refresh map markers on android with button

i am running a web service with some json data which i use to make markers on my map(this gets updated every hour).i want to add button on my android map so that i will refresh the markers data.any idea without changing much of the structure?should i do something on the threads?or restart the activity?
heres is the code
public class MainActivity extends FragmentActivity {
private static final String LOG_TAG = "jsonmap";
private static final String SERVICE_URL = "http://7a27183e.ngrok.com";
public GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_maps);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
map = mapFragment.getMap();
if (map != null) {
setUpMap();
// new MarkerTask().execute();
}
}
}
private void setUpMap() {
UiSettings settings = map.getUiSettings();
settings.setZoomControlsEnabled(true);
settings.setScrollGesturesEnabled(true);
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
//.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
// .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
//DATE!!
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
.snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))
.position(new LatLng(
jsonObj.getDouble("x"),
jsonObj.getDouble("y")))
.icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoContents(Marker arg0) {
return null;
}
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.customlayout, null);
TextView tTitle = (TextView) v.findViewById(R.id.title);
TextView tSnippet = (TextView) v.findViewById(R.id.snippet);
tTitle.setText(arg0.getTitle());
tSnippet.setText(arg0.getSnippet());
return v;
}
});
}
}
}
this is the json structure:
https://gist.githubusercontent.com/anonymous/42af315ab003ab01764d/raw/79b6cf5451038bd2e35c376766e9ab44bd385a02/gistfile2.txt
and a screenshot:
http://imgur.com/WZNC9Oz
I have done some modification in your method named createMarkersFromJson() at line map.addMarker(). Now you can use changeMarkerPosition() to change the position of marker.
HashMap<String, Marker> markerHashMap = new HashMap<>();
void changeMarkerPosition(String key, LatLng latLng) {
markerHashMap.get(key).setPosition(latLng);
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
//.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
// .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
//DATE!!
JSONObject jsonObj = jsonArray.getJSONObject(i);
markerHashMap.put("key"+i,(map.addMarker(new MarkerOptions()
.title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
.snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))
.position(new LatLng(
jsonObj.getDouble("x"),
jsonObj.getDouble("y")))
.icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
);)
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoContents(Marker arg0) {
return null;
}
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.customlayout, null);
TextView tTitle = (TextView) v.findViewById(R.id.title);
TextView tSnippet = (TextView) v.findViewById(R.id.snippet);
tTitle.setText(arg0.getTitle());
tSnippet.setText(arg0.getSnippet());
return v;
}
});
}

To get Id of selected item in spinner android

Here, It is my java file
public class Create_Event extends SherlockFragment
implements OnClickListener {
class Organizer extends AsyncTask<Void, Void, Object> {
private ProgressDialog pdia;
protected void onPreExecute() {
super.onPreExecute();
pdia = new ProgressDialog(getActivity());
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected Object doInBackground(Void... params) {
try {
HttpClient httpclient1 = new DefaultHttpClient();
HttpPost httppost1 = new HttpPost(Constants.BASE_URL
+ "mobile_logins/all_my_event");
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1);
nameValuePairs1.add(new BasicNameValuePair("id", Constants.id));
httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse response1 = httpclient1.execute(httppost1);
String _response1 = EntityUtils.toString(response1.getEntity());
Log.e("test", _response1);
jsobj1 = new JSONObject(_response1);
orr = jsobj1.getJSONArray("organizers");
String orggg = orr.toString();
Log.e("Organization", orggg);
return jsobj1;
} catch (Exception e) {
e.printStackTrace();
Log.e("Fail 1", e.toString());
return e;
}
}
protected void onPostExecute(Object jsobj) {
pdia.dismiss();
String post = jsobj.toString();
Log.e("event_rese", post);
int len = orr.length();
Log.e("json_posexe", orr.toString());
Log.e("Onpostexe_arrlength", String.valueOf(len));
try {
JSONArray JA = orr;
JSONObject json1 = null;
final String[] host1 = new String[orr.length()];
final String[] host_id=new String[orr.length()];
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < host1.length; i++) {
list.add(host1[i]);
}
Log.e("onpostexe_list",list.toString());
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
organization=sp.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
if (json instanceof JSONObject) {
asyncrun = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
} else {
ExecptionHandler.register(getActivity(), (Exception) jsobj);
}
}
}
}
}
Here, I need id of the selected organization from spinner. The id and organization name came from Jsonobject(here jsobj1). How to get id of selected item from jsonobject? Is it possible?? Please Help...
Create a Organization bean as below with method #Override toString()
public class Organization {
private Integer orgId; // Long etc.
private String orgName;
// more properties if you need
#Override // Mandatory
public String toString() {
return orgName; // Return anything, what you want to show in spinner
}
// Getter & Setter
}
Then Create a java.util.List<Organization> organizationList; from your API response JSONArray or any other way. And make and set ArrayAdapter<Organization> to load Spinner options.
List<Organization> organizationList = ... // init using JSON Data OR any how;
ArrayAdapter<Organization> orgAdapter = new ArrayAdapter<Organization>(this, android.R.layout.simple_spinner_item, organizationList);
orgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner mySpinner = findViewById(R.id.orgSpinner);
mySpinner.setAdapter(orgAdapter);
Now get selected Organization and its Properties in any Click/Change Event like below
// In any OnClick / OnSelect event
Organization selectedOrganization = (Organization) mySpinner.getSelectedItem();
Integer orgId = selectedOrganization.getOrgId();
String orgName = selectedOrganization.getOrgName();
// and if you have more properties
Yes,it is Possible, try like below.
HashMap<String,String> map_values = new HashMap<String,String>();
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
map_values.put(host1[i],host_id[i]);
}
and spinner
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
String value = sp.getSelectedItem().toString();
String id = map_values.get(value);
Log.v("id",""+id);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
mSpinner.getSelectedItemId(); // here is your selected item's Id.
BTW google first, ask later :)

Categories

Resources