Activity search crash - android

Hello guys i have an issue with my search activit. If i try to search an item for example (iphone 6) and type only "iphone" or "6" or only "i" and other exc... the search works god, but if i put the entire name of the item in this case : iphone 6 , apps crash.
This is the code :
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lsv;
String categoryId,keyword,city;
ProgressDialog progressBar;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
#SuppressLint("NewApi") #Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Browse Ads");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
lsv = (ListView)findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
categoryId = getIntent().getExtras().getString("categoryId", "0");
keyword = getIntent().getExtras().getString("keyword","keyword");
city = getIntent().getExtras().getString("city","city");
new SearchList().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), BrowseAdsDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
}
#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();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class SearchList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(SearchActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.ADSEARCH_URL,categoryId,city,keyword), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = contacts.length()-1; i > -1; i--) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adCreatedAt = c.getString("adCreatedAt");
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdCreatedAt(adCreatedAt);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} 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);
cd.dismissdialog();
adapter = new CateAdDisplayAdapter(getApplicationContext(), catAddList);
lsv.setAdapter(adapter);
}
}

Assuming you are making an api call:
You should encode parameters in your url.
String query = URLEncoder.encode("phone 6", "utf-8");
String url = "http://myurl.com/search?q=" + query;
The result would be: http://myurl.com/search?q=phone%206

Related

how can i display add to cart button in listview with baseadapter

i am working on a ecommerce app and i have a list where list of items will be there. Just like product name, price, discounted value etc fetched from database.
i am using ListView to show products where every item have there seprate Menu_ID. Whenever i click on list item following code is run where i use putExtra to open speciefic menu_id item details.
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
and new activity will be open with product detail where i display add to cart button whenever i click on add to cart button item display in cart activity.
code is like
public void inputDialog() {
// open database first
try {
dbhelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.order);
alert.setMessage(R.string.number_order);
alert.setCancelable(false);
final EditText edtQuantity = new EditText(this);
int maxLength = 3;
edtQuantity.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
edtQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(edtQuantity);
alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String temp = edtQuantity.getText().toString();
int quantity = 0;
// when add button clicked add menu to order table in database
if (!temp.equalsIgnoreCase("")) {
quantity = Integer.parseInt(temp);
Toast.makeText(getApplicationContext(), "Success add product to cart", Toast.LENGTH_SHORT).show();
if (dbhelper.isDataExist(Menu_ID)) {
dbhelper.updateData(Menu_ID, quantity, (Menu_price * quantity));
} else {
dbhelper.addData(Menu_ID, Menu_name, quantity, (Menu_price * quantity));
}
checkoutButton.setEnabled(true);
checkoutButton.setBackgroundColor(R.color.ColorPrimaryDark);
checkoutButton.setTextColor(Color.WHITE);
} else {
dialog.cancel();
checkoutButton.setEnabled(false);
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// when cancel button clicked close dialog
dialog.cancel();
}
});
alert.show();
}
Now the question is
i want to display add to cart button in product list where i place my order directly from product list without opening product detail.
ListActivity is like
public class ActivityMenuList extends AppCompatActivity {
ListView listMenu;
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
// declare static variable to store tax and currency symbol
public static double Tax;
public static String Currency;
private ActivityMenuDetail details;
// declare adapter object to create custom menu list
AdapterMenuList mla;
// create arraylist variables to store data from server
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
public static ArrayList<Double> Discounted_Price = new ArrayList<Double>();
public static ArrayList<String> Discounted_Value = new ArrayList<String>();
public static ArrayList<Double> Our_Price = new ArrayList<Double>();
String MenuAPI;
String fullAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
DecimalFormat formatData1 = new DecimalFormat("#.##");
DecimalFormat formatData2 = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_list);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.title_menu);
}
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listMenu = (ListView) findViewById(R.id.listMenu);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// menu API url
MenuAPI = Config.ADMIN_PANEL_URL+"/api/get-menu-data-by-category-id2.php"+"?accesskey="+Config.AccessKey+"&category_id=";
// tax and currency API url
TaxCurrencyAPI = Config.ADMIN_PANEL_URL+"/api/get-tax-and-currency.php"+"?accesskey="+Config.AccessKey;
// get category id and category name that sent from previous page
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category_name");
MenuAPI += Category_ID;
mla = new AdapterMenuList(ActivityMenuList.this);
// call asynctask class to request tax and currency data from server
new getTaxCurrency().execute();
// event listener to handle search button when clicked
btnSearch.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get keyword and send it to server
try {
Keyword = URLEncoder.encode(edtKeyword.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MenuAPI += "&keyword=" + Keyword;
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
});
// event listener to handle list when clicked
listMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
});
// Using to refresh webpage when user swipes the screen
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
}, 3000);
}
});
listMenu.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean enable = false;
if (listMenu != null && listMenu.getChildCount() > 0) {
boolean firstItemVisible = listMenu.getFirstVisiblePosition() == 0;
boolean topOfFirstItemVisible = listMenu.getChildAt(0).getTop() == 0;
enable = firstItemVisible && topOfFirstItemVisible;
}
swipeRefreshLayout.setEnabled(enable);
}
});
}
#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_category, 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.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent i = new Intent(ActivityMenuList.this, ActivityCart.class);
startActivity(i);
return true;
case R.id.refresh:
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// asynctask class to handle parsing json in background
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
// method to parse json data from server
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
Discounted_Value.clear();
Discounted_Price.clear();
Our_Price.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
listMenu.setVisibility(View.VISIBLE);
listMenu.setAdapter(mla);
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Discounted_Price.add(Double.valueOf(formatData1.format(menu.getDouble("Discounted_Price"))));
Our_Price.add(Double.valueOf(formatData2.format(menu.getDouble("Our_Price"))));
Menu_image.add(menu.getString("Menu_image"));
Discounted_Value.add(menu.getString("Discounted_Value"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
listMenu.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
ListAdapter code
public class AdapterMenuList extends BaseAdapter {
private Activity activity;
private ActivityMenuDetail details;
public AdapterMenuList(Activity act) {
this.activity = act;
}
public AdapterMenuList(ActivityMenuDetail details) {
this.details = details;
}
public int getCount() {
return ActivityMenuList.Menu_ID.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lsv_item_menu_list, null);
holder = new ViewHolder();
holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
holder.txtSubText = (TextView) convertView.findViewById(R.id.txtSubText);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.ImageCatList);
holder.discounted_Price = (TextView) convertView.findViewById(R.id.DiscPriceCatList);
holder.discounted_Value = (TextView) convertView.findViewById(R.id.DiscValueCatList);
holder.discounted_Price.setTextColor(Color.GRAY);
holder.discounted_Price.setPaintFlags(holder.discounted_Price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.addtocart = (TextView) convertView.findViewById(R.id.Listaddtocart);
holder.layout = (LinearLayout) convertView.findViewById(R.id.Listcardview);
holder.our_Price = (TextView) convertView.findViewById(R.id.Our_Price);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.discounted_Value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if(editable.toString().equals("0 % off") | editable.toString().equals("00 % off")){
// 1 - You can set empty text
holder.discounted_Value.setText("");
// 2 - Or you can change the color of the text
holder.discounted_Value.setTextColor(Color.TRANSPARENT);
// 3 - Or you can change the visibility of the view
holder.discounted_Value.setVisibility(View.INVISIBLE);
holder.layout.setVisibility(View.GONE);
}else{
//Here you should undo your code
//1 - if you using method one dose not need to do anything here
// for method 2
holder.discounted_Value.setTextColor(Color.BLACK);
// for method 3
holder.discounted_Value.setVisibility(View.VISIBLE);
holder.layout.setVisibility(View.VISIBLE);
}
}
});
holder.txtText.setText(ActivityMenuList.Menu_name.get(position));
holder.txtSubText.setText("\u20B9" + ActivityMenuList.Menu_price.get(position));
holder.discounted_Price.setText("\u20B9" + ActivityMenuList.Discounted_Price.get(position));
holder.discounted_Value.setText(ActivityMenuList.Discounted_Value.get(position)+ " % off");
holder.our_Price.setText("Our Price" + " " + "\u20B9" + ActivityMenuList.Our_Price.get(position));
Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityMenuList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);
return convertView;
}
static class ViewHolder {
TextView txtText, txtSubText, discounted_Price, quantity, discounted_Value, our_Price;
ImageView imgThumb;
TextView addtocart;
LinearLayout layout;
}
}
Any idea how can i put add to cart button in listview item where i place order from list without opening new activity.
thankx.
Yes it is pretty straight forward to do.
Just add the "add to cart" option in every item itself.
So in the listview, show add to cart at the right most side where the user can click to add to the cart directly.
To get the click, in the base adapter in the getView() method, set the click listener on that holder item(add to cart button) and do the stuff in its onClick.

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

Issue on my activity

Hello all i have a search activity into my app that works good if i try to search an item by tiping a text keyword but if i try to search an item that also contain a number app crash. For example if i try to search the text "home" search works good but if i search "home 3" app crash. The error is : exception-illegal-character-in-query-at-index I want that the search works good also by typing a text or a text + number exc..
Thank you
IMPORTANT :
the search activity call an encoded url, "ADSEARCH_URL"
public static final String ADSEARCH_URL="https://gjeme.com/apps/menjehere/index.php?action=searchAd&categoryId=%s&adcity=%s&q=%s";
This is the search activity :
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lsv;
String categoryId,keyword,city;
ProgressDialog progressBar;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
#SuppressLint("NewApi") #Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Browse Ads");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif- Bold.otf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
lsv = (ListView)findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
categoryId = getIntent().getExtras().getString("categoryId", "0");
keyword = getIntent().getExtras().getString("keyword","keyword");
city = getIntent().getExtras().getString("city","city");
new SearchList().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), BrowseAdsDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
}
#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();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class SearchList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(SearchActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.ADSEARCH_URL,categoryId,city,keyword) , ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = contacts.length()-1; i > -1; i--) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adCreatedAt = c.getString("adCreatedAt");
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdCreatedAt(adCreatedAt);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} 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);
cd.dismissdialog();
adapter = new CateAdDisplayAdapter(getApplicationContext(), catAddList);
lsv.setAdapter(adapter);
}
}
}
I think there isn't any problem with alpha-numeric characters here, but the SPACE is created one, while you are adding the text to URL.
Replace space(es) of searched keyword with %20 and hopefully you will find it fine.

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

When I press backspace did the AutoCompleteTextView show the suggestion list

My code is following ...
public class NameListActivity extends Activity implements TextWatcher {
private Button add = null;
private AutoCompleteTextView editAuto = null;
private Button chfrlist = null;
private ImageView im = null;
String access_token = new String();
private ImageView infobtn = null;
private PopupWindow popupWindow;
private View view;
private ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_name_list);
access_token = MainService.readToken();
add = (Button) findViewById(R.id.add_button);
editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
chfrlist = (Button) findViewById(R.id.chfrlistbutton);
im = (ImageView) findViewById(R.id.helpact);
im.setOnClickListener(new ImageListener());
infobtn = (ImageView) findViewById(R.id.informbtn);
initPopupWindow();
infobtn.setOnClickListener(new infobtnListener());
editAuto.addTextChangedListener(this);
add.setOnClickListener(new addListener());
chfrlist.setOnClickListener(new ChfrListListener());
}
public class addListener implements OnClickListener {
public void onClick(View v) {
addTask task = new addTask();
task.execute();
editAuto.setText("");
}
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChangedTask task = new onTextChangedTask();
task.execute();
}
public class onTextChangedTask extends AsyncTask<Void, Void, Void> {
ArrayAdapter<String> adapter = null;
String[] userName = null;
String q = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
ArrayList<String> userNameArrayList = new ArrayList<String>();
Weibo weibo = new Weibo();
#Override
protected void onPreExecute() {
weibo.setToken(access_token);
q = editAuto.getText().toString();
System.out.println("start onTextChanged");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (q.length() != 0) {
System.out.println("q is " + q);
String s1 = "https://api.weibo.com/search/suggestions/users.json";
try {
jsonArray = Weibo.client.get(s1,
new PostParameter[] { new PostParameter("q", q) })
.asJSONArray();
} catch (Throwable e) {
System.out.println("这里有个神马异常呢 。。。" + e);
}
System.out.println("return length is " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObject = jsonArray.getJSONObject(i);
String sname = jsonObject.getString("screen_name");
userNameArrayList.add(sname);
} catch (JSONException e) {
e.printStackTrace();
}
}
userName = (String[]) userNameArrayList
.toArray(new String[userNameArrayList.size()]);
adapter = new ArrayAdapter<String>(NameListActivity.this,
android.R.layout.simple_dropdown_item_1line, userName);
}
return null;
}
#Override
protected void onPostExecute(Void v) {
System.out.println("post");
editAuto.setAdapter(adapter);
}
}
void showToast(String s) {
Toast toast = Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);
toast.show();
}
public class addTask extends AsyncTask<Void, Void, Void> {
String s = null;
boolean flag = false;
User user = null;
Weibo weibo = new Weibo();
String screen_name = null;
protected void onPreExecute() {
Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
weibo.setToken(access_token);
screen_name = editAuto.getText().toString();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (screen_name.length() != 0) {
Users um = new Users();
try {
user = new User(Weibo.client.get(
"https://api.weibo.com/users/show.json",
new PostParameter[] { new PostParameter(
"screen_name", screen_name) })
.asJSONObject());
} catch (Throwable e) {
e.printStackTrace();
flag = true;
s = new String("您输入的这个用户好像不存在唉");
}
if (user != null) {
ContentValues values = new ContentValues();
values.put("uid", user.getId());
values.put("user_name", user.getName());
SQLiteDatabase db = null;
try {
db = MainService.getDatabase();
} catch (Exception e) {
System.out.println("db error");
finish();
}
Cursor result = db.query("users", new String[] { "uid",
"user_name" }, "uid=?",
new String[] { user.getId() }, null, null, null);
if (result.getCount() == 0)
db.insert("users", null, values);
} else {
flag = true;
s = new String("网络存在问题,检查一下吧");
}
} else {
flag = true;
s = new String("框里输入点东西才能添加啊");
}
return null;
}
#Override
protected void onPostExecute(Void v) {
if (flag == true) {
System.out.println("要打印的是" + s);
showToast(s);
}
}
}
public class infobtnListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击了图片");
ColorDrawable cd = new ColorDrawable(-0000);
popupWindow.setBackgroundDrawable(cd);
// popupWindow.showAsDropDown(v);
popupWindow.showAtLocation(findViewById(R.id.informbtn),
Gravity.LEFT | Gravity.BOTTOM, 0, 100);
}
}
public class ImageListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent t = new Intent(NameListActivity.this,
// GridLayoutActivity.class);
// startActivity(t);
finish();
}
}
public class ChfrListListener implements OnClickListener {
public void onClick(View v) {
if ((haveInternet() == true)
&& (GridLayoutActivity.hasAccessToken() == true)) {
// TODO Auto-generated method stub
pd = ProgressDialog.show(NameListActivity.this, "",
"正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
/* 开启一个新线程,在新线程里执行耗时的方法 */
new Thread(new Runnable() {
public void run() {
Intent t = new Intent(NameListActivity.this,
ChooseFromListActivity.class);
startActivity(t);
finish();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
} else {
Intent t = new Intent(NameListActivity.this,
WebViewActivity.class);
startActivity(t);
finish();
}
}
}
private void initPopupWindow() {
view = getLayoutInflater().inflate(R.layout.namewindow, null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
pd.dismiss();// 关闭ProgressDialog
}
};
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_name_list, menu);
return true;
}
}
My question is : when I input words in the EditText, nothing happened. But when I press backspace did the AutoCompleteTextView show the suggestion list ... the problem is in the editAuto.setAdapter(adapter);
What is wrong?
make the following changes in your code
1) Instead of
private AutoCompleteTextView editAuto = null; JUST WRITE private AutoCompleteTextView editAuto;
2) Add this line to onCrate()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);
and remove this line from onTextChangedTask()
ArrayList<String> userNameArrayList = new ArrayList<String>();
3) Add this line to onCrate()
editAuto.setAdapter(adapter);
I know this is way late but for those who face similar problems here is the solution to show the autoCompleteTextView's drop down whenever you want i.e on button click or onTextChanged. After you set the ArrayAdapter for the autoCompleteTextView just put the following line.
autoCompleteTextView.showDropDown();

Categories

Resources