I tried to create code to get all users from my server except me.
It is not jumping to the #overwrite response.
I hope sombody can help me.
I was looking now for days why it's not working
XD didnt found the prob.
My php code:
<?php
$con = mysqli_connect("localhost", "userID", "password", "database");
$name = $_POST["name"];
$passwort = $_POST["passwort"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE name = ? AND passwort = ?");
mysqli_stmt_bind_param($statement, "ss", $name, $passwort);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $vorname, $nachname, $passwort);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["vorname"] = $vorname;
$response["nachname"] = $nachname;
$response["passwort"] = $passwort;
}
echo json_encode($response);
?>
In JAVA they all come together:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Adapter;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.android.app.Data.LoginRequest;
import com.example.android.app.Data.RegistryRequest;
import com.example.android.app.Data.UserlistRequest;
import com.example.android.app.Tools.User;
import com.example.android.app.Tools.UserAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Map;
public class listeAndererActivity extends AppCompatActivity {
private String Tag="lsiteanderer";
private ArrayList<User> userListe = new ArrayList<>();
private UserAdapter useradapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_liste_anderer);
String ownname="juli";
/////VERSION 2///////////////////////////////////////////////////////////////
Response.Listener<JSONArray> responseListenerJSONArray=new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject (i);
User user = new User (obj.getString ("name"),obj.getInt("user_id"));
Log.v(Tag, "name in der for schlife ist"+user.getName());
userListe.add(user);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
useradapter=new UserAdapter(this, userListe);
UserlistRequest userlistRequest = new UserlistRequest(ownname, responseListenerJSONArray);
RequestQueue queue= Volley.newRequestQueue(listeAndererActivity.this);
queue.add(userlistRequest);
ListView listView = (ListView) findViewById(R.id.AndererListe);
listView.setAdapter(useradapter);
}
}
My Reqest Class:
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Juli on 17.12.2017.
*/
public class UserlistRequest extends JsonArrayRequest {
private static final String userlistRequestUrl="https://unityentertainment.000webhostapp.com/OtherUser.php";
private Map<String,String> params;
public UserlistRequest(String name, Response.Listener<JSONArray> listener){
super(Request.Method.POST, userlistRequestUrl, listener, null);
params= new HashMap<>();
params.put("name", name);
}
// public UserlistRequest(String ownname, Listener<JSONArray> responseListenerJSONArray) {
// super();
// }
#Override
public Map<String, String> getParams() {
return params;
}
}
My Data Class:
public class User {
private String name;
private int user_id;
public User(String name, int user_id){
this.name=name;
this.user_id=user_id;
}
public String getName() {
return name;
}
public int getUser_id() {
return user_id;
}
}
My Adapter:
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.example.android.app.R;
import com.example.android.app.ListeAndererActivity;
import java.util.ArrayList;
public class UserAdapter extends ArrayAdapter<User> {
public UserAdapter(ListeAndererActivity activity, ArrayList<User> userArrayList) {
super((Context) activity, 0 ,userArrayList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.itemlist_user, parent, false);
}
// Get the {#link AndroidFlavor} object located at this position in the list
User currentAndroidFlavor = getItem(position);
// Find the TextView in the list_item.xml layout with the ID version_name
TextView nameTextView = (TextView) listItemView.findViewById(R.id.itemlistUser_TextView);
// Get the version name from the current AndroidFlavor object and
// set this text on the name TextView
nameTextView.setText(currentAndroidFlavor.getName());
return listItemView;
}
}
you should track your request and response and see where it stops. Use somthing like postman or some firefox/chrome plugin to test the back end php rest API part of your code and narrow down the possibilities and also monitor the testing device log by printing values and look where your code is stopping or behave different than intended.
from my opinion you should first use api testing softwares like postman.
postman is great for that.
also this worked for me
$stmt=$db->prepare("SELECT * FROM search WHERE designation LIKE ?");
$stmt->bind_param("s",$a);
$stmt->execute();
$d=$stmt->get_result();
while($b=$d->fetch_array(MYSQLI_ASSOC)){
$result[]=$b;
}
//you could then do something like this
$response['test']=$result;
echo json_encode($result);
I did like below:
public class UserlistRequest extends JsonArrayRequest {
private static final String userlistRequestUrl="https://unityentertainment.000webhostapp.com/OtherUser.php";
private Map<String,String> params;
public UserlistRequest(String name, Response.Listener<JSONArray> listener) {
super(Method.POST, userlistRequestUrl, (String) null, listener, null);
// public UserlistRequest(String name, Response.Listener<JSONArray> listener){
// super(Request.Method.POST, userlistRequestUrl, listener, null);
params= new HashMap<>();
params.put("name", name);
params.put("name", name);
}
// public UserlistRequest(String ownname, Listener<JSONArray> responseListenerJSONArray) {
// super();
// }
#Override
public Map<String, String> getParams() {
return params;
}
}
But it doesn't use the getparams
Related
I m getting volley timeout error every time i try to insert data..Despite of the error, the data is inserted correctly but its inserting two times every time i press the button.
I need to remove the error and insert data only once. Also it takes too much time after clicking button to display error.
package com.example.sumit.myapplication;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Sumit on 20-02-2018.
*/
public class register extends Fragment{
RequestQueue requestQueue;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
View v = inflater.inflate(R.layout.login,container,false);
return v;
}
public void onCreate(Bundle savedInstancesState)
{
super.onCreate(savedInstancesState);
TextView t = (TextView) ((MainActivity) getActivity()).findViewById(R.id.textView3);
t.setText("Register");
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
final View vt = super.getView();
final CardView b=(CardView)vt.findViewById(R.id.cardView);
final TextView txt = (TextView)vt.findViewById(R.id.uid);
final EditText txt1 = (EditText) vt.findViewById(R.id.editText);
final EditText txt2 = (EditText) vt.findViewById(R.id.editText2);
final EditText txt3 = (EditText) vt.findViewById(R.id.editText3);
final EditText txt4 = (EditText) vt.findViewById(R.id.editText4);
final Spinner hostel1=(Spinner) vt.findViewById(R.id.spinner1);
final Spinner branch1=(Spinner) vt.findViewById(R.id.spinner2);
final String HttpUrl = "https://testzineapp.000webhostapp.com/insert_record.php";
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vt) {
final String id=txt1.getText().toString().trim();
final String name=txt2.getText().toString().trim();
final String number=txt3.getText().toString().trim();
final String email=txt4.getText().toString().trim();
final String hostel=hostel1.getSelectedItem().toString().trim();
final String branch=branch1.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
// Showing response message coming from server.
Toast.makeText(getContext(), ServerResponse, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Showing error message if something goes wrong.
Toast.makeText(getContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("College_ID", id);
params.put("Name", name);
params.put("Mobile_Number", number);
params.put("Email_ID", email);
params.put("Hosteller", hostel);
params.put("Branch", branch);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
txt1.setText("");
txt2.setText("");
txt3.setText("");
txt4.setText("");
};
});
super.onViewCreated(view, savedInstanceState);
}
}
Because of volley default retry policy your your request is processing two times, try this code to avoid it.
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(_context);
requestQueue.add(stringRequest);
I am new to Java so please excuse any silly or obvious mistake. I have a activity that pulls a json encoded string from a PHP file and put it into a simple list view. I am getting the dreaded red squiggly lines and what is to me a cryptic error message. Here is my code. I appreciate any assistance.
package --Hidden--;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class tracklist extends Activity implements OnItemClickListener {
private static final String URL = "http://rickthompson.com/json/fetchtracks.php";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracklist);
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
R.layout.rowlayout, R.id.label, profileUserOptions);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
///////////// login script
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.names().get(0).equals("tracks")) {
Toast.makeText(getApplicationContext(), "tracks " + jsonObject.getString("tracks"), Toast.LENGTH_LONG).show();
/// save user id in prefs
JSONArray contacts = jsonObject.getJSONArray("tracks");
HashMap<String, String> trackview = null;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String isrc = c.getString("isrc");
trackview = new HashMap<>();
trackview.put("isrc", isrc);
}
trackview.toString();
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.rowlayout, R.id.label, trackview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
} else {
Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
SharedPreferences userPrefs = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String userid = userPrefs.getString("memberid", "");
hashMap.put("u", userid);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
hashMap.put("sg", selectedSubGenre);
return hashMap;
}
};
requestQueue.add(request);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "something clicked", Toast.LENGTH_LONG).show();
}
}
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("tracks")){
//rest of the code
}
In the above code I hope you are trying to get "name" array which should be
JSONArray jso3 = new JSONArray (jsonObject.getString("names"));
Please provide the error details so that i can give you a detailed description.
I have a class which implements serializable and I am trying to send it's object using intent , so I am getting null object when I set that object using putExtra();
Below is my code.
YelpSearch.java(fromClass)
import android.app.ListActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class YelpSearch extends ListActivity implements Serializable {
#SuppressWarnings("serial")
class Business implements Serializable {
final String name;
final String url;
final String id;
public Business(String name, String url, String id) {
this.name = name;
this.url = url;
this.id = id;
}
#Override
public String toString() {
return name;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setTitle("Finding Tacos...");
setProgressBarIndeterminateVisibility(true);
Log.v("TAG","YelpSearchOnCreate");
new AsyncTask<Void, Void, List<Business>>() {
#Override
protected List<Business> doInBackground(Void... params) {
Log.v("TAG","Async List");
String businesses = Yelp.getYelp(YelpSearch.this).search("food", "91754");
Log.v("TAG","String businsesses"+businesses);
try {
Log.v("TAG","try");
return processJson(businesses);
} catch (JSONException e) {
return Collections.<Business>emptyList();
}
}
#Override
protected void onPostExecute(List<Business> businesses) {
Log.v("TAG","onPostExecute");
Log.v("BusinessesList","Businesses "+ businesses);
//setTitle("Tacos Found");
setProgressBarIndeterminateVisibility(false);
getListView().setAdapter(new ArrayAdapter<Business>(YelpSearch.this, android.R.layout.simple_list_item_1, businesses));
}
}.execute();
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
Business biz = (Business) listView.getItemAtPosition(position);
Log.v("Sending data to Detail","hi "+biz);
//startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(biz.url)));
Intent intent = new Intent(getApplicationContext(), YelpBizDetail.class);
// Intent intent = new Intent(YelpSearch.this,YelpBizDetail.class).putExtra("myCustomerObj",biz);
intent.putExtra("Detailclass",biz);
Log.v("Sending data to Detail","sent "+biz);
startActivity(intent);
}
List<Business> processJson(String jsonStuff) throws JSONException {
JSONObject json = new JSONObject(jsonStuff);
JSONArray businesses = json.getJSONArray("businesses");
ArrayList<Business> businessObjs = new ArrayList<Business>(businesses.length());
for (int i = 0; i < businesses.length(); i++) {
JSONObject business = businesses.getJSONObject(i);
businessObjs.add(new Business(business.optString("name"), business.optString("mobile_url"),business.optString("id")));
}
return businessObjs;
}
}
YelpBizDetail(toClass)
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import com.....projectmaw.YelpSearch.Business;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class YelpBizDetail extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yelp_biz_detail);
Intent i = getIntent();
Business biz = (Business) i.getSerializableExtra("Detailclass");
// String biz = (String) i.getSerializableExtra("Detailclass");
//String biz = (String) i.getSerializableExtra("Detailclass");
Log.v("Received on Detail","data "+biz);
}
}
Try making some changes in onListItemClick in your YelpSearch.java, like change your startActivity(intent) with
startActivity(new Intent(getApplicationContext(), YelpBizDetail.class).putExtra("Detailclass",biz)); this will create new intent when new activity is started. and remove
Log.v("Sending data to Detail","hi "+biz);
//startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(biz.url)));
Intent intent = new Intent(getApplicationContext(), YelpBizDetail.class);
// Intent intent = new Intent(YelpSearch.this,YelpBizDetail.class).putExtra("myCustomerObj",biz);
intent.putExtra("Detailclass",biz);
Log.v("Sending data to Detail","sent "+biz);
I have some dummy problem, I need to get Spinner Item Position from the Fragment to this class:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.objects.Person;
import com.example.nortti.politrange.objects.Site;
import com.example.nortti.politrange.utils.WebApiAdapter;
import com.example.nortti.politrange.views.GeneralFragment;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class PersonCatalog implements ICatalog{
private final String COMMAND_PREFIX = "/api/stats/1";
private final WebApiAdapter apiAdapter = new WebApiAdapter(COMMAND_PREFIX);
private ArrayList<Person> catalogList = new ArrayList<Person>();
private Site site;
public PersonCatalog(Site site) {
this.site = site;
}
#Override
public ArrayList<Person> getCatalogList() {
return catalogList;
}
public void populateData() {
JSONArray jsonObject = null;
try {
jsonObject = (JSONArray)(new JSONParser()).parse(apiAdapter.select(null));
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
catalogList.clear();
Iterator<JSONObject> iterator = jsonObject.iterator();
while(iterator.hasNext()) {
JSONObject o = iterator.next();
catalogList.add(new Person((String)o.get("personName"),(int)(long)o.get("rank")));
}
}
}
I broke my head, I don't know how to do it. Please help! Should I use some Intents or create some getters?
UPD: Fragment Code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.adapters.GenAdapter;
import com.example.nortti.politrange.adapters.SiteAdapter;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.intefaces.impls.PersonCatalog;
import com.example.nortti.politrange.intefaces.impls.SitesCatalog;
import com.example.nortti.politrange.objects.Site;
public class GeneralFragment extends Fragment implements OnClickListener, OnItemSelectedListener {
private Button genApply;
private Spinner spinner;
private ListView genList;
private View header;
private ICatalog siteCatalogImpl;
private ICatalog personCatalogImpl;
public int Num;
public void setSpinnerSource(ICatalog siteCatalogImpl) {
this.siteCatalogImpl = siteCatalogImpl;
spinData();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.general_fragment, container,false);
header = inflater.inflate(R.layout.gen_head, null);
spinner = (Spinner) v.findViewById(R.id.wSpin);
spinner.setOnItemSelectedListener(this);
genApply = (Button) v.findViewById(R.id.genApply);
genApply.setOnClickListener(this);
genList = (ListView) v.findViewById(R.id.genList);
genList.addHeaderView(header);
this.setSpinnerSource(new SitesCatalog());
Intent i = new Intent();
i.putExtra("spin", spinner.getSelectedItemPosition()+1);
return v;
}
private void spinData() {
siteCatalogImpl.populateData();
spinner.setAdapter(new SiteAdapter(getActivity(), siteCatalogImpl.getCatalogList()));
}
private void listData(Site site) {
personCatalogImpl = new PersonCatalog(site);
personCatalogImpl.populateData();
genList.setAdapter(new GenAdapter(getActivity(), personCatalogImpl.getCatalogList()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
int siteIndex = spinner.getSelectedItemPosition();
switch (v.getId()) {
case R.id.genApply:
listData((Site)siteCatalogImpl.getCatalogList().get(siteIndex));
break;
}
}
}
I calling PersonCatalog at the listdata method.
Try this.
final ArrayList<String> providerlist= new ArrayList<String>();
Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = providerlist.get(position);
// Showing selected spinner item
Toast.makeText(this,
"Selected Country : " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I am building a search app using fragments for each screen. I have the search working and storing the JSON results in an ArrayList<Map<String, String>>in the main activity so the other fragments can access it. the current problem is on my resultsFragment I have a Google MapFragment embedded in the main ListFragment and a listView below that. The map is successfully populated, but the list is empty. I have spent hours trying to figure this out. Here is the code for resultsFragment
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.Map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ResultsFragment extends ListFragment {
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_results, container, false);
//Get search results from stored ArrayList
resultsList = MainActivity.getResultsList();
//Build listView from results
ListView lv =(ListView) getActivity().findViewById(android.R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), resultsList,
R.layout.custom_row_view, new String[] { "AgencyID", "AgencyName",
"Address1" }, new int[] { R.id.text1, R.id.text2,
R.id.text3 });
// updating listview
setListAdapter(adapter);
//Setup embedded Google Map fragment
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Add markers to the map from resultsList
for (int i = 0; i < resultsList.size(); i++) {
Double latitude = Double.valueOf(resultsList.get(i).get("Lat"));
Double longitude = Double.valueOf(resultsList.get(i).get("Lng"));
String mname = resultsList.get(i).get("AgencyName");
LatLng posit = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(posit)
.title(mname));
}
return rootView;
}
}
In case its helpful here is the code from my homeFragment (where the search results are stored to the ArrayList)
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import com.wny.wecare.handler.JSONParser;
public class HomeFragment extends Fragment implements OnItemSelectedListener, OnClickListener{
private OnFragmentInteractionListener mListener;
private Spinner spinner;
private Button btnSubmit;
private static final String[] list={"Alden", "Amherst", "Angola",
"Blasdell", "Boston", "Bowmansville", "Buffalo", "Cheektowaga", "Clarence",
"Depew", "Derby", "East Aurora", "Eden", "Elma", "Getzville", "Gowanda",
"Grand Island", "Holland", "Irving", "Kenmore", "Lackawanna", "Lake View",
"Lancaster", "Lawtons", "North Collins", "Orchard Park", "Snyder", "Springville",
"Tonawanda", "West Seneca", "Williamsville"};
// Setup ArrayList from main activity to store results
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray agency = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
btnSubmit = (Button) rootView.findViewById(R.id.town_search);
btnSubmit.setOnClickListener(this);
spinner =(Spinner)rootView.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
return rootView;
}
// Check if parent activity implements the interface
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener =
(OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
//add items into spinner dynamically
/*public void addItemsOnSpinner2(View v) {
addItemsOnSpinner2(v);
final List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}*/
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.town_search:
String town = (String) spinner.getSelectedItem().toString();
agencySearch(town);
mListener.onFragmentButton();
break;
case R.id.zip_search:
String strZip = ((EditText) v.findViewById(R.id.txt_zip)).getText().toString().trim();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;
/*case R.id.btn_location:
String strZip = v.findViewById(R.id.txt_zip).toString();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;*/
}
}
#Override
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
public void agencySearch(int zsearch) {
// Setting the URL for the Search by Zip
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_zip.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("zip", Integer.toString(zsearch)));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
}