obj is a string with the Id for a specific object in my parse database. I want to get individual rows values and show them in a text view. The below code is what I've got. Not sure why but the query alwasy seems tho return empty. Thus my strings restName,restCuisine,etc all have their initialized values only i.e their values aren't changing because of my query. Any help would be appreciated
public class SingleRestraunt extends ActionBarActivity {
private GoogleMap map;
TextView resteName, resteCuisine, resteLocation, resteAddress;
String restName = "nothing", obj, restCuisine = "nothing",
restLocation = "nothing", restAddress = "nothing";
Double Lang = 19.144378, Long = 72.837135;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_restraunt);
resteName = (TextView) findViewById(R.id.restrauntName);
resteCuisine = (TextView) findViewById(R.id.restrauntCuisine);
resteLocation = (TextView) findViewById(R.id.restrauntLocation);
resteAddress = (TextView) findViewById(R.id.restrauntAddress);
Intent i = getIntent();
obj = i.getStringExtra("restId");
getDetails(obj);
}
private void getDetails(final String obj) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("resdb");
query.getInBackground(obj, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
restName = object.getString("name");
restCuisine = object.getString("cuisine");
restLocation = object.getString("location");
restAddress = object.getString("address");
} else {
e.printStackTrace();
}
}
});
prepareMap(Lang, Long);
addData();
}
public void addData() {
resteName.setText(restName);
resteCuisine.setText(restCuisine);
resteLocation.setText(restLocation);
resteAddress.setText(restAddress);
}
public void prepareMap(Double Lang, Double Long) {
final LatLng REST = new LatLng(Lang, Long);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
#SuppressWarnings("unused")
Marker hamburg = map.addMarker(new MarkerOptions().position(REST)
.title("Here"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(REST, 15));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.single_restraunt, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
I think it is not correct to call prepareMap(Lang, Long) and addData() after to the call query.getInBackground(...) because "In background" means in a different Thread. You should reorder your calls like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("resdb");
query.getInBackground(obj, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
restName = object.getString("name");
restCuisine = object.getString("cuisine");
restLocation = object.getString("location");
restAddress = object.getString("address");
// Update your info after to get the rest info
prepareMap(Lang, Long);
addData();
} else {
e.printStackTrace();
}
}
});
I hope this help you!
Related
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.
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.
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
I'm trying to get the value the user enters in the userNameVar and passwordVar variables, and then compare them to the values stored in my database. However, when I enter the details, which are the same as what I have stored in my database, I get the following message:
Error message
Here is my login class code
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText usernameField;
private EditText passwordField;
private static Button login_btn;
TextView register_link;
String userNameVar = "";
String passwordVar = "";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
User userObj;
DatabaseUserList databaseUserList = new DatabaseUserList();
private static final String TAG_SUCCESSFUL = "Successful";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
login_btn = (Button) findViewById(R.id.login_button);
usernameField = (EditText) findViewById(R.id.etUsername);
passwordField = (EditText) findViewById(R.id.etPassword);
//starts to listen for clicks on this button
login_btn.setOnClickListener(this);
register_link = (TextView) findViewById(R.id.register_link);
register_link.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_button:
//null object reference problem here
Log.d("Username and password",
userNameVar = usernameField.getText().toString();
passwordVar = passwordField.getText().toString();
usernameField.getText().toString());
validateUser(userNameVar, passwordVar);
break;
}
}
private void validateUser (String username, String password)
{
new LogtheuserIn().execute();
}
private void resultsofloginAttmempt(User u)
{
if(u != null)
{
Log.d("User", userObj.toString() + "User must have logged in successfully");
}
}
private void userLoggedIn()
{
Intent intent = new Intent(this, FirstPage.class);
//User has to implement serializable
intent.putExtra("Userisin", userObj);
startActivity(intent);
}
public class LogtheuserIn extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute()
{
Log.d("onPrexecute", "on the preExecutePart");
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Loading users");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
List<NameValuePair> arguements = new ArrayList<NameValuePair>();
try{
Log.d("This is the username ", "and password taken from the input fields");
String loginDetails = ServerConnection.SERVER_ADDRESS + "login.php?userName=" + userNameVar + "?password" + passwordVar;
JSONObject jObject = jParser.makeHttpRequest(loginDetails, "GET", arguements);
Log.d("All users", jObject.toString());
int success = jObject.getInt(TAG_SUCCESSFUL);
} catch (Exception e) {
pDialog.dismiss();
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "Problem with the server",
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
protected void onPostExecute(String dismissable)
{
//Dismiss the dialogue after we have
//gotten the user(s)
pDialog.dismiss();
Login.this.runOnUiThread(
new Runnable() {
public void run()
{
resultsofloginAttmempt(userObj);
Log.d("Array details", databaseUserList.getListOfUsers().toString());
}
}
);
}
}
#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_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Recheck findViewById(R.id.whatisyourrealid); because it's returning null.
I'm developing an Android application for read some information from a XML file on the web. At first, I had a problem to parsing. Now my problem is that my code read only one information. I've created my class MyFilm. How can I insert all information from that file in my arraylist. Thank you in advance.
public class FilmListActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new WebService() {
#Override
protected ArrayList<MyFilm> doInBackground(Object... params) {
ArrayList<MyFilm> arr = new ArrayList<MyFilm>();
Intent intent = getIntent();
String pkg = getPackageName();
try {
MyFilm parametriRicerca = new MyFilm();
parametriRicerca = (MyFilm) intent.getSerializableExtra(pkg+".MyFilm");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
URL input = new URL("http://whatdowedo.altervista.org/griffith_list2.xml");
xpp.setInput(input.openStream(), null);
int eventType = xpp.getEventType();
String currentTag = null;
MyFilm tmp = new MyFilm();
String title = null;
String regista = null;
String attore = null;
String genere = null;
String paese = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
} else if (eventType == XmlPullParser.TEXT) {
if ("title".equals(currentTag)) {
title = xpp.getText().trim();
}
if("director".equals(currentTag)){
regista = xpp.getText().trim();
}
if("country".equals(currentTag)){
paese = xpp.getText().trim();
}
if("genre".equals(currentTag)){
genere = xpp.getText().trim();
}
if("cast".equals(currentTag)){
attore = xpp.getText().trim();
}
if(parametriRicerca.getTitle().equals(title)){
arr.add(parametriRicerca);
}
}
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
}.execute();
}
abstract class WebService extends AsyncTask<Object, MyFilm, ArrayList<MyFilm>> {
public WebService() {
super();
}
#Override
protected void onPreExecute() {
}
#Override
protected abstract ArrayList<MyFilm> doInBackground(Object... params);
#Override
protected void onPostExecute(ArrayList<MyFilm> result) {
super.onPostExecute(result);
FilmsAdapterView adapter = new FilmsAdapterView(FilmListActivity.this,result);
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}