SearchActivity as below:
public class SearchActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private SimpleCursorAdapter myAdapter;
SearchView searchView = null;
private WarehouseSalesDetails[] strArrData;
private String selectedID;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search_item);
Toolbar toolBarSearch = (Toolbar)findViewById(R.id.toolbarSearch);
setSupportActionBar(toolBarSearch);
final String[] from = new String[]{"title"};
final int[] to = new int[]{android.R.id.text1};
//setup SimpleCursorAdapter
myAdapter = new SimpleCursorAdapter(SearchActivity.this,android.R.layout.simple_spinner_dropdown_item,null,from,to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
new RetrieveWarehouseSalesTask(this).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_search,menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager)SearchActivity.this.getSystemService(Context.SEARCH_SERVICE);
if(searchItem!=null){
searchView = (SearchView) searchItem.getActionView();
}
if(searchView!=null){
searchView.setSearchableInfo(searchManager.getSearchableInfo(SearchActivity.this.getComponentName()));
searchView.setIconified(false);
searchView.setSuggestionsAdapter(myAdapter);
//getting selected on item suggestion
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener(){
#Override
public boolean onSuggestionClick(int position){
//Add clicked text to search box
CursorAdapter ca = searchView.getSuggestionsAdapter();
Cursor cursor = ca.getCursor();
cursor.moveToPosition(position);
searchView.setQuery(cursor.getString(cursor.getColumnIndex("title")),false);
Log.d("strArr id",strArrData[position].id);
selectedID = strArrData[position].id;
return true;
}
#Override
public boolean onSuggestionSelect(int position){
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String s){
Intent intent = new Intent(SearchActivity.this,RetrieveIndividualWarehouseSales.class);
intent.putExtra("pid",selectedID);
startActivity(intent);
return false;
}
#Override
public boolean onQueryTextChange(String s){
//filter data
final MatrixCursor mc = new MatrixCursor(new String[]{
BaseColumns._ID,"title"
});
for(int i = 0; i<strArrData.length; i++){
if(strArrData[i].title.toLowerCase().startsWith(s.toLowerCase())){
mc.addRow(new Object[]{i,strArrData[i].title});
}
}
myAdapter.changeCursor(mc);
return false;
}
});
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return super.onOptionsItemSelected(item);
}
#Override
protected void onNewIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction())){
String query = intent.getStringExtra(SearchManager.QUERY);
if(searchView!=null){
searchView.clearFocus();
}
}
}
class RetrieveWarehouseSalesTask extends AsyncTask<Void,Void,Void> {
private String TAG = ActiveWarehouseSalesFragment.RetrieveWarehouseSalesTask.class.getSimpleName();
private String TAG_PID = "pid";
public ProgressDialog pDialog;
private Context context;
//URL to get JSON details
private String url = "http://example.com/example.php";
ArrayList<HashMap<String,String>> sales_details;
List<WarehouseSalesDetails> data = new ArrayList<>();
JSONObject jsonObj;
String jsonStr;
JSONArray sales;
//for recycler view
private RecyclerView warehouse_recycler;
private AdapterRecycler mAdapter;
public RetrieveWarehouseSalesTask(Context context){
this.context = context;
sales_details = new ArrayList<>();
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Searching...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0){
HttpHandler sh = new HttpHandler();
//making a request to URL and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url (SearchActivity): " + jsonStr);
return null;
}
#Override
protected void onPostExecute(Void result){
//ArrayList<String> dataList = new ArrayList<String>();
super.onPostExecute(result);
if(pDialog.isShowing()){
pDialog.dismiss();
}
if(jsonStr != null){
try{
jsonObj = new JSONObject(jsonStr);
//Getting JSON Array Node
sales = jsonObj.getJSONArray("Result");
//looping through all results
for(int i = sales.length() - 1; i >= 0 ;i--){
JSONObject s = sales.getJSONObject(i);
WarehouseSalesDetails wsd = new WarehouseSalesDetails();
wsd.id = s.getString("id");
wsd.company_name = s.getString("company_name");
wsd.promotion_image= s.getString("promotion_image");
wsd.title = s.getString("title");
wsd.promotional_period = s.getString("promotional_period");
wsd.viewCount = s.getString("view_count");
data.add(wsd);
}
//strArrData = dataList.toArray(new String[dataList.size()]);
strArrData = data.toArray(new WarehouseSalesDetails[data.size()]);
Log.d("TAG",sales_details.toString());
}catch(final JSONException e){
Log.e(TAG, "JSON parsing error: " + e.getMessage());
}
}else{
Log.e(TAG,"Couldn't get json from server");
}
/*//update RecyclerView
warehouse_recycler = (RecyclerView)((AppCompatActivity) context).findViewById(R.id.recyclerView);
mAdapter = new AdapterRecycler(context, data);
System.out.println("mAdapter size is: " + mAdapter.getItemCount());
System.out.println("Data size is: " + data.size());
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
warehouse_recycler.setLayoutManager(layoutManager);
//mAdapter.notifyDataSetChanged();
warehouse_recycler.setAdapter(mAdapter);
warehouse_recycler.invalidate();
*/
}
}
}
I am trying to call an activity when user make a search on the search bar. I am storing id and title in strArrData. The suggestions displayed shows correct values. However, when I clicks on either of the suggestions, it always pass in the wrong id. And I found out that, the array always stores the values of the first few json values. How should I fix this ?
Found a solution by using Hashmap.
First of all store all your json values in hashmap as below:
HashMap<String, String> idMap = new HashMap<String, String>();
idMap.put(s.getString("id"),s.getString("title"));
Secondly, implement this method in your class to get the hashmap key based on hashmap value:
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
And finally:
String selectedID = getKeyFromValue(idMap,selectedTitle).toString();
Log.d("selected id",selectedID);
Intent intent = new Intent(SearchActivity.this,NextActivity.class);
intent.putExtra("pid",selectedID);
startActivity(intent);
Related
Hi guys I dont have much experience with AsyncTask and this is my first time using RecyclerView besides a couple of tutorials I done to learn about it.
If I use dummy data in EventActivity everything works fine and a list shown on the screen. But when I create an ArrayList of EventItems and pass that to the adapter it's just a blank screen. The JSON from localhost is being parsed and sent to the EventItem class. I have tried several things to get it to work but as my experience with AsyncTask and RecyclerView are limited I end up just crashing the app and getting a null pointer exception.
I think that the RecyclerView is being created before the JSON has been retrieved from localhost and this is what's causing the blank screen or null pointer exception but I'm not 100% sure and dont know how to fix the issue if I am correct.
Any help is appreciated.
EventActivity
public class EventActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
fetchEvents();//call EventBackgroundWorker
//ArrayList<EventItem> eventList = new EventItem().getRecyclerList();//causes java null pointer exception
ArrayList<EventItem> eventList = new ArrayList<>();
//Dummie data
// eventList.add(new EventItem (1, "Title1", "Date", "endDate", "Location1", 5, 1111));
// eventList.add(new EventItem (R.drawable.ic_favourite, "Title2", "11/07/2018", "11/07/2018", "Wales", 10, 5));
// eventList.add(new EventItem (R.drawable.ramspeed_custom, "Title3", "11/01/2018", "11/09/2018", "Paris, France", 0, 90));
// eventList.add(new EventItem (R.drawable.ramspeed_custom, "Title4", "12/01/2018", "11/09/2018", "New York", 20, 500));
// eventList.add(new EventItem (R.drawable.ic_favourite, "Title5", "Mon 11/05/2015", "11/09/2018", "London, England", 5, 500));
// eventList.add(new EventItem (R.drawable.biker, "Title6", "Mon 11/05/2018", "20/07/2018", "Swords Dublin", 0, 500));
mRecyclerView = (RecyclerView) findViewById(R.id.event_recycler_view);
mRecyclerView.setHasFixedSize(true);//increase performance of app if recyclerView does not increase in size
mLayoutManager = new LinearLayoutManager(this);
// mAdapter = new EventAdapter(eventList);
mAdapter = new EventAdapter(eventList);//context added for testing //////////////////////////////
// mAdapter = new EventAdapter(new ArrayList<EventItem>(0));
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
// buildRecyclerView();
}
//run background thread
private void fetchEvents(){
// String username = "user";
// String userPassword = "password";
String startConnectionCondition = "event";
//this passes the context
EventBackgroundWorker backgroundWorker = new EventBackgroundWorker(this);
backgroundWorker.execute(startConnectionCondition, null);
}
/* private void buildRecyclerView(){
ArrayList<EventItem> eventList = new EventItem().getRecyclerList();
mRecyclerView = (RecyclerView) findViewById(R.id.event_recycler_view);
mRecyclerView.setHasFixedSize(true);//increase performance of app if recyclerView does not increase in size
mLayoutManager = new LinearLayoutManager(this);
// mAdapter = new EventAdapter(eventList);
mAdapter = new EventAdapter(eventList);//context added for testing
// mAdapter = new EventAdapter(new ArrayList<EventItem>(0));
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
*/
/* public void showEventList(boolean b){
ArrayList<EventItem> eventList = new ArrayList<>();
for(int i =0; i< eventList.size(); i++){
eventList.get(i);
Log.d("tag","eventList from main " + eventList);
}
mAdapter = new EventAdapter(eventList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}*/
}//MainActivity
EventAdapter
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private ArrayList<EventItem> mEventList;
Context context;
//constructor for EventAdapter
public EventAdapter(ArrayList<EventItem> eventList){
// context =c;
mEventList = eventList;
Log.d("tag","EventAdapter eventlist variable called from constructor " + eventList);
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public ImageView mPromoImage;
public TextView mTitle;
public TextView mStartDate;
public TextView mEndDate;
public TextView mLocation;
public TextView mFee;
public ImageView mFavourite;
//constructor for EventViewHolder class
public EventViewHolder(View itemView) {
super(itemView);
// mPromoImage = (ImageView) itemView.findViewById(R.id.event_promotional_image);
mTitle = (TextView) itemView.findViewById(R.id.event_title_textView);
mStartDate = (TextView) itemView.findViewById(R.id.event_start_textView);
mEndDate = (TextView) itemView.findViewById(R.id.event_end_textView);
mLocation = (TextView) itemView.findViewById(R.id.event_location_textView);
mFee = (TextView) itemView.findViewById(R.id.event_fee_textView);
// mFavourite = (ImageView) itemView.findViewById(R.id.event_favourite_image);
Log.d("tag", "EventViewHolder being called");
}
}//EventViewHolder class
#Override
public EventViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_event, parent, false);
//create view holder
EventViewHolder viewHolder = new EventViewHolder(v);
return viewHolder;
}
//pass values to inflated XML Views in item_event.xml
#Override
public void onBindViewHolder(EventViewHolder holder, int position) {
EventItem currentEvent = mEventList.get(position);
// holder.mPromoImage.setImageResource(currentEvent.getEventPromoImage());
holder.mTitle.setText(currentEvent.getEventTitle());
holder.mStartDate.setText(currentEvent.getEventStartDate());
holder.mEndDate.setText(currentEvent.getEventEndDate());
holder.mLocation.setText(currentEvent.getEventLocation());
holder.mFee.setText(String.valueOf(currentEvent.getEventFee()));//int value passed
// holder.mFavourite.setImageResource(currentEvent.getEventFavourite());
//Log.d("tag", "position" + position );
Log.d("tag","eventAdapter " + currentEvent.getEventTitle());
}
//how many items there will be
#Override
public int getItemCount() {
return mEventList.size();
}
}
EventItem
public class EventItem {
private int mEventPromoImage;
private int mId;
private String mEventTitle;
private String mEventStartDate;
private String mEventEndDate;
private String mEventLocation;
private int mEventFee;
private int mEventViews;
// public EventItem(){}
public EventItem(int id, String eventTitle, String eventStartDate,
String eventEndDate, String eventLocation, int eventFee, int eventViews){
// mEventPromoImage = eventPromoImage;
mId = id;
mEventTitle = eventTitle;
mEventStartDate = eventStartDate;
mEventEndDate = eventEndDate;
mEventLocation = eventLocation;
mEventFee = eventFee;
mEventViews = eventViews;
Log.d("tag","EVENTITEM title EventItem" + mEventTitle);
// Log.d("tag","EVENTITEM startDate EventItem" + mEventStartDate );
// Log.d("tag","EVENTITEM endDate EventItem" + mEventEndDate );
// Log.d("tag","EVENTITEM address EventItem" + mEventLocation);
// Log.d("tag","EVENTITEM fee EventItem" + mEventFee);
}
public int getEventPromoImage() {
return mEventPromoImage;
}
public void setEventPromoImage(int mEventPromoImage) {
this.mEventPromoImage = mEventPromoImage;
}
public int getEventId() {
return mId;
}
public void setEventId(int mId){
this.mId = mId;
}
public String getEventTitle() {
Log.d("tag","getEventTitle() " + mEventTitle);
return mEventTitle;
}
public void setEventTitle(String mEventTitle) {
this.mEventTitle = mEventTitle;
}
public String getEventStartDate() {
return mEventStartDate;
}
public void setEventStartDate(String mEventStartDate) {
this.mEventStartDate = mEventStartDate;
}
public String getEventEndDate(){
return mEventEndDate;
}
public void setEventEndDate(String mEventEndDate){
this.mEventEndDate = mEventEndDate;
}
public String getEventLocation() {
return mEventLocation;
}
public void setEventLocation(String mEventLocation) {
this.mEventLocation = mEventLocation;
}
public int getEventFee() {
return mEventFee;
}
public void setEventFee(int mEventFee) {
this.mEventFee = mEventFee;
}
public int getEventViews(){
return mEventViews;
}
public void getEventViews(int mEventViews) {
this.mEventViews = mEventViews;
}
public ArrayList<EventItem> getRecyclerList(){
ArrayList event = new ArrayList();
event.add(mEventTitle);
event.add(mEventStartDate);
event.add(mEventEndDate);
event.add(mEventLocation);
event.add(mEventFee);
event.add(mEventViews);
return event;
}
}
EventBackgroundWorker
public class EventBackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alert;
public static final String REQUEST_URL = "http://10.0.2.2/m/event/";
public EventBackgroundWorker(Context ctxt) {
context = ctxt;
}
//Invoked on UI thread before doInBackground is called
#Override
protected void onPreExecute() {
alert = new AlertDialog.Builder(context).create();
alert.setTitle("Result from server");
}
#Override
protected String doInBackground(String... params) {
String type = params[0];//eventList
//String login_url = "http://10.0.2.2/m/event/";
if(type.equals("event")){
try {
String user_name = params[1];
URL url = new URL(REQUEST_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.connect();//works without this connect Find out why
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("getEvents", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//read response
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while((line = bufferedReader.readLine()) != null){
result += line;
}
//parse JSON event Array
// Create an empty ArrayList that we can start adding events to
ArrayList<EventItem> eventArray = new ArrayList<>();
JSONArray baseJsonResponse = new JSONArray(result);
for(int i =0; i < baseJsonResponse.length(); i++){
JSONObject event = baseJsonResponse.getJSONObject(i);
int id = event.getInt("id");
String title = event.getString("title");
String address = event.getString("address");
String startDate = event.getString("startDate");
String endDate = event.getString("endDate");
int fee = event.getInt("fee");
int views = event.getInt("views");
//Send data to eventItem Object
EventItem eventObject = new EventItem(id,title,address,startDate,endDate,fee,views);
eventArray.add(eventObject);
/* Log.d("tag", "JSON id " + id);
Log.d("tag", "JSON title " + title);
Log.d("tag", "JSON address " + address);
Log.d("tag", "JSON startDate " + startDate);
Log.d("tag", "JSON endDate " + endDate);
Log.d("tag", "JSON fee " + fee);
Log.d("tag", "JSON views " + views);*/
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {//added for URL object
e.printStackTrace();
} catch (IOException e) {
//HTPURLConnection
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
//results from doInBackground are passed here
#Override
protected void onPostExecute(String result) {
Log.d("tag", "onPostExecute called" + result);
alert.setMessage(result);
alert.show();
}
}
The AsyncTask creates eventArray but does nothing with it. doInBackground() should return the eventArray and onPostExecute() should set it as adapter content (by a Callback or by setting the Adapter instance at the AsyncTask object). Your Adapter should have a setter for the content which should call notifyDataSetChanged().
So i have a AsyncTask that pulls data from a Mysql database and displays it, currently this works fine but i need to change the simple adapter to a custom adapter so i can do more with what is displayed. But i'm not sure what i need to change in order to get my custom adapter to work with my AsyncTask.
public class SearchFor extends AppCompatActivity implements View.OnClickListener {
DBManager db;
ListView lv;
myAdapter myAdapter;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> attractionList;
ArrayList<HashMap<String, String>> transportList;
// url to get all attraction list
private static String url_all_attractions = "http://10.0.2.2/TravelApp/get_all_attractions.php";
private static String url_all_transport = "http://10.0.2.2/TravelApp/get_all_transport.php";
// JSON Node names for attraction
private static final String TAG_SUCCESS = "success";
private static final String TAG_ATTRACTION = "attraction";
private static final String TAG_ATTRACTIONID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_TYPE = "Type";
private static final String TAG_LOCATION = "Location";
private static final String TAG_OPENING = "OpeningTime";
private static final String TAG_CLOSING = "ClosingTime";
private static final String TAG_NEARBYSTOP = "NearbyStop";
private static final String TAG_LATITUDE = "Latitude";
private static final String TAG_LONGITUDE = "Longitude";
//JSON Node names for transport
private static final String TAG_TRANSPORT = "transport";
private static final String TAG_TRANSPORTID = "Id";
private static final String TAG_TIME = "Time";
private static final String TAG_NEXTSTOP = "NextStop";
private static final String TAG_PHONENUMBER = "PhoneNumber";
// attraction JSONArray
JSONArray attraction = null;
JSONArray transport = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_for);
db = new DBManager(this);
// Hashmap for ListView
attractionList = new ArrayList<HashMap<String, String>>();
transportList = new ArrayList<HashMap<String, String>>();
lv = (ListView) findViewById(R.id.list_search);
this.registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId()== R.id.list_search ){
this.getMenuInflater().inflate(R.menu.context_menu_more,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menuBookmark:
testAdd();
break;
case R.id.menuDirections:
break;
default:
return super.onContextItemSelected(item);
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, menu);
getMenuInflater().inflate(R.menu.optionsmenu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.go_home){
Intent i = new Intent(getApplicationContext(),QavelNav.class);
startActivity(i);
}
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
if(id == R.id.attractionSub1){
new LoadAllAttractions().execute();
}else if(id == R.id.attractionSub2){
Toast.makeText(getApplicationContext(),"Pubs", Toast.LENGTH_LONG).show();
}else if(id == R.id.attractionSub3){
}else if(id == R.id.attractionSub4){
}else if(id == R.id.transportSub1){
new LoadAllTransport().execute();
}else if(id == R.id.transportSub2){
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
System.out.println(position);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllAttractions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchFor.this);
pDialog.setMessage("Loading attractions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All attraction from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_attractions, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Attractions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// attraction found
// Getting Array of Products
attraction = json.getJSONArray(TAG_ATTRACTION);
// looping through All Products
for (int i = 0; i < attraction.length(); i++) {
JSONObject c = attraction.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ATTRACTIONID);
String name = c.getString(TAG_NAME);
String type = c.getString(TAG_TYPE);
String location = c.getString(TAG_LOCATION);
String opening = c.getString(TAG_OPENING);
String closing = c.getString(TAG_CLOSING);
String nearbyStop1 = c.getString(TAG_NEARBYSTOP);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ATTRACTIONID, id);
map.put(TAG_NAME, name);
map.put(TAG_TYPE, type);
map.put(TAG_LOCATION, location);
map.put(TAG_OPENING,opening);
map.put(TAG_CLOSING,closing);
map.put(TAG_NEARBYSTOP, nearbyStop1);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
attractionList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
final ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
// dismiss the dialog after getting all attraction
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchFor.this, attractionList,
R.layout.list_attractions, new String[]{TAG_ATTRACTIONID,
TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_OPENING,TAG_CLOSING,TAG_NEARBYSTOP,TAG_LATITUDE,TAG_LONGITUDE},
new int[]{R.id.Attractionid, R.id.tvAttractionName, R.id.tvAttractionType, R.id.tvAttractionLocation,R.id.tvAttractionOpening,R.id.tvAttractionClosing,R.id.tvAttractionNearbyStop1});
// updating listview
//myAdapter = new myAdapter(listData);
lv.setAdapter(adapter);
}
});
}
}
class LoadAllTransport extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchFor.this);
pDialog.setMessage("Loading Transport. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All attraction from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_transport, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Transport: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// attraction found
// Getting Array of Products
transport = json.getJSONArray(TAG_TRANSPORT);
// looping through All Products
for (int i = 0; i < transport.length(); i++) {
JSONObject c = transport.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_TRANSPORTID);
String name = c.getString(TAG_NAME);
String type = c.getString(TAG_TYPE);
String location = c.getString(TAG_LOCATION);
String time = c.getString(TAG_TIME);
String nextStop = c.getString(TAG_NEXTSTOP);
String phoneNumber = c.getString(TAG_PHONENUMBER);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TRANSPORTID, id);
map.put(TAG_NAME, name);
map.put(TAG_TYPE, type);
map.put(TAG_LOCATION, location);
map.put(TAG_TIME,time);
map.put(TAG_NEXTSTOP,nextStop);
map.put(TAG_PHONENUMBER, phoneNumber);
// adding HashList to ArrayList
transportList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all attraction
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchFor.this, transportList,
R.layout.list_transport, new String[]{TAG_TRANSPORTID,
TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_TIME,TAG_NEXTSTOP,TAG_PHONENUMBER},
new int[]{R.id.transportid, R.id.tvTransportName, R.id.tvTransportType, R.id.tvTransportLocation,R.id.tvTransportPhone});
// updating listview
lv.setAdapter(adapter);
}
});
}
}
public void testAdd(){
TextView TextName = (TextView)findViewById(R.id.tvAttractionName);
System.out.println(TextName.getText().toString());
}
public void addAttraction(View v){
TextView TextName = (TextView)findViewById(R.id.tvAttractionName);
System.out.println(TextName.getText().toString());
TextView TextType = (TextView) findViewById(R.id.tvAttractionType);
TextView TextLocation = (TextView)findViewById(R.id.tvAttractionLocation);
TextView TextOpening = (TextView)findViewById(R.id.tvAttractionOpening);
TextView TextClosing = (TextView)findViewById(R.id.tvAttractionClosing);
TextView TextNearbyStop = (TextView)findViewById(R.id.tvAttractionNearbyStop1);
ContentValues values = new ContentValues();
values.put(DBManager.ColName,TextName.getText().toString());
values.put(DBManager.ColType,TextType.getText().toString());
values.put(DBManager.ColLocation,TextLocation.getText().toString());
values.put(DBManager.ColOpening,TextOpening.getText().toString());
values.put(DBManager.ColClosing,TextClosing.getText().toString());
values.put(DBManager.ColNearbyStop,TextNearbyStop.getText().toString());
long id = db.Insert("BookmarkAttraction",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
public void addTransport(View v){
TextView TextName = (TextView)findViewById(R.id.tvTransportName);
TextView TextType = (TextView) findViewById(R.id.tvTransportType);
TextView TextLocation = (TextView)findViewById(R.id.tvTransportLocation);
TextView TextPhoneNumber = (TextView)findViewById(R.id.tvTransportPhone);
ContentValues values = new ContentValues();
values.put(DBManager.ColName,TextName.getText().toString());
values.put(DBManager.ColType,TextType.getText().toString());
values.put(DBManager.ColLocation,TextLocation.getText().toString());
values.put(DBManager.ColPhoneNumber,TextPhoneNumber.getText().toString());
long id = db.Insert("BookmarkTransport",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_attractions, null);
final Adapter ac = listItem.get(position);
TextView attractionId = (TextView) myView.findViewById(R.id.Attractionid);
attractionId.setText(ac.ID);
TextView Name = (TextView) myView.findViewById(R.id.tvAttractionName);
Name.setText(ac.Name);
TextView Type = (TextView) myView.findViewById(R.id.tvAttractionType);
Type.setText(ac.Type);
TextView Location = (TextView) myView.findViewById(R.id.tvAttractionLocation);
Location.setText(ac.Location);
TextView Opening = (TextView) myView.findViewById(R.id.tvAttractionOpening);
Opening.setText(ac.Opening);
TextView Closing = (TextView) myView.findViewById(R.id.tvAttractionClosing);
Closing.setText(ac.Closing);
TextView NearbyStop1 = (TextView) myView.findViewById(R.id.tvAttractionNearbyStop1);
NearbyStop1.setText(ac.NearbyStop);
return myView;
}
}
}
The parts of interest are the custom adapter (myAdapter) located at the bottom and the first AsyncTask is what im trying to convert to a custom adapter. The onPostExecute is where the the simple adapter is and probably where i need to reference the custom adapter but need help with this
Seems you're using a single adapter for both of your needs.
Did you think about creating a two Custom Adapter classes for your two AsyncTasks.
Also few suggestions:
1. You can use Loader Callbacks and Cursor loader If you're using AsyncTask for DB fetching.
2. preExecute and postExecute already run on UI thread. So no need of runOnUIThread call there.
3. Use ViewHolder pattern in the Adapters getView method for better optimization.
I have got 3 spinner where data is coming from server, if we click the search button without selecting any spinner then on next activity , it should show all list(all product without condition), but if we select according to 3 spinner then it should show only related item.I am getting all item when clicking search button without selecting anything but i am not getting selected item in next activity .
here is my Search Activity:
public class PMSearchActivity extends AppCompatActivity {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private ImageButton mtoolbar,pmplus;
private Button mpigeonSearchbtn;
private Spinner pmcountry;
private Spinner pmstrain;
private Spinner pmdistance;
private TextView error_text;
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmsearch);
getSupportActionBar().hide();
pmplus = (ImageButton) findViewById(R.id.plus);
pmplus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMSearchActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
finish();
}
}) ;
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMSearchActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
mpigeonSearchbtn = (Button) findViewById(R.id.pmaddcompanybtn);
mpigeonSearchbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
pmcountry = (Spinner) findViewById(R.id.sname);
pmstrain = (Spinner) findViewById(R.id.fbcountry);
pmdistance = (Spinner) findViewById(R.id.pstrain);
error_text = (TextView) findViewById(R.id.error_text);
adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems);
pmstrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems2);
pmdistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems3);
pmcountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void attemptLogin() {
// Reset errors.
// mEmailView.setError(null);
//mPasswordView.setError(null);
// Store values at the time of the login attempt.
String PMcountry = pmcountry.getSelectedItem().toString();
String PMstrains = pmstrain.getSelectedItem().toString();
String PMdistance = pmdistance.getSelectedItem().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
}
Intent intent = new Intent(PMSearchActivity.this, PMPigeonListingActivity.class);
intent.putExtra("Country_name", PMcountry);
intent.putExtra("Strain_name", PMstrains);
intent.putExtra("Distance_name", PMdistance);
startActivity(intent);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListStrainTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Strain-");
// Json coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListDistanceTask() {
}
// Json coding
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Country-");
// Json coding
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
here in PiegonListing activity:
public class PMPigeonListingActivity extends AppCompatActivity {
private Button mpigeonListBtn;
private ImageView mimg3;
private ImageButton mtoolbar;
private String PostCountry;
private String PostStrain;
private String PostDistance;
private Button listpigeonbutton;
private Spinner lsDistance;
private Spinner lsStrain;
private Spinner lsCountry;
private Button lssearchbutton;
private TextView listallbtn;
//Web api url
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
//Tag values to read from json
public static final String TAG_IMAGE_URL = "pimage";
public static final String TAG_NAME = "pprice";
public static final String TAG_PID = "pid";
public static final String TAG_PNAME = "pname";
public static final String TAG_PDETAILS = "pdetails";
public static final String TAG_MOBILE = "pmobile";
public static final String TAG_EMAIL = "pemail";
//GridView Object
private GridView gridView;
private GridView gridView2;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private ArrayList<String> names;
private ArrayList<Integer> pid;
private ArrayList<String> pname;
private ArrayList<String> pdetails;
private ArrayList<String> pimage;
private ArrayList<String> pmobile;
private ArrayList<String> pemail;
//for inline search
private ArrayList<String> images2;
private ArrayList<String> names2;
private ArrayList<Integer> pid2;
private ArrayList<String> pname2;
private ArrayList<String> pdetails2;
private ArrayList<String> pimage2;
private ArrayList<String> pmobile2;
private ArrayList<String> pemail2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmpigeon_listing);
getSupportActionBar().hide();
gridView = (GridView) findViewById(R.id.gridView);
gridView2 = (GridView) findViewById(R.id.gridView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
PostCountry = extras.getString("Country_name");
PostStrain = extras.getString("Strain_name");
PostDistance = extras.getString("Distance_name");
}
images = new ArrayList<>();
names = new ArrayList<>();
pid = new ArrayList<>();
pname = new ArrayList<>();
pdetails = new ArrayList<>();
pmobile = new ArrayList<>();
pemail = new ArrayList<>();
images2 = new ArrayList<>();
names2 = new ArrayList<>();
pid2 = new ArrayList<>();
pname2 = new ArrayList<>();
pdetails2 = new ArrayList<>();
pmobile2 = new ArrayList<>();
pemail2 = new ArrayList<>();
lsStrain = (Spinner) findViewById(R.id.lsStrain);
lsDistance = (Spinner) findViewById(R.id.lsDistance);
lsCountry = (Spinner) findViewById(R.id.lsCountry);
lssearchbutton = (Button) findViewById(R.id.lssearchbutton);
listallbtn = (TextView) findViewById(R.id.listallbtn);
if (PostCountry.equals("Select Country") && PostStrain.equals("Select Strain") && PostDistance.equals("Select Distance")) {
listallbtn.setVisibility(View.GONE);
} else {
listallbtn.setVisibility(View.VISIBLE);
}
//Calling the getData method
getData();
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
lssearchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
listallbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
lsCountry.setSelection(0);
lsStrain.setSelection(0);
lsDistance.setSelection(0);
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
// button list
listpigeonbutton = (Button) findViewById(R.id.listpigeonbutton);
listpigeonbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
}
});
adapter = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems);
lsStrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems2);
lsDistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems3);
lsCountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......searchPigeonList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("image"));
names.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
Log.d("Test",response);
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
gridView.setAdapter(pmpigeonlistadapter);
pmpigeonlistadapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void filter() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......hPigeonList";
final String lstrain = lsStrain.getSelectedItem().toString();
final String ldistance = lsDistance.getSelectedItem().toString();
final String lcountry = lsCountry.getSelectedItem().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid2.add(obj.getInt("id"));
pname2.add(obj.getString("pigeon_name"));
pdetails2.add(obj.getString("pigeon_details"));
pmobile2.add(obj.getString("usr_mobile"));
pemail2.add(obj.getString("usr_email"));
images2.add(obj.getString("image"));
names2.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonSearchInlineAdapter pmPigeonSearchInlineAdapter = new PMPigeonSearchInlineAdapter(getApplicationContext(), images2, names2, pid2, pdetails2, pmobile2, pemail2, pname2);
//Adding adapter to gridview
pmPigeonSearchInlineAdapter.notifyDataSetChanged();
gridView2.setAdapter(pmPigeonSearchInlineAdapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params2 = new HashMap<String, String>();
params2.put("country", lcountry);
params2.put("strain", lstrain);
params2.put("distance", ldistance);
return params2;
}
};
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
gridView2.setAdapter(null);
requestQueue2.add(stringRequest);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
// some coding
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
// some coding
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsDistance.getAdapter();
lsDistance.setSelection(array_spinner.getPosition(PostDistance));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("Select Country");
// some coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMPigeonListingActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsCountry.getAdapter();
lsCountry.setSelection(array_spinner.getPosition(PostCountry));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
In Pigeon listing activity there is 1 option like search activity where user can search without selecting any item just like in search activity.
Set listeners for each of your spinners
setOnItemSelectedListener
In onItemSelected method , get the selected value in a variable and pass on these values to next activity.
E.g.
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String yourValue = yourSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I have my class that is based on a tutorial online, i dont fully understand it yet ( working on it ), but its working.
It populates the listview, now i want to get the id and show the data related to that id on a more detailed activity.
I already obtain the id of the item i am clicking:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
But now, i am not getting how i will do this, get the data of the position i clicked.
I have a inner class "GetObras" but i cant use the variables from it on my onCreate, i tried make them global, etc
public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView list;
private static String url = "http://ploran.gear.host/scriptobras6.php";
ArrayList<HashMap<String, String>> obrasList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obrasList = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.list1);
new GetObras().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
}
private class GetObras extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray obras = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray obras = jsonObj.getJSONArray("obras");
// looping through All
for (int i = 0; i < obras.length(); i++) {
JSONObject c = obras.getJSONObject(i);
String id = c.getString("Id");
String nomeObra = c.getString("NomeObra");
String idCliente = c.getString("idCliente");
String DataLevantamento = c.getString("DataPLevantamento");
String DataRealizacao = c.getString("DataRLevantamento");
String Estado = c.getString("Estado");
String DataMateriais = c.getString("DataRMateriais");
String DataInicioObra = c.getString("DataInicioObra");
String DataConclusao = c.getString("DataConclusao");
String DataVestoria = c.getString("DataVestoria");
String Obs = c.getString("Obs");
String Prompor = c.getString("Prompor");
String Levantpor = c.getString("Levantpor");
String executpor = c.getString("executpor");
// tmp hash map for single contact
HashMap<String, String> obra = new HashMap<>();
// adding each child node to HashMap key => value
obra.put("Id", id);
obra.put("nomeObra", nomeObra);
obra.put("idCliente", idCliente);
obra.put("DataLevantamento", DataLevantamento);
obra.put("DataRealizacao", DataRealizacao);
obra.put("Estado", Estado);
obra.put("DataMateriais", DataMateriais);
obra.put("DataIncioObra", DataInicioObra);
obra.put("DataConclusao", DataConclusao);
obra.put("DataVestoria", DataVestoria);
obra.put("Obs", Obs);
obra.put("Prompor", Prompor);
obra.put("Levantpor", Levantpor);
obra.put("executpor", executpor);
// adding contact to contact list
obrasList.add(obra);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, obrasList,
R.layout.list_item, new String[]{"nomeObra", "idCliente",
"Estado"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
list.setAdapter(adapter);
}
}
List<String> cities;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// User pressed the search button
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// User changed the text
return false;
}
}
If what i think is correct, i could just get the JsonArray from the doInBackground method in GetObras and do:
JSONObject c = obras.getJSONObject(position);
Thank you.
You can retrieve it using obrasList reference. As your are passing obrasList to your adapter.
Below is the sample code:
obrasList.get(position).get(yourkey);
Hope this will help you.. :))
I have arrayList> in my app.I have this array fro, the Internet,through parsing json data. I want to save this array,then my app can be work without Internet.What can I do? I know how to stored data im SQLite,but response of query is cursor,I know that I can create custom adapter that working with cursor.But maybe I can find easier way for this?
MainActivity:
public class MainActivity extends ListActivity {
private Context context;
SqlHelper dbHelper;
Intent intent;
private static String url = "https://fierce-citadel-4259.herokuapp.com/hamsters";
private static final String TITLE = "title";
private static final String DESCRIPTION = "description";
private static final String IMAGE = "image";
ArrayList<HashMap<String,String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
lv=(ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title1 = jsonlist.get(position).get("title");
String description1 = jsonlist.get(position).get("description");
String url1 = jsonlist.get(position).get("image");
intent = new Intent(MainActivity.this, DetailInfo.class);
intent.putExtra("title", title1);
intent.putExtra("description", description1);
intent.putExtra("url", url1);
startActivity(intent);
dbHelper = new SqlHelper(MainActivity.this);
try {
dbHelper.open();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.reload) {
new ProgressTask(MainActivity.this).execute();
}
else if(id == R.id.menu_item_share){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Put whatever you want");
startActivity(Intent.createChooser(intent,"Share via"));
}
return super.onOptionsItemSelected(item);
}
private class ProgressTask extends AsyncTask<String,Void,Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
private Context context;
public ProgressTask(MainActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute(){
this.dialog.setMessage("Progress start");
this.dialog.show();
}
protected void onPostExecute(final Boolean success){
try{
if((this.dialog != null)&& this.dialog.isShowing()){
this.dialog.dismiss();
}
CustomListAdapter adapter = new CustomListAdapter(MainActivity.this,jsonlist, R.layout.list_item,new String[]{TITLE,DESCRIPTION},new int[]{R.id.title,R.id.description});
lv.setAdapter(adapter);
//setListAdapter(adapter);
}catch (final IllegalArgumentException e){e.printStackTrace();}
}
protected Boolean doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for(int i =0;i<json.length();i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtitle = c.getString(TITLE);
String vdescription = c.getString(DESCRIPTION);
String vimage = c.getString(IMAGE);
/* dbHelper.createEntry(vtitle,vdescription,vimage);
dbHelper.close();*/
HashMap<String, String> map = new HashMap<>();
map.put(TITLE, vtitle);
map.put(DESCRIPTION, vdescription);
map.put(IMAGE, vimage);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
/*private void displaysavedlv(){
Cursor cursor = dbHelper.fetchAllCountries();
CustomCursorAdapter adapter1 = new CustomCursorAdapter(MainActivity.this,cursor);
lv.setAdapter(adapter1);
}*/
/* private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}*/
}
yes you can do this without sqlite. TinyDB will do the trick for you.
checkout here : https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo
You can create one method in sqlite that returns arrayList with hashmap :
public ArrayList<HashMap<String, String>> getAllData()
{
ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from tablename", null );
res.moveToFirst();
while(res.isAfterLast() == false){
hashmap = new HashMap<String, String>();
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
array_list.add(hashmap);
res.moveToNext();
}
return array_list;
}
Cheers!