list of brands not displaying in a spinner - android

Hi in the below code I am displaying two spinner one is for displaying brand name and another for displaying model name.
I am getting the response from server like this:
{"RESULT":"SUCCESS","BRANDS":[{"BRANDID":"14","BRANDNAME":"471"},{"BRANDID":"3","BRANDNAME":"ACE"},{"BRANDID":"4","BRANDNAME":"ADLER"},{"BRANDID":"5","BRANDNAME":"ALIEN"},{"BRANDID":"6","BRANDNAME":"ARTISAN-TORO"},{"BRANDID":"7","BRANDNAME":"ASSOCIATED PACIFIC"},{"BRANDID":"8","BRANDNAME":"ASTEX"},{"BRANDID":"9","BRANDNAME":"BERNINA"},{"BRANDID":"10","BRANDNAME":"BONIS"},{"BRANDID":"11","BRANDNAME":"BROTHER"},{"BRANDID":"12","BRANDNAME":"BROTHER "},{"BRANDID":"13","BRANDNAME":"CHANDLER"},{"BRANDID":"15","BRANDNAME":"CINCINNATI"},{"BRANDID":"16","BRANDNAME":"CONSEW"},{"BRANDID":"17","BRANDNAME":"CONSEW\/SEIKO"},{"BRANDID":"18","BRANDNAME":"DENNISON"},{"BRANDID":"19","BRANDNAME":"DURKOPP ADLER"},{"BRANDID":"20","BRANDNAME":"EAGLE"},{"BRANDID":"21","BRANDNAME":"EASTMAN"},{"BRANDID":"22","BRANDNAME":"EASTMAN CARDINAL"},{"BRANDID":"23","BRANDNAME":"ECONOSEW"},{"BRANDID":"1","BRANDNAME":"usha"}]}
Model Response:
{"RESULT":"SUCCESS","MODELS":[{"MODELNAME":"150","MODELID":"2"},{"MODELNAME":"C150WS","MODELID":"3"},{"MODELNAME":"HC720A","MODELID":"4"}
Based on the brand i want to display model names.
java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url","" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.d("Brand_result","" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
spinner_fn();
Log.i("listbrands", " " + listBrands);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}
//ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext()
// ,android.R.layout.simple_spinner_item,listBrands_String);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}

Related

I used PagerAdapter for sliding images its not notifying properly

I used PagerAdapter for sliding images and i added a favorite button too in that sliding image. After clicking favorite button its not getting notified properly image not turns to unfavorite icon.
it is for loading api
private class PremiumProjectLoad extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url= ApiLinks.PremiumProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(getActivity(),null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("cityID",CommonStrings.cityID);
if(session.isLoggedIn()){
params.put("userID",UserLogin.get(SessionManager.KEY_CUSTOMER_ID));
}
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String Status=json.optString("status");
String Message=json.optString("message");
CommonImagePath=json.optString("imagepath");
PremiumDataArray.clear();
if(Status.equals("ok")){
JSONArray DataArray=json.optJSONArray("data");
if(DataArray!=null && DataArray.length()>0) {
for (int i = 0; i < DataArray.length(); i++) {
JSONObject DataObj = DataArray.optJSONObject(i);
String projectID = DataObj.optString("projectID");
String projectName = DataObj.optString("projectName");
String propertyUnitPriceRange = DataObj.optString("propertyUnitPriceRange");
String projectOfMonthImage = DataObj.optString("projectOfMonthImage");
String propertyUnitBedRooms = DataObj.optString("propertyUnitBedRooms");
String projectBuilderName = DataObj.optString("projectBuilderName");
String propertyTypeName = DataObj.optString("propertyTypeName");
String purpose = DataObj.optString("purpose");
String projectBuilderAddress = DataObj.optString("projectBuilderAddress");
String projectFavourite = DataObj.optString("projectFavourite");
PremiumData premiumData = new PremiumData();
premiumData.setProjectID(projectID);
premiumData.setProjectName(projectName);
premiumData.setPropertyUnitPriceRange(propertyUnitPriceRange);
premiumData.setProjectOfMonthImage(projectOfMonthImage);
premiumData.setPropertyUnitBedRooms(propertyUnitBedRooms);
premiumData.setProjectBuilderName(projectBuilderName);
premiumData.setPropertyTypeName(propertyTypeName);
premiumData.setPurpose(purpose);
premiumData.setProjectBuilderAddress(projectBuilderAddress);
premiumData.setProjectFavourite(projectFavourite);
PremiumDataArray.add(premiumData);
}
LoopViewPager viewpager = (LoopViewPager) homeView.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) homeView.findViewById(R.id.indicator);
// if(pagerAdapter==null)
pagerAdapter = new PremiumProjectAdapter(getActivity(), PremiumDataArray);
viewpager.setAdapter(pagerAdapter);
indicator.setViewPager(viewpager);
// pagerAdapter.notifyDataSetChanged();
}
}
else {
Toast.makeText(getActivity(),Message, Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
pager adapter
public class PremiumProjectAdapter extends PagerAdapter {
private final Random random = new Random();
private ArrayList<PremiumData> mSize;
Context mContext;
LayoutInflater mLayoutInflater;
String ProjectID;
String path=CommonImagePath+"/uploads/projectOfMonth/orginal/";
// public PremiumProjectAdapter() {
// }
public PremiumProjectAdapter(Context contexts, ArrayList<PremiumData> count) {
mSize = count;
mContext=contexts;
}
#Override public int getCount() {
return mSize.size();
}
#Override public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override public void destroyItem(ViewGroup view, int position, Object object) {
view.removeView((View) object);
}
#Override public Object instantiateItem(ViewGroup view, final int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.home_premium_layout, view, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.premium_ProImage);
TextView ProjectName = (TextView) itemView.findViewById(R.id.premium_ProName);
TextView ProjectUnitPrice = (TextView) itemView.findViewById(R.id.premium_UnitPrice);
TextView ProjectUnitBedroom = (TextView) itemView.findViewById(R.id.premium_UnitBedrooms);
TextView ProjectAddress = (TextView) itemView.findViewById(R.id.premium_ProAddress);
ImageView unshortlisted = (ImageView) itemView.findViewById(R.id.unshortlisted);
ImageView shortlisted = (ImageView) itemView.findViewById(R.id.shortlisted);
final PremiumData data = mSize.get(position);
if (data.getProjectFavourite() != null) {
if (data.getProjectFavourite().equals("ShortListed")) {
shortlisted.setVisibility(View.VISIBLE);
unshortlisted.setVisibility(View.GONE);
} else {
shortlisted.setVisibility(View.GONE);
unshortlisted.setVisibility(View.VISIBLE);
}
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange(), Html.FROM_HTML_MODE_COMPACT));
}else{
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange()));
}
ImageLoader.getInstance().displayImage(path+data.getProjectOfMonthImage(), imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(!data.getProjectName().equals("null") && data.getProjectName().length()>30){
String s = data.getProjectName().substring(0, 25);
String subString = s + "...";
ProjectName.setText(subString);
}
else{
ProjectName.setText(data.getProjectName());
}
ProjectUnitBedroom.setText(data.getPropertyUnitBedRooms());
ProjectAddress.setText(data.getProjectBuilderAddress());
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent DetailsAction=new Intent(mContext, DetailsActivity.class);
DetailsAction.putExtra("projectID",data.getProjectID());
DetailsAction.putExtra("purpose",data.getPurpose());
mContext.startActivity(DetailsAction);
}
});
unshortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!session.isLoggedIn()){
Intent toLogin=new Intent(mContext, LoginActivity.class);
CommonStrings.FromSearchIndex="true";
mContext.startActivity(toLogin);
}else{
ProjectID=data.getProjectID();
new ShortlistProject().execute();
}
}
});
shortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProjectID=data.getProjectID();
new UnShortlistProject().execute();
}
});
view.addView(itemView);
return itemView;
}
private class ShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.AddShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
//SearchFragment.getInstance().onResume();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
private class UnShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.RemoveShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
// HomeFragment.getInstance().async_Premium();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
As far as i am able to understand your question you want favorite and unfavorite functionality by adapter . Please use this code below to achieve that :
public class CustomGridAdapterFoodDrink extends BaseAdapter {
private Context mContext;
private ProgressDialog loading;
ArrayList<FoodDrink> foodDrinkArrayList = new ArrayList<>();
SharedPreferences pref;
String userId;
String like_dislike_value = "Like";
String likeValueStr = "1";
boolean like = true;
int positionVal = 444;
HashMap<Integer,Boolean> state = new HashMap<>();
public CustomGridAdapterFoodDrink(Context c, ArrayList<FoodDrink> foodDrinkArrayList) {
mContext = c;
this.foodDrinkArrayList = foodDrinkArrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return foodDrinkArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView projectNamtTxtView = (TextView) grid.findViewById(R.id.projectName);
TextView totalOfferText = (TextView) grid.findViewById(R.id.TotalOffers);
ImageView merchantImage = (ImageView) grid.findViewById(R.id.merchantImage);
final ImageView like_dislike_icon = (ImageView) grid.findViewById(R.id.like_dislike_icon);
totalOfferText.setText(foodDrinkArrayList.get(position).getOffers());
projectNamtTxtView.setText(foodDrinkArrayList.get(position).getProject_name());
Glide.with(mContext)
.load(foodDrinkArrayList.get(position).getProject_photo())
.centerCrop()
.placeholder(R.drawable.review_pro_pic1)
.crossFade()
.into(merchantImage);
like_dislike_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", null);
/* if(state.size()> 0){
like = state.get(position);*/
if (!like) {
like = true;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
} else {
like = false;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it);
likeDislike2(foodDrinkArrayList.get(position).getID(), "0");
}
/* } else {
like = true;
state.put(position,like);
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
}*/
// if(positionVal !=position) {
// likeValueStr ="1";
// positionVal = position;
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
// else {
// likeValueStr ="0";
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
}
});
} else {
grid = (View) convertView;
}
return grid;
}
private void likeDislike(String merchantId, final String like_dislike, final ImageView imageView) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
if (msg.equalsIgnoreCase("Like")) {
imageView.setImageResource(R.mipmap.like_it_act);
} else {
imageView.setImageResource(R.mipmap.like_it);
}
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
private String getlikeUrl(String userId, String merchantId, String like_dislike) {
String url = "";
try {
url = NetworkURL.URL
+ "likeMerchant"
+ "?user_id=" + URLEncoder.encode(new Global().checkNull(userId), "UTF-8")
+ "&merchant_id=" + URLEncoder.encode(new Global().checkNull(merchantId), "UTF-8")
+ "&like_dislike=" + URLEncoder.encode(new Global().checkNull(like_dislike), "UTF-8")
;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
return url;
}
private void likeDislike2(String merchantId, final String like_dislike) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
}

I have using 3 tab first one and last tab is refresh data then when i click the center tab cannot able to refresh what i do.?

I have using 3 tab(Request,Reached,Left) first tab and last tab is refreshed when i click the tab but the center tab cannot able to refresh how to do help me.
My code:
VisitorListItems.java
public class VisitorListItems {
String visitorname,mobileno,whomtomeet,date,time;
int Reg_id;
Bitmap visitorimg;
public VisitorListItems(String visitorname,String mobileno,String whomtomeet,Bitmap visitorimg,String date,String time,int Reg_id){
this.visitorname=visitorname;
this.mobileno=mobileno;
this.whomtomeet=whomtomeet;
this.visitorimg=visitorimg;
this.date=date;
this.time=time;
this.Reg_id=Reg_id;
}
public String getVisitorname(){
return visitorname;
}
public String getMobileno(){return mobileno; }
public String getWhomtomeet(){
return whomtomeet;
}
public String getDate() { return date; }
public String getTime(){return time;}
public Bitmap getVisitorimg(){
return visitorimg;
}
public int getReg_id(){return Reg_id;}
}
MyListviewAdapter.java
public class MyListviewAdapter extends ArrayAdapter<VisitorListItems> {
String RegIdno;
private Button btnallow;
private Button btndeny;
private ProgressDialog pbd;
private TextView txtWhomtomeet,txtdate,txttimein,txtregidno,txtmobil;
ArrayList<VisitorListItems> visitorlist=new ArrayList<>();
ConnectionClass connectionClass;
public MyListviewAdapter(Context context,int textViewResourceId, ArrayList<VisitorListItems> objects) {
super(context,textViewResourceId,objects);
visitorlist=objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertview, ViewGroup parent){
View v=convertview;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.registrationlisttemplate, null);
connectionClass=new ConnectionClass();
TextView txtvisitorname = (TextView) v.findViewById(R.id.txtvisitorname);
btnallow=(Button)v.findViewById(R.id.btnallow);
btndeny=(Button)v.findViewById(R.id.btndeny);
txtWhomtomeet = (TextView) v.findViewById(R.id.txtWhomtomeet);
txtdate=(TextView)v.findViewById(R.id.txtdate);
txttimein=(TextView)v.findViewById(R.id.txttimein);
txtregidno=(TextView)v.findViewById(R.id.txtregidno);
txtmobil = (TextView) v.findViewById(R.id.txtmobil);
ImageView imageView = (ImageView) v.findViewById(R.id.imgvisitor);
txtvisitorname.setText(visitorlist.get(position).getVisitorname());
txtWhomtomeet.setText(visitorlist.get(position).getWhomtomeet());
txtmobil.setText(visitorlist.get(position).getMobileno());
imageView.setImageBitmap(visitorlist.get(position).getVisitorimg());
txtdate.setText(visitorlist.get(position).getDate());
txttimein.setText(visitorlist.get(position).getTime());
txtregidno.setText(String.valueOf(visitorlist.get(position).getReg_id()));
txtregidno.setVisibility(View.INVISIBLE);
btnallow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegIdno=txtregidno.getText().toString();
Visitorallow visitorallow=new Visitorallow();
visitorallow.execute("");
}
});
btndeny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegIdno=txtregidno.getText().toString();
Visitordeny visitordeny=new Visitordeny();
visitordeny.execute("");
// Toast.makeText(getContext(),M,Toast.LENGTH_SHORT).show();
}
});
return v;
}
public class Visitorallow extends AsyncTask<String,String,String> {
String Z="";
Boolean isSuccess;
#Override
protected String doInBackground(String... params) {
try{
Connection con=connectionClass.CONN();
if(con==null){
Z="Error in Connection with SQL Server";
}
else {
String query="Update app_Registration set FlatOwner='"+1+"' where Id='"+RegIdno+"'";
PreparedStatement preparedStatement=con.prepareStatement(query);
preparedStatement.executeUpdate();
Z="Update Successfully";
isSuccess=true;
}
}catch (Exception ex){
isSuccess=false;
Z="Exception";
}
return Z;
}
#Override
protected void onPreExecute() {
// super.onPreExecute();
pbd=new ProgressDialog(getContext());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String s) {
// super.onPostExecute(s);
if(pbd.isShowing())
pbd.dismiss();
// btndeny.setVisibility(View.GONE);
Toast.makeText(getContext(),s,Toast.LENGTH_SHORT).show();
}
}
public class Visitordeny extends AsyncTask<String,String,String> {
String Z="";
Boolean isSuccess;
#Override
protected String doInBackground(String... params) {
try{
Connection con=connectionClass.CONN();
if(con==null){
Z="Error in Connection with SQL Server";
}
else {
String query="Update app_Registration set FlatOwner='"+0+"' where Id='"+RegIdno+"'";
PreparedStatement preparedStatement=con.prepareStatement(query);
preparedStatement.executeUpdate();
Z="Update Successfully";
isSuccess=true;
}
}catch (Exception ex){
isSuccess=false;
Z="Exception";
}
return Z;
}
#Override
protected void onPreExecute() {
// super.onPreExecute();
pbd=new ProgressDialog(getContext());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String s) {
// super.onPostExecute(s);
if(pbd.isShowing())
pbd.dismiss();
// btndeny.setVisibility(View.GONE);
Toast.makeText(getContext(),s,Toast.LENGTH_SHORT).show();
}
}
}
VisitorList.java(Fragment)
public class VisitorList extends Fragment {
// private ProgressDialog pbbar;
//private ProgressBar pbbar;
private ProgressDialog pbd;
private ListView lstview;
ConnectionClass connectionClass;
String Y = "";
String mobileno;
int RegIdNo;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mobileno=getActivity().getIntent().getStringExtra("user_name");
View rootView = inflater.inflate(R.layout.visitorlistslide, container, false);
lstview = (ListView) rootView.findViewById(R.id.lstview);
// txtregid=(TextView)rootView.findViewById(R.id.txtregid);
connectionClass = new ConnectionClass();
Fetch fetch = new Fetch();
fetch.execute("");
return rootView;
}
public class Fetch extends AsyncTask<String, String, String> {
String z = "";
ArrayList<VisitorListItems> visitorList=new ArrayList<>();
#Override
protected void onPreExecute() {
pbd=new ProgressDialog(getActivity());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String r) {
// pbbar.setVisibility(View.GONE);
if (pbd.isShowing())
pbd.dismiss();
// txtregid.setText(String.valueOf(Reg_Id));
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
MyListviewAdapter myAdapter=new MyListviewAdapter(getActivity(),R.layout.registrationlisttemplate,visitorList);
// myAdapter.notifyDataSetChanged();
lstview.setAdapter(myAdapter);
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from app_Registration where OwnerMobileNo='"+ mobileno+"' and FlatOwner is null and Security=1";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList data1 = new ArrayList();
while (rs.next()) {
//Reg_Id=rs.getInt("Id");
RegIdNo=rs.getInt("Id");
String r=rs.getString("VisitorImg");
//Convertong Images string to bitmap
byte[] decodeString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString,0, decodeString.length);
visitorList.add(new VisitorListItems("VisitorName : " + rs.getString("VisitorName"),"Whomtomeet : " + rs.getString("Whomtomeet"),"Mobile No. : " + rs.getString("MobileNo"),decodebitmap,"Visit Date :"+rs.getString("datein"),rs.getString("timein"),RegIdNo));
}
z = "Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
}
return z;
}
}
}
Update you VisitorList class and check
public class VisitorList extends Fragment {
// private ProgressDialog pbbar;
//private ProgressBar pbbar;
private ProgressDialog pbd;
private ListView lstview;
ConnectionClass connectionClass;
String Y = "";
String mobileno;
int RegIdNo;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mobileno=getActivity().getIntent().getStringExtra("user_name");
View rootView = inflater.inflate(R.layout.visitorlistslide, container, false);
lstview = (ListView) rootView.findViewById(R.id.lstview);
// txtregid=(TextView)rootView.findViewById(R.id.txtregid);
return rootView;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// write here the code of refresh the data
connectionClass = new ConnectionClass();
Fetch fetch = new Fetch();
fetch.execute("");
}
}
public class Fetch extends AsyncTask<String, String, String> {
String z = "";
ArrayList<VisitorListItems> visitorList=new ArrayList<>();
#Override
protected void onPreExecute() {
pbd=new ProgressDialog(getActivity());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String r) {
// pbbar.setVisibility(View.GONE);
if (pbd.isShowing())
pbd.dismiss();
// txtregid.setText(String.valueOf(Reg_Id));
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
MyListviewAdapter myAdapter=new MyListviewAdapter(getActivity(),R.layout.registrationlisttemplate,visitorList);
// myAdapter.notifyDataSetChanged();
lstview.setAdapter(myAdapter);
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from app_Registration where OwnerMobileNo='"+ mobileno+"' and FlatOwner is null and Security=1";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList data1 = new ArrayList();
while (rs.next()) {
//Reg_Id=rs.getInt("Id");
RegIdNo=rs.getInt("Id");
String r=rs.getString("VisitorImg");
//Convertong Images string to bitmap
byte[] decodeString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString,0, decodeString.length);
visitorList.add(new VisitorListItems("VisitorName : " + rs.getString("VisitorName"),"Whomtomeet : " + rs.getString("Whomtomeet"),"Mobile No. : " + rs.getString("MobileNo"),decodebitmap,"Visit Date :"+rs.getString("datein"),rs.getString("timein"),RegIdNo));
}
z = "Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
}
return z;
}
}
}

My questions is, how do I pass the list data i have obtained from JSON in a fragment to an activity?

This is my Fragment Class - Here i get the JSON array object and call the adapter class for setting it. In the corressponding XML file, i have used a card view and lsit view to display the data. i want to know how to implement a onItemClickListener{} function so that i can go to another activity and display the list in a more detailed manner.
{
String url = "http://www.appplay.in/student_project/public/staff_details";
ProgressDialog mProgressDialog;
ListView lvDetail;
Context context;
ArrayList<staff_model> myList = new ArrayList<>();
ListView lv;
public static ArrayList<staff_model> staff_array;
JSONObject jsonObject;
JSONObject jsonKey;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
context=container.getContext();
View v = inflater.inflate(R.layout.tab_fragment_2, container, false);
lvDetail = (ListView) v.findViewById(R.id.CustomList);
// submit=(Button)v.findViewById(R.id.button) ;
new GetGalleryimage().execute();
v.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent in = new Intent(getActivity(), Staff_Main.class);
startActivity(in);
}
});
return v;
}
public void positionAction(View view) {
int position = (int) view.getTag();
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
private class GetGalleryimage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonarr = jsonObj.getJSONArray("User_Details");
for(int i=0; i<jsonarr.length(); i++)
{
JSONObject jsonObject = jsonarr.getJSONObject(i);
myList.add(new staff_model(jsonObject.getString("name"),jsonObject.getString("dob"),jsonObject.getString("occupation"),jsonObject.getString("emailid"),jsonObject.getString("contact"),jsonObject.getString("timetable"),jsonObject.getString("image")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v("result",""+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
staff_BaseAdapter rcAdapter = new staff_BaseAdapter(getActivity(),0, myList);
lvDetail.setAdapter(rcAdapter);
}
}
public class MAP_Detailservice extends
AsyncTask<String, String, String> {
Context mContext;
JSONObject mJsnObj;
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
showProgress();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
JSONObject json = new JSONObject();
String cricketAllMatchesLink = "http://www.appplay.in/student_project/public/staff_details";
try {
return String.valueOf(HttpUtils.getJson(cricketAllMatchesLink));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.v("POST EXECUTE", "RESULT :" + result);
super.onPostExecute(result);
hideProgress();
// mProgressDialog.dismiss();
// if (HttpUtils.status == 408) {
// Toast.makeText(getActivity(), "Conection Lost ",
// Toast.LENGTH_SHORT).show();
// }
try {
JSONArray array = new JSONArray(result);
JSONObject mJsonObject = array.getJSONObject(0);
// ArrayList<user_agent> GetSearchResults();
ArrayList<staff_model> staff_result = new ArrayList<staff_model>();
/**
* Question Array Parsing
*/
JSONArray jsonQuesstionsArray = mJsonObject
.getJSONArray("User_Details");
for (int i = 0; i < jsonQuesstionsArray.length(); i++) {
// Reading questions
JSONObject jsonQuestionObject = jsonQuesstionsArray
.getJSONObject(i);
String name = jsonQuestionObject.getString("name");
String dob = jsonQuestionObject.getString("dob");
String occupation = jsonQuestionObject.getString("occupation");
String emailid = jsonQuestionObject.getString("emailid");
String contact = jsonQuestionObject.getString("contact");
String timetable = jsonQuestionObject.getString("timetable");
String image = jsonQuestionObject.getString("image");
}
lvDetail.setAdapter(new staff_BaseAdapter(
getActivity(), 0,staff_result));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void showProgress() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Loading please wait");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
public void hideProgress() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onDestroy(){
super.onDestroy();
if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
mProgressDialog.cancel();
}
}
}
This is my Adapter class - Where I have gotten the data and set the code
ArrayList<StaffList> myList = new ArrayList<StaffList>();
LayoutInflater inflater;
Context context;
public StaffBaseAdapter(Context context, ArrayList<StaffList> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public StaffList getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.staff_list_view, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
StaffList currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
}
}
}
This is my Model Class
String title;
int imgResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
first your model class "staff_model" implement parcelable it will help to transfer your single model item pass to other activity.
Then add ItemClickListener in your listview
add this into your getView function
MyViewHolder rowHolder=new MyViewHolder(convertView);
rowHolder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do whatever u want
}
});
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here you can convert your json to string
startActivity(new Intent(this, MainActivity.class).putExtra("myList",new Gson().toJson(list)));
}
});
and in your receiving activity
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> list1=new Gson().fromJson(getIntent().getStringExtra("myList"),type);
Here Specify the TypeToken .You will have the exact json that you passed in the intent.

how to show only selected data when spinner value is selected in android?

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
}
});

how to display dynamic spinner values in android

In the code below, I took two spinners. One is for brand and other for model. But data is not being displaying in spinner. It is not showing any errors but dropdown is also not shown.
Can any one help me?
What is the mistake in the code?
Java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
private RelativeLayout mRel_Ownview,mRel_publicview;
private LinearLayout mLin_Stock,mLin_Contact;
private TextView mTxt_OwnView,mTxt_PublicView;
private Map<String, String> BrandMap = new HashMap<String, String>();
private RangeSeekBar<Integer> seekBar;
private RangeSeekBar<Integer> seekBar1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
actionBar.setTitle("DEVINE MECHINES");
SharedPreferences userPreference = getActivity().getSharedPreferences("UserDate", Context.MODE_PRIVATE);
userId=userPreference.getString("MYID", null);
companyId=userPreference.getString("companyId",null);
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
seekBar = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
seekBar1 = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar1.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin1);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax1);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
mTxt_OwnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_publicview.setVisibility(View.GONE);
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.text_white));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.light_blue));
mRel_Ownview.setVisibility(View.VISIBLE);
}
});
mTxt_PublicView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_Ownview.setVisibility(View.GONE);
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.text_white));
mRel_publicview.setVisibility(View.VISIBLE);
}
});
String selectedBrandId = BrandMap.get(String.valueOf(spinner1.getSelectedItem()));
// System.out.print(url);
mLin_Stock=(LinearLayout)rootView.findViewById(R.id.stock);
mLin_Stock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment =new StockFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
});
mLin_Contact =(LinearLayout)rootView.findViewById(R.id.contacts);
mLin_Contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getLead();
fragment = new ContactFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
getLead();
}
});
// add RangeSeekBar to pre-defined layout
ViewGroup layout = (ViewGroup) rootView.findViewById(R.id.layout_seek);
layout.addView(seekBar);
ViewGroup layout1 = (ViewGroup) rootView.findViewById(R.id.layout_seek1);
layout1.addView(seekBar1);
getBrands();
getModels();
return rootView;
}
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url", "" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
//Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.i("Brand_result","Now" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
Log.i("listbrands", "List Brands" + listBrands);
/* for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}*/
spinner_fn();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
Log.i("Result","Brand Result"+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
/*ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),
listBrands_String, android.R.layout.simple_spinner_item);*/
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
//dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void getLead()
{
String url = URLBuilder.getLeadUrl();
String json = JSONBuilder.getJSONLead(userId, companyId);
SendToServerTask task = new SendToServerTask(getActivity());
task.execute(url, json);
}
private void setLead(String json)
{
ObjectMapper objectMapper = new ObjectMapper();
try
{
LeadResult result_object = objectMapper.readValue(json, LeadResult.class);
String lead_result = result_object.getRESULT();
Log.d("lead_result","" + lead_result);
if (lead_result.equals("SUCCESS"))
{
list=result_object.getUSERS();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTask extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTask(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setLead(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}

Categories

Resources