MvvmCross Android: Linking kills SwitchCompat.Checked propety - mvvmcross

I have layout with SwitchCompat binding to ViewModel
<android.support.v7.widget.SwitchCompat
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
app:MvxBind="Checked FlashlightEnabled;
Click FlashlightCheckedCommand"/>
I also add in LinkerPleaseInclude.cs file some Include methods
public void Include(Switch s)
{
s.CheckedChange += (sender, args)
=> s.Checked = !s.Checked;
s.Checked = true;
}
public void Include(SwitchCompat sc)
{
sc.CheckedChange += (sender, args)
=> sc.Checked = !sc.Checked;
sc.Checked = true;
}
But when I set the Sdk and User Assemblies linking, my Checked binding is removed.
Output Message:
2018-10-16 12:31:17 [WARN] (MvxBind) Failed to create target binding for binding Checked for FlashlightEnabled10-16 12:31:17.143 I/mono-stdout( 5716): at System.Activator.CreateInstance (System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[]

Make sure you've added [Android.Runtime.Preserve(AllMembers = true)] to your LinkerPleaseInclude class. If not the class will be ignored.
Here you have the latest LinkerPleaseInclude please be sure you have the same:
using Android.App;
using Android.Views;
using Android.Widget;
using MvvmCross.Binding.BindingContext;
using MvvmCross.Navigation;
using MvvmCross.ViewModels;
using System;
using System.Collections.Specialized;
using System.Windows.Input;
namespace $YourNameSpace$
{
// This class is never actually executed, but when Xamarin linking is enabled it does how to ensure types and properties
// are preserved in the deployed app
[Android.Runtime.Preserve(AllMembers = true)]
public class LinkerPleaseInclude
{
public void Include(Button button)
{
button.Click += (s, e) => button.Text = button.Text + "";
}
public void Include(CheckBox checkBox)
{
checkBox.CheckedChange += (sender, args) => checkBox.Checked = !checkBox.Checked;
}
public void Include(Switch #switch)
{
#switch.CheckedChange += (sender, args) => #switch.Checked = !#switch.Checked;
}
public void Include(View view)
{
view.Click += (s, e) => view.ContentDescription = view.ContentDescription + "";
}
public void Include(TextView text)
{
text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
text.Hint = "" + text.Hint;
}
public void Include(CheckedTextView text)
{
text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
text.Hint = "" + text.Hint;
}
public void Include(CompoundButton cb)
{
cb.CheckedChange += (sender, args) => cb.Checked = !cb.Checked;
}
public void Include(SeekBar sb)
{
sb.ProgressChanged += (sender, args) => sb.Progress = sb.Progress + 1;
}
public void Include(RadioGroup radioGroup)
{
radioGroup.CheckedChange += (sender, args) => radioGroup.Check(args.CheckedId);
}
public void Include(RadioButton radioButton)
{
radioButton.CheckedChange += (sender, args) => radioButton.Checked = args.IsChecked;
}
public void Include(RatingBar ratingBar)
{
ratingBar.RatingBarChange += (sender, args) => ratingBar.Rating = 0 + ratingBar.Rating;
}
public void Include(Activity act)
{
act.Title = act.Title + "";
}
public void Include(INotifyCollectionChanged changed)
{
changed.CollectionChanged += (s, e) => { var test = $"{e.Action}{e.NewItems}{e.NewStartingIndex}{e.OldItems}{e.OldStartingIndex}"; };
}
public void Include(ICommand command)
{
command.CanExecuteChanged += (s, e) => { if (command.CanExecute(null)) command.Execute(null); };
}
public void Include(MvvmCross.IoC.MvxPropertyInjector injector)
{
injector = new MvvmCross.IoC.MvxPropertyInjector();
}
public void Include(System.ComponentModel.INotifyPropertyChanged changed)
{
changed.PropertyChanged += (sender, e) =>
{
var test = e.PropertyName;
};
}
public void Include(MvxTaskBasedBindingContext context)
{
context.Dispose();
var context2 = new MvxTaskBasedBindingContext();
context2.Dispose();
}
public void Include(MvxNavigationService service, IMvxViewModelLoader loader)
{
service = new MvxNavigationService(null, loader);
}
public void Include(ConsoleColor color)
{
Console.Write("");
Console.WriteLine("");
color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.ForegroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.DarkGray;
}
}
}

Related

I am trying to show floating activity and it is working but the problem appears on less than API 24

2021-08-10 10:21:03.685 4272-4288/com.hamid.almusabaha E/libEGL: load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library "/system/lib/egl/libGLES_emulation.so" not found
2021-08-10 10:21:05.530 4272-4272/com.hamid.almusabaha E/ActivityThread: Failed to find provider info for com.google.android.gms.chimera
2021-08-10 10:21:06.564 4272-4343/com.hamid.almusabaha E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2021-08-10 10:21:06.570 4272-4332/com.hamid.almusabaha E/cr_SBApiBridge: Failed to init handler: Attempt to invoke virtual method 'java.lang.reflect.Constructor java.lang.Class.getDeclaredConstructor(java.lang.Class[])' on a null object reference
2021-08-10 10:21:11.302 4272-4272/com.hamid.almusabaha E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hamid.almusabaha, PID: 4272
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at com.hamid.almusabaha.Musbiha_Large$7.run(Musbiha_Large.java:185)
at android.app.Activity.runOnUiThread(Activity.java:5866)
at com.hamid.almusabaha.Musbiha_Large.showFloatView(Musbiha_Large.java:179)
at com.hamid.almusabaha.MainActivity$20.onClick(MainActivity.java:318)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
This is my activity
public class Musbiha_Large {
private static boolean mIsFloatViewShowing;
private Activity mActivity;
private WindowManager mWindowManager;
private View mFloatView;
private WindowManager.LayoutParams mFloatViewLayoutParams;
private boolean mFloatViewTouchConsumedByMove = false;
private int mFloatViewLastX;
private int mFloatViewLastY;
private int mFloatViewFirstX;
private int mFloatViewFirstY;
static LinearLayout coverLargeL;
private int numpr = 0;
boolean isDark = false;
boolean isPha = false;
public
Musbiha_Large(final Activity activity) {
mActivity = activity;
LayoutInflater inflater = LayoutInflater.from(activity);
mFloatView = inflater.inflate(R.layout.musbiha_large, null);
final TextView textNbrLarge = mFloatView. findViewById ( R.id.textNbrLarge );
final ImageView PlayLarge = mFloatView. findViewById ( R.id.PlayLarge );
final ImageView lightLarge = mFloatView. findViewById ( R.id.lightLarge );
final ImageView ResetLarge = mFloatView. findViewById ( R.id.ResetLarge );
final LinearLayout lirarlightLarge = mFloatView. findViewById ( R.id.lirarlightLarge );
final ImageButton exetLarge = mFloatView.findViewById(R.id.exetLarge);
final ImageButton plph = mFloatView.findViewById(R.id.plph);
coverLargeL = mFloatView.findViewById(R.id.
coverLargeF);
exetLarge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismissFloatView();
}
});
mFloatView.setOnClickListener(mFloatViewOnClickListener);
mFloatView.setOnTouchListener(mFloatViewOnTouchListener);
mFloatViewLayoutParams = new WindowManager.LayoutParams();
mFloatViewLayoutParams.format = PixelFormat.TRANSLUCENT;
mFloatViewLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mFloatViewLayoutParams.type = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
: WindowManager.LayoutParams.TYPE_TOAST;
mFloatViewLayoutParams.gravity = Gravity.CENTER;
mFloatViewLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mFloatViewLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
public void dismissFloatView() {
if (mIsFloatViewShowing) {
mIsFloatViewShowing = false;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mWindowManager != null) {
mWindowManager.removeViewImmediate(mFloatView);
}
}
});
}
}
public void showFloatView() {
if (!mIsFloatViewShowing) {
mIsFloatViewShowing = true;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (!mActivity.isFinishing()) {
mWindowManager = (WindowManager) mActivity.getSystemService(WINDOW_SERVICE);
if (mWindowManager != null) {
mWindowManager.addView(mFloatView, mFloatViewLayoutParams);
}
}
}
});
}
}
private View.OnClickListener mFloatViewOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// Toast.makeText(mActivity, "Float view is clicked!", Toast.LENGTH_SHORT).show();
// sbha.setBackgroundResource ( R.drawable.green );
}
});
}
};
private View.OnTouchListener mFloatViewOnTouchListener = new View.OnTouchListener() {
#TargetApi(Build.VERSION_CODES.FROYO)
#Override
public boolean onTouch(View v, MotionEvent event) {
WindowManager.LayoutParams prm = mFloatViewLayoutParams;
int totalDeltaX = mFloatViewLastX - mFloatViewFirstX;
int totalDeltaY = mFloatViewLastY - mFloatViewFirstY;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mFloatViewLastX = (int) event.getRawX();
mFloatViewLastY = (int) event.getRawY();
mFloatViewFirstX = mFloatViewLastX;
mFloatViewFirstY = mFloatViewLastY;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - mFloatViewLastX;
int deltaY = (int) event.getRawY() - mFloatViewLastY;
mFloatViewLastX = (int) event.getRawX();
mFloatViewLastY = (int) event.getRawY();
if (Math.abs(totalDeltaX) >= 5 || Math.abs(totalDeltaY) >= 5) {
if (event.getPointerCount() == 1) {
prm.x += deltaX;
prm.y += deltaY;
mFloatViewTouchConsumedByMove = true;
if (mWindowManager != null) {
mWindowManager.updateViewLayout(mFloatView, prm);
}
} else {
mFloatViewTouchConsumedByMove = false;
}
} else {
mFloatViewTouchConsumedByMove = false;
}
break;
default:
break;
}
return mFloatViewTouchConsumedByMove;
}
};

Error parsing data JSON, Fragment Android Studio

Someone please help me why my result always error parsing data ?
My app run smoothly but does not display anything. i feel so stuck here.
this is my code
Sorry for bad english
API JSON
public function getkategori2(){
$data = array();
$token = $this->input->post('f_token');
$tabel = $this->input->post('f_tabel');
if ($token == '' || $tabel == ''){
$data['result'] = false;
$data['msg'] = "Data Kosong";
echo json_encode($data);
return;
}
$sql = 'SELECT * FROM '.$tabel.'_kategori INNER JOIN files WHERE '.$tabel.'_kategori.id_kategori = files.id_kategori';
$q = $this->db->query($sql);
if ($q->num_rows()>0) {
foreach ($q->result() as $value) {
$kategori = array(
'nama_kategori' => $value->nama_kategori,
'file_name' => $value->file_name,
);
};
$data['result'] = true;
$data['kategori_data'] = $kategori;
$data['msg'] = '';
} else {
$data['result'] = false;
$data['msg'] = 'error';
}
echo json_encode($data);
}
JSON Result
{
"result":true,
"kategori_data":
{
"nama_kategori":"Pasta",
"file_name":"1_Pasta.jpg"
},
"msg":""
}
KategoriAdapter
public class KategoriAdapter extends RecyclerView.Adapter<KategoriAdapter.ViewHolder> {
private ArrayList<Kategori> mData;
private Context context;
private SessionManager sesi;
public KategoriAdapter (Context context, ArrayList<Kategori> mData){
this.context = context;
this.mData = mData;
}
#Override
public KategoriAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(context)
.inflate(R.layout.item_list_kategori, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(KategoriAdapter.ViewHolder holder, int position) {
Kategori k = mData.get(position);
String kategori = k.getKategoriNama();
String gambar = k.getImg();
//masukan kedalam object viewholder
holder.tvKategori.setText(kategori);
Picasso.with(context)
.load(Constant.BASE_IMAGE + sesi.getTabel() + "/kategori/" + gambar)
.into(holder.ivKategori);
}
//buta object interface onAdapterjabatanListener
private OnAdapterListener listener;
//buat method untuk mendefiniskan listenernya
public void setListener(OnAdapterListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
//buat class yang extend dari ViewHolder
class ViewHolder extends RecyclerView.ViewHolder{
public LinearLayout container;
public TextView tvKategori;
public ImageView ivKategori;
public ViewHolder(View v){
super(v);
//baru hubungkan variablenya dengan item yang ada di class layout item
container = v.findViewById(R.id.container);
tvKategori = v.findViewById(R.id.tvKategori);
ivKategori = v.findViewById(R.id.ivKategori);
}
}
KategoriFragment
public class KategoriFragment extends Fragment {
SessionManager sesi;
private ArrayList<Kategori> data;
private OkHttpClient okClient;
private RecyclerView rvData;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_kategori, container, false);
sesi = new SessionManager(getActivity());
data = new ArrayList<>();
okClient = new OkHttpClient();
rvData = rootView.findViewById(R.id.rvData);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
rvData.setLayoutManager(manager);
getData();
return rootView;
}
private void getData(){
data.clear();
String url = Constant.BASE_URL + "getkategori2";
FormBody parameters = new FormBody.Builder()
.add("f_token", sesi.getToken())
.add("f_tabel", sesi.getTabel())
.build();
//buat request untuk ambil data
Request request = new Request.Builder()
.url(url)
.post(parameters)
.build();
okClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
e.printStackTrace();
RbHelpers.pesan(getActivity(),
"error :" + e.getMessage());
}
});
}
#Override
public void onResponse(Call call,final Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//hilangkan dialognya
}});
final String responData = response.body().string();
RbHelpers.pre("respon data : " + responData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//debug hasilnya kedalam android monitor
try {
//parsing json
try {
JSONObject json = new JSONObject(responData);
Log.d("tagJSON",json.toString());
//check hasilnya apakah true or false
boolean hasil = json.getBoolean("result");
if (hasil){
//ada datanya
//buat object jsonArray
JSONArray jArray = json.getJSONArray("kategori_data");
//looping data dan masukkan kedalam arraylist
for (int i = 0; i < jArray.length(); i++){
JSONObject jObj = jArray.getJSONObject(i);
Kategori kategori = new Kategori();
kategori.setKategoriNama(jObj.getString("nama_kategori"));
kategori.setImg(jObj.getString("file_name"));
//tinggal masukan ke arraylist
data.add(kategori);
}
} else {
String msg = json.getString("msg");
RbHelpers.pesan(getActivity(), msg);
}
//tinggal masukin ke recylerview
//UserAdapter adapter = new UserAdapter
KategoriAdapter adapter = new KategoriAdapter(getActivity(), data);
rvData.setAdapter(adapter);
} catch (JSONException e){
RbHelpers.pesan(getActivity(), "Error parsing data");
e.printStackTrace();
}
} catch (Exception e) {
RbHelpers.pesan(getActivity(), "Error ambil data");
e.printStackTrace();
}
}
});
}
});
}
Think this is the wrong part "kategori_data" is a JSONObject , not a JSONArray, Check the correct format in jsonBlob as
Here you have an example of a mine working project where i have a model Articulo(Product) and I make a request to retrieve that object data
try{
// Get the JSON array
JSONObject result = response.getJSONObject("articulo");
int i ;
for(i=0;i<1;i++){
JSONObject articulo = result;
ListaArticulos item = new ListaArticulos(
articulo.getString("IdArticulo"),
articulo.getString("Precio"),
articulo.getString("Stock"),
articulo.getString("Consultas"),
articulo.getString("IdCategoria"),
articulo.getString("Descripcion"),
articulo.getString("Observacion"),
articulo.getString("Codigo"),
articulo.getString("Imagen")
);
So in conclusion what you need to do is change JSONArray jArray = json.getJSONArray("kategori_data");
for
JSONObject jsonOb = json.getJSONObject("kategori_data");

NullPointerException: thrown in OnMapReady method

Started running my google maps project and encountered this NullPointerException error in the
Logcat ->
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.sachiewerk.smart_healthcare.pharma2.onMapReady(pharma2.java:100)
at com.google.android.gms.maps.zzak.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:504)
at fr.b(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):20)
at com.google.android.gms.maps.internal.bg.a(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):5)
at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):5)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
The app finds and displays nearby pharmacies, This class show details of nearby pharmacy details like(address, phone numbers, website URI and price ratings) in a custom info window.
this is the class java code
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sachiewerk.smart_healthcare.models.PlaceInfo;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class pharma2 extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready..");
mMap = googleMap;
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.getUiSettings().setMyLocationButtonEnabled(false);
buildGoogleApiClient();
init();
}
/*
------------------------------------------------------------------------
*/
Button btnPharma = (Button) findViewById(R.id.btnPharma);
btnPharma.setOnClickListener(new View.OnClickListener(){
String search = "pharmacy";
#Override
public void onClick (View v){
mMap.clear();
String url = getUrl(latitude, longitude, search);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
GetNearbyBanksData getNearbyPlacesData = new GetNearbyBanksData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(pharma2.this, "These are your Nearby Pharmacies! ",
Toast.LENGTH_LONG).show();
}
});
/*
------------------------------------------------------------------------
*/
}
private static final String TAG = "pharma2";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 20f;
private static final int PLACE_PICKER_REQUEST = 1;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136));
//widgets
private AutoCompleteTextView mSearchText;
private ImageView mGps;
private ImageView mInfo;
private ImageView mPlacePicker;
//vars
private boolean mLocationPermissionGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutocompleteAdapter mPlaceAutocompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
private Marker mMarker;
private Location mLastLocation;
LocationRequest mLocationRequest;
double latitude, longitude;
private int PROXIMITY_RADIUS = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hosp2);
mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
mGps = (ImageView) findViewById(R.id.ic_gps);
mInfo = (ImageView) findViewById(R.id.place_info);
mPlacePicker = (ImageView) findViewById(R.id.place_picker);
getLocationPermission();
}
private void init() {
Log.d(TAG, "init: initializing");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mSearchText.setOnItemClickListener(mAutocompleteClickListener);
mPlaceAutocompleteAdapter = new PlaceAutocompleteAdapter(this, Places.getGeoDataClient(this, null),
LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(mPlaceAutocompleteAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
//execute our method for searching
geolocate();
}
return false;
}
});
}
mGps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked gps icon");
getDeviceLocation();
}
});
mInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked place Info");
try {
if (mMarker.isInfoWindowShown()) {
mMarker.hideInfoWindow();
} else {
Log.d(TAG, "onClick: place info: " + mPlace.toString());
mMarker.showInfoWindow();
}
} catch (NullPointerException e) {
Log.e(TAG, "onClick: NullPointerException: " + e.getMessage());
}
}
});
mPlacePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(pharma2.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, "onClick: GooglePlayServicesRepairableException: " + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, "onClick: GooglePlayServicesNotAvailableException: " + e.getMessage());
}
}
});
hideSoftKeyboard();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, place.getId());
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
}
}
private void geolocate() {
Log.d(TAG, "geolocate: geolocating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(pharma2.this);
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchString, 2);
} catch (IOException e) {
Log.d(TAG, "geolocate: IOException: " + e.getMessage());
}
if (list.size() > 0) {
Address address = list.get(0);
Log.d(TAG, "geolocate: found a location: " + address.toString());
//Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM,
address.getAddressLine(0));
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new
StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyAvxiw4FVJzY-XGx9mW8fNde4bjvc8mlbo");
return (googlePlacesUrl.toString());
}
/*
------------------------------------------------------------------------
*/
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting device's current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM, "Your Device's Location");
} else {
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(pharma2.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom, PlaceInfo placeInfo) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
mMap.clear();
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(pharma2.this));
if (placeInfo != null) {
try {
String snippet = "Address: " + placeInfo.getAddress() + "\n" +
"Phone Number: " + placeInfo.getPhoneNumber() + "\n" +
"Website: " + placeInfo.getWebsiteUri() + "\n" +
"Rating: " + placeInfo.getRating() + "\n";
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(placeInfo.getName())
.snippet(snippet);
mMarker = mMap.addMarker(options);
} catch (NullPointerException e) {
Log.e(TAG, "moveCamera: NullPointerException: " + e.getMessage());
}
} else {
mMap.addMarker(new MarkerOptions().position(latLng));
}
hideSoftKeyboard();
}
private void moveCamera(LatLng latLng, float zoom, String title) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
if (!title.equals("My Location")) {
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(title);
mMap.addMarker(options);
}
hideSoftKeyboard();
}
private void initMap() {
Log.d(TAG, "initMap: initializing map..");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(pharma2.this);
}
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called");
mLocationPermissionGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionGranted = true;
//initialize map
initMap();
}
}
}
}
private void hideSoftKeyboard() {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/*---------------------------------------------------------------------------------------------------------- */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
/*---------------------------------------------------------------------------------------------------------- */
/*
----------------------Google Places Autocomplete suggesstions-------------------------------------------------------------
*/
private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
hideSoftKeyboard();
final AutocompletePrediction item = mPlaceAutocompleteAdapter.getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient ,placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
if(!places.getStatus().isSuccess()){
Log.d(TAG, "onResult: PLace query did not complete successfully: " + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(TAG, "onResult: name: " + place.getName());
mPlace.setAddress(place.getAddress().toString());
Log.d(TAG, "onResult: address: " + place.getAddress());
// mPlace.setAttribution(place.getAttributions().toString());
// Log.d(TAG, "onResult: attribution: " + place.getAttributions());
mPlace.setId(place.getId());
Log.d(TAG, "onResult: id: " + place.getId());
mPlace.setLatLng(place.getLatLng());
Log.d(TAG, "onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(TAG, "onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(TAG, "onResult: Phone Number:" + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(TAG, "onResult: Website: " + place.getWebsiteUri());
Log.d(TAG, "onResult: place: " + mPlace.toString());
}catch(NullPointerException e){
Log.d(TAG, "onResult: NullPointerException: " + e.getMessage() );
}
moveCamera(new LatLng(place.getViewport().getCenter().latitude,
place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace);
places.release();
}
};
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mMarker != null) {
mMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("You are Here!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(pharma2.this, "Your Current Location",
Toast.LENGTH_LONG).show();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
Really want to get this app to work because it is my end of year project for my java class.
Any help will much appreciated.
I think it's not working because you're calling the method OnMapReady() before creating the view in the OnCreate() method. Besides, you're not calling the method initMap() anywhere.
i think you got error on this part.
Button btnPharma = (Button) findViewById(R.id.btnPharma);
btnPharma.setOnClickListener(new View.OnClickListener(){});
Your activity_hosp2.xml doesn't have btnPharma id, thus it got
Attempt to invoke virtual method on a null object reference
when you try to listener to null object.

How to detect If AdRotator V2.1 is showing an Ad or an error occurred

I want to update my UI based on the scenario when an Ad is being shown or an error occurred. I am using AdRotator v2.1. Looking at the source code it seems that the control would collapse if it could not serve an ad from various provider, and the IsAdRotatorEnabled would be set to false. But that property does not trigger an notification change. How can i detect if no ads are being shown?
Enabled="{Binding AreAdsEnabled,Mode=TwoWay,FallbackValue=true,UpdateSourceTrigger=PropertyChanged}"
This is hack i am currently using. Its quite brittle. Its looking at log message for strings to detect if an error has occurred.
public class BaseAdControl
{
public AdRotatorControl CurrentAdRotatorControl { get; set; }
private UserControl userControlWrapper;
public BaseAdControl(AdRotatorControl MyAdRotatorControl, UserControl userControlWrapper)
{
// TODO: Complete member initialization
this.CurrentAdRotatorControl = MyAdRotatorControl;
this.userControlWrapper = userControlWrapper;
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.PubCenter, typeof(Microsoft.Advertising.WinRT.UI.AdControl));
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.AdDuplex, typeof(AdDuplex.Universal.Controls.Win.XAML.AdControl));
MyAdRotatorControl.Loaded += MyAdRotatorControl_Loaded;
MyAdRotatorControl.Unloaded += MyAdRotatorControl_Unloaded;
}
#region Public Properties
#endregion Public Properties
#region Public Methods
public virtual void adDuplex_AdLoadingError(object sender, AdDuplex.Universal.Win.WinRT.Models.AdLoadingErrorEventArgs e)
{
AdDuplex.Universal.Controls.Win.XAML.AdControl adCtrl = sender as AdDuplex.Universal.Controls.Win.XAML.AdControl;
adCtrl.AdLoadingError -= adDuplex_AdLoadingError;
Utilities.logger.LogDebug(e.Error.Message);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual async void Logger(string message)
{
Utilities.logger.LogDebug("AdRotator: " + message);
if (string.Equals(message, "No Ads available", StringComparison.CurrentCultureIgnoreCase))
{
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
else if (message.Contains("Ad created for provider"))
{
var cont = CurrentAdRotatorControl as Control;
Object adType = null;
if (cont != null)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
Border border = VisualTreeHelper.GetChild(CurrentAdRotatorControl, 0) as Border;
if (border != null)
{
adType = border.Child;
}
});
if (adType != null)
{
if (adType is Microsoft.Advertising.WinRT.UI.AdControl)
{
var pubsub = adType as Microsoft.Advertising.WinRT.UI.AdControl;
if (pubsub != null)
pubsub.ErrorOccurred += pubsub_ErrorOccurred;
}
else if (adType is AdDuplex.Universal.Controls.Win.XAML.AdControl)
{
var adDuplex = adType as AdDuplex.Universal.Controls.Win.XAML.AdControl;
if (adDuplex != null)
adDuplex.AdLoadingError += adDuplex_AdLoadingError;
}
else if (adType is SomaAd)
{
var smato = adType as SomaAd;
if (smato != null)
smato.GetAdError += smato_GetAdError;
}
}
}
this.userControlWrapper.Visibility = Utilities.AreAdsEnabled ? Visibility.Visible : Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: "+this.userControlWrapper.Visibility);
}
}
public virtual void MyAdRotatorControl_Loaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log += Logger;
}
public virtual void MyAdRotatorControl_Unloaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log -= Logger;
}
public virtual void pubsub_ErrorOccurred(object sender, Microsoft.Advertising.WinRT.UI.AdErrorEventArgs e)
{
Microsoft.Advertising.WinRT.UI.AdControl adCtrl = sender as Microsoft.Advertising.WinRT.UI.AdControl;
adCtrl.ErrorOccurred -= pubsub_ErrorOccurred;
Utilities.logger.LogDebug(e.Error + " ," + e.ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual void smato_GetAdError(object sender, string ErrorCode, string ErrorDescription)
{
SomaAd adCtrl = sender as SomaAd;
adCtrl.GetAdError -= smato_GetAdError;
Utilities.logger.LogDebug(ErrorDescription + " ," + ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
#endregion Public Methods
}

WP8 issue with html agility pack

This is the function I used to get the string content from the website ..the problem is when executed first I cannot get the string content (App.Data2 = userprofile.InnerText;) since it skips to the next line (App.savecontent(App.Data2);) so that I get an empty string. If I recall the function I could get the string. Is there any possibility to solve this issue I need the string value first time automatically
This is my Page.cs code :
namespace Project_Future1
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
{
string url = "http://www.astrosage.com/horoscope/daily-";
HtmlWeb.LoadAsync(url + App.Data + "-horoscope.asp", DownLoad);
}
data();
App.loadContent();
change2();
}
public void change2()
{
try
{
Util.LiveTile.UpdateLiveTile(App.Data2);
}
catch (Exception)
{
}
}
public void DownLoad(object sender, HtmlDocumentLoadCompleted e)
{
if (e.Error == null)
{
HtmlDocument doc = e.Document;
if (doc != null)
{
var userprofile = doc.DocumentNode.SelectSingleNode("//div[#class = 'ui-large-content']");
App.Data2 = userprofile.InnerText;
App.savecontent(App.Data2);
}
}
}
private void data()
{
SelectedSign.Text = App.Data;
SSContent.Text = App.Data2;
}
private void Refresh_click(object sender, EventArgs e)
{
SSContent.Text = App.Data2;
}
private void Fb_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/FB.xaml", UriKind.Relative));
}
}
}
this is my App.Xaml.cs File :
public static void savecontent(string save)
{
try
{
if (!string.IsNullOrEmpty(appFileName1))
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
oIsolatedStorage.CreateDirectory(appFolder1);
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(appFolder1 + "\\" + appFileName1, FileMode.OpenOrCreate, oIsolatedStorage));
writeFile.WriteLine(save);
writeFile.Close();
}
}
catch (Exception)
{
throw;
}
}
this is my code to load the content from the storage :
public static void loadContent()
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (oIsolatedStorage.DirectoryExists(appFolder1))
{
IsolatedStorageFileStream fileStream = oIsolatedStorage.OpenFile(appFolder1 + "\\" + appFileName1, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
App.Data2 = reader.ReadLine();
reader.Close();
}
}
}