i want to send current location to specific people in my firebase database when a button is clicked. These people change from device to device depending on which people the user has selected to get notification about the sender's location. I have a clue on what's required of me to do but i can't seem to figure it out.
This is the class i used to read the user's current location:
and in my menuActivity i want to call the latitude and the longitude when sendLoc button is clicked
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {
ImageButton fakeCallBtn;
Button sendLoc;
ImageButton notif;
ImageButton flash;
private GoogleMap mMap;
LocationManager locationManager;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("RescueX ");
sendLoc=(Button)findViewById(R.id.Locationbtn);
sendLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Location l = gt.getLocation();
if( l == null){
Toast.makeText(getApplicationContext(),"GPS unable to get
Value",Toast.LENGTH_SHORT).show();
}else {
double lat = l.getLatitude();
double lon = l.getLongitude();
Intent lociIntent = new Intent(MenuActivity.this,
ViewLocation.class);
lociIntent.putExtra("lat", lat);
lociIntent.putExtra("lon",lon);
startActivity(lociIntent);
Toast.makeText(getApplicationContext()," Emergency Alert has
been Successfully sent ",Toast.LENGTH_SHORT).show();
}
}
});
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getCountryName() + ",";
str += addressList.get(0).getLocality();
mMap.addMarker(new MarkerOptions().position(latLng).title(str)); // this is the location i want to share with the specific people in my database
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
}
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else {
mUserRef.child("online").setValue("true");
}
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null) {
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendToStart() {
Intent startIntent = new Intent(MenuActivity.this, Home.class);
startActivity(startIntent);
finish();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId()== R.id.log_out){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
//noinspection SimplifiableIfStatement
if (item.getItemId() == R.id.action_settings) {
Intent notifIntent= new Intent(MenuActivity.this, Settings.class);
startActivity(notifIntent);
}
if(item.getItemId() == R.id.all_users){
Intent usersIntent= new Intent(MenuActivity.this, UsersActivity.class);
startActivity(usersIntent);
}
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Profile.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_users_activity) {
Intent searchIntent = new Intent(MenuActivity.this, UsersActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_history_layout) {
Intent searchIntent = new Intent(MenuActivity.this, History.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_help_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Help.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_feedback_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Feedback.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_signout_layout) {
Intent searchIntent = new Intent(MenuActivity.this, SignOut.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_friends_layout) {
Intent searchIntent = new Intent(MenuActivity.this, FriendsActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_share) {
Intent searchIntent = new Intent(MenuActivity.this, Share.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}}
this is the class that creates a group that should be sent the location when a button is clicked to send the location:
public class EmergencyList extends AppCompatActivity {
private Toolbar mToolbar;
private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Button mProfileSendReqBtn, mDeclineBtn;
private DatabaseReference mUsersDatabase;
private ProgressDialog mProgressDialog;
private DatabaseReference mFriendReqDatabase;
private DatabaseReference mFriendDatabase;
private DatabaseReference mNotificationDatabase;
private ImageView mProfileImage;
private DatabaseReference mRootRef;
private FirebaseUser mCurrent_user;
private String mCurrent_state;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_list);
mToolbar = (Toolbar)findViewById(R.id.user_Appbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Who to notify in emergency");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String user_id = getIntent().getStringExtra("user_id");
mRootRef = FirebaseDatabase.getInstance().getReference();
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mFriendReqDatabase = FirebaseDatabase.getInstance().getReference().child("Connection_req");
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Contacts");
mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Notification");
mCurrent_user = FirebaseAuth.getInstance().getCurrentUser();
mProfileImage = (ImageView) findViewById(R.id.profile_image);
mProfileName = (TextView) findViewById(R.id.profile_displayName);
mProfileStatus = (TextView) findViewById(R.id.profile_status);
mProfileFriendsCount = (TextView) findViewById(R.id.profile_totalFriends);
mProfileSendReqBtn = (Button) findViewById(R.id.profile_send_req_btn);
mDeclineBtn = (Button) findViewById(R.id.profile_decline_btn);
mCurrent_state = "not_emergency_contact";
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Loading User Data");
mProgressDialog.setMessage("Please wait while we load the user data.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
mUsersDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String display_name = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String image = dataSnapshot.child("profile_picture").getValue().toString();
mProfileName.setText(display_name);
mProfileStatus.setText(status);
Picasso.with(EmergencyList.this).load(image).placeholder(R.drawable.my_profile).into(mProfileImage);
if(mCurrent_user.getUid().equals(user_id)){
mDeclineBtn.setEnabled(false);
mDeclineBtn.setVisibility(View.INVISIBLE);
mProfileSendReqBtn.setEnabled(false);
mProfileSendReqBtn.setVisibility(View.INVISIBLE);
}
//--------------- FRIENDS LIST / REQUEST FEATURE -----
mFriendReqDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
String req_type = dataSnapshot.child(user_id).child("emergency_type").getValue().toString();
if(req_type.equals("received")){
mCurrent_state = "emergency_received";
mProfileSendReqBtn.setText("Accept As Emergency ");
mDeclineBtn.setVisibility(View.VISIBLE);
mDeclineBtn.setEnabled(true);
} else if(req_type.equals("sent")) {
mCurrent_state = "emergency_sent";
mProfileSendReqBtn.setText("Cancel Emergency Request");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
mProgressDialog.dismiss();
} else {
mFriendDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
mCurrent_state = "emergency_contact";
mProfileSendReqBtn.setText("Remove "+mProfileName.getText() + " As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
mProgressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
mProgressDialog.dismiss();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProfileSendReqBtn.setEnabled(false);
// --------------- NOT FRIENDS STATE ------------
if(mCurrent_state.equals("not_emergency_contact")){
DatabaseReference newNotificationref = mRootRef.child("Emergency_Notification").child(user_id).push();
String newNotificationId = newNotificationref.getKey();
HashMap<String, String> notificationData = new HashMap<>();
notificationData.put("from", mCurrent_user.getUid());
notificationData.put("type", "request");
Map requestMap = new HashMap();
requestMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id + "/emergency_type", "sent");
requestMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid() + "/emergency_type", "received");
requestMap.put("Emergency_Notifications/" + user_id + "/" + newNotificationId, notificationData);
mRootRef.updateChildren(requestMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Toast.makeText(EmergencyList.this, "There was some error in sending request", Toast.LENGTH_SHORT).show();
} else {
mCurrent_state = "emergency_sent";
mProfileSendReqBtn.setText("Cancel Emergency Contact");
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
// - -------------- CANCEL REQUEST STATE ------------
if(mCurrent_state.equals("emergency_sent")){
mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mProfileSendReqBtn.setEnabled(true);
mCurrent_state = "not_emergency_contact";
mProfileSendReqBtn.setText("Add As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
});
}
});
}
// ------------ REQ RECEIVED STATE ----------
if(mCurrent_state.equals("emergency_received")){
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id + "/date", currentDate);
friendsMap.put("Emergency_Contact/" + user_id + "/" + mCurrent_user.getUid() + "/date", currentDate);
friendsMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id, null);
friendsMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid(), null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
mProfileSendReqBtn.setEnabled(true);
mCurrent_state = "emergency_contact";
mProfileSendReqBtn.setText("Remove " + mProfileName.getText() + " As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
} else {
String error = databaseError.getMessage();
Toast.makeText(EmergencyList.this, error, Toast.LENGTH_SHORT).show();
}
}
});
}
// ------------ UNFRIENDS ---------
if(mCurrent_state.equals("emergency_contact")){
Map unfriendMap = new HashMap();
unfriendMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id, null);
unfriendMap.put("Emergency_Contact/" + user_id + "/" + mCurrent_user.getUid(), null);
mRootRef.updateChildren(unfriendMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
mCurrent_state = "not_emergency_contact";
mProfileSendReqBtn.setText("Add As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
} else {
String error = databaseError.getMessage();
Toast.makeText(EmergencyList.this, error, Toast.LENGTH_SHORT).show();
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
}
});
}
}
this is the class where i call the people from my Emergency_Contacts in my database:
public class EmergencyFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public EmergencyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_emergency, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.emergency_contacts);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Contact").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Emergency, EmergencyFragment.EmergencyViewHolder> emergencyRecyclerViewAdapter = new FirebaseRecyclerAdapter<Emergency, EmergencyFragment.EmergencyViewHolder>(
Emergency.class,
R.layout.users_emergency_layout,
EmergencyFragment.EmergencyViewHolder.class,
mFriendsDatabase
) {
#Override
protected void populateViewHolder(final EmergencyFragment.EmergencyViewHolder emergencyViewHolder, Emergency emergency, int i) {
emergencyViewHolder.setDate(emergency.getDate());
final String user_id = getRef(i).getKey();
mUsersDatabase.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String Username = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
emergencyViewHolder.setName(Username);
emergencyViewHolder.setUserImage(userThumb, getContext());
emergencyViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{" Open Details", "view history"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent emergencyIntent = new Intent(getContext(), EmergencyList.class);
emergencyIntent.putExtra("user_id", user_id);
startActivity(emergencyIntent);
}
if(i == 1){
Intent historyIntent = new Intent(getContext(), History.class);
historyIntent.putExtra("user_id", user_id);
historyIntent.putExtra("Username", Username);
startActivity(historyIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(emergencyRecyclerViewAdapter);
}
public static class EmergencyViewHolder extends RecyclerView.ViewHolder {
View mView;
public EmergencyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.contacts_status);
userStatusView.setText(date);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.contacts_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.image_display);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.my_profile).into(userImageView);
}
}
}
}
i want the location to be stored or opened on the history class now i am not sure how to get the location from the menuactivity class -> Emergency_Contacts then to -> history where it's going to be displayed.
Related
Why if change mSwitch1 or mSwitch2 or mSwitch3, change All Switchs? If you leave one Switch in Activity, everything works.
AndroidStudio / javascript .
Why if change mSwitch1 or mSwitch2 or mSwitch3, change All Switchs? If you leave one Switch in Activity, everything works.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
...
String sw1 = pref.getString(APP_PREFERENCES_SWITCH1, "");
String sw2 = pref.getString(APP_PREFERENCES_SWITCH2, "");
String sw3 = pref.getString(APP_PREFERENCES_SWITCH3, "");
if (sw1.length() == 2) {
mSwitch1.setChecked(true);
}
if (sw1.length() == 1) {
mSwitch1.setChecked(false);
}
if (sw2.length() == 2) {
mSwitch2.setChecked(true);
}
if (sw2.length() == 1) {
mSwitch2.setChecked(false);
}
if (sw3.length() == 2) {
mSwitch3.setChecked(true);
}
if (sw3.length() == 1) {
mSwitch3.setChecked(false);
}
...
mSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences pref3 = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
if (mSwitch1.isChecked()) {
String Swe1 = "12";
Editor editSwe1 = pref3.edit();
editSwe1.putString(APP_PREFERENCES_SWITCH1, Swe1);
editSwe1.apply();
Toast.makeText(getApplicationContext(), "SET ON1", Toast.LENGTH_SHORT).show();
} else {
String Swe2 = "1";
Editor editSwe2 = pref3.edit();
editSwe2.putString(APP_PREFERENCES_SWITCH1, Swe2);
editSwe2.apply();
Toast.makeText(getApplicationContext(), "SET OFF1", Toast.LENGTH_SHORT).show();
}
}
});
mSwitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences pref4 = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
if (mSwitch2.isChecked()) {
String Swe3 = "12";
Editor editSwe3 = pref4.edit();
editSwe3.putString(APP_PREFERENCES_SWITCH2, Swe3);
editSwe3.apply();
Toast.makeText(getApplicationContext(), "SET ON2", Toast.LENGTH_SHORT).show();
} else {
String Swe4 = "1";
Editor editSwe4 = pref4.edit();
editSwe4.putString(APP_PREFERENCES_SWITCH2, Swe4);
editSwe4.apply();
Toast.makeText(getApplicationContext(), "SET OFF2", Toast.LENGTH_SHORT).show();
}
}
});
...
}
I'm currently working on an app where I want to add a button to toggle visibility on a certain ImageView. Beforehand, there are 3 GraphViews on my UI, and when visibility is toggled, ImageView will overlap the two graphs below. However, when I run the app, the 'app has stopped'
The btndiag button causes the error
public class MainActivity extends Activity {
private static final String TAG = "TUP-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private ConnectedThread mConnectedThread;
private boolean mIsUserInitiatedDisconnect = false;
// All controls here
private TextView mTxtReceive;
private Button mBtnDisconnect;
private Button mBtnStart;
private GraphView1 graphView1;
private GraphView2 graphView2;
private GraphView3 graphView3;
private StringBuilder recDataString = new StringBuilder();
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
private Button btnDiag;
private ImageView imgDiag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
graphView1 = (GraphView1) findViewById(R.id.graph_view1);
graphView2 = (GraphView2) findViewById(R.id.graph_view2);
graphView3 = (GraphView3) findViewById(R.id.graph_view3);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.d(TAG, "Ready");
mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
mBtnStart = (Button) findViewById(R.id.btnStart);
btnDiag = (Button)findViewById(R.id.btDiag);
mTxtReceive = (TextView)findViewById(R.id.textView);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnDisconnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mIsUserInitiatedDisconnect = true;
new DisConnectBT().execute();
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mConnectedThread.write("B");
}
});
mBtnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mConnectedThread.write("A");
}
});
btnDiag.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnDiag.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
imgDiag.setVisibility(View.VISIBLE);
}
});
}
});
}
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[512];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
mTxtReceive.post(new Runnable() {
#Override
public void run() {
String[] items = strInput.split("\\*");
for (String item : items )
{
if(item.length() == 12){
try{
//get sensor value from string between indices 1-5;
final int value = Integer.parseInt(item.substring(1, 3));
ImageView imageView = (ImageView) findViewById(R.id.edg_image);
if ( value <= 77) {
imageView.setImageResource(R.drawable.left);
}
else if ( value <= 80 && value >=78) {
imageView.setImageResource(R.drawable.center);
}
else if ( value >= 81 ){
imageView.setImageResource(R.drawable.right);
}
System.out.println("acc = " + value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
//get sensor value from string between indices 1-5;
final int value = Integer.parseInt(item.substring(3, 6));
System.out.println("ecg = "+ value);
graphView1.plotProcedure1(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
final int value = Integer.parseInt(item.substring(6, 9));
System.out.println("eda = "+ value);
graphView2.plotProcedure2(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
final int value = Integer.parseInt(item.substring(9, 12));
System.out.println("emg = "+ value);
graphView3.plotProcedure3(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
}
}
}
});
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
};
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket mBTSocket) {
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpOut = mBTSocket.getOutputStream();
} catch (IOException e) { }
mmOutStream = tmpOut;
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
logcat error
01-04 07:04:08.467 22700-22700/com.tup.tup E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tup.tup, PID: 22700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tup.tup/com.tup.tup.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2273)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.tup.tup.MainActivity.onCreate(MainActivity.java:82)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2188)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2273)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
Actually, I have converted WordPress site into an android app. In WordPress site there is some add available on the site which is created in javascript, and when data is fetched into the android app as a webview, there is some space is shown in place of that ads. I want to remove it or want to add AdMob ads there. How could it be possible? Please help me regarding this.
Thanks in advance.
My Code is
public class PostViewActivity extends AppCompatActivity {
private static final String TAG = PostViewActivity.class.getSimpleName();
public static final String TAG_SEL_POST_ID = "post_id";
public static final String TAG_SEL_POST_TITLE = "post_title";
public static final String TAG_SEL_POST_IMAGE = "post_image";
private String commentsNumber;
private String selectedPostID, selectedPostTitle;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private ImageButton fab;
private TextView post_name;
private TextView post_content;
private TextView post_author;
private ImageView postImageView;
private String post_image, objURL, objTitle;
private Integer commentsCount;
private TextView timestamp;
private NetworkImageView profilePic;
private ShareActionProvider mShareActionProvider;
private WebView post_contentHTML;
private Boolean user_can_comment = true;
private Spanned spannedContent;
private ProgressBar pbLoader;
private LinearLayout llayout;
private Integer OC = 0;
//----------Exit and Banner Ad----------------------------------
private InterstitialAd interstitial;
private AdView mAdView;
private Toolbar toolbar;
public static void navigate(AppCompatActivity activity, View transitionImage, Post post) {
Intent intent = new Intent(activity, PostViewActivity.class);
intent.putExtra(TAG_SEL_POST_IMAGE, post.getImge());
intent.putExtra(TAG_SEL_POST_TITLE, post.getName());
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionImage, TAG_SEL_POST_IMAGE);
ActivityCompat.startActivity(activity, intent, options.toBundle());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString(TAG_SEL_POST_ID, selectedPostID);
savedInstanceState.putString(TAG_SEL_POST_TITLE, selectedPostTitle);
Log.d(TAG, savedInstanceState.toString());
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "Restored: " + savedInstanceState.toString());
selectedPostID = (String) savedInstanceState.getString(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getString(TAG_SEL_POST_TITLE);
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
//Get a Tracker (should auto-report)
if (Const.Analytics_ACTIVE) {
AnalyticsUtil.sendScreenName(this, TAG);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initActivityTransitions();
setContentView(R.layout.activity_post_view);
//Forcing RTL Layout, If Supports and Enabled from Const file
Utils.forceRTLIfSupported(this);
ActivityCompat.postponeEnterTransition(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//Get and Set the Post Title
String itemTitle = getIntent().getStringExtra(TAG_SEL_POST_TITLE);
setTitle(Html.fromHtml(itemTitle));
if (savedInstanceState == null) {
if (getIntent().getExtras() == null) {
selectedPostID = null;
selectedPostTitle = "Unknown Error";
} else {
selectedPostID = getIntent().getExtras().getString(TAG_SEL_POST_ID);
selectedPostTitle = getIntent().getExtras().getString(TAG_SEL_POST_TITLE);
}
} else {
Log.d(TAG, "Resume: " + savedInstanceState.toString());
selectedPostID = (String) savedInstanceState.getString(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getString(TAG_SEL_POST_TITLE);
/*selectedPostID = (String) savedInstanceState.getSerializable(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getSerializable(TAG_SEL_POST_TITLE);*/
}
//Setting up Fields Display
fab = (ImageButton) findViewById(R.id.fab);
post_name = (TextView) findViewById(R.id.title);
timestamp = (TextView) findViewById(R.id.timestamp);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/GenR102.ttf");
post_name.setTypeface(font);
float density = getResources().getDisplayMetrics().density;
int leftPadding = (int) (20 * density);
Configuration config = getResources().getConfiguration();
if (ViewCompat.getLayoutDirection(post_name) == ViewCompat.LAYOUT_DIRECTION_RTL) {
//post_name.setPadding(leftPadding,R.dimen.spacing_large,0,0);
post_name.setPadding(leftPadding, 0, 0, 0);
} else {
post_name.setPadding(0, 0, leftPadding, 0);
}
post_content = (TextView) findViewById(R.id.description);
post_contentHTML = (WebView) findViewById(R.id.descriptionHTML);
if (!Const.ShowPostAsWebView) {
post_content.setMovementMethod(LinkMovementMethod.getInstance());
Typeface font_postcontent = Typeface.createFromAsset(getAssets(), "fonts/OSRegular.ttf");
post_content.setTypeface(font_postcontent);
} else {
post_contentHTML.setVisibility(View.VISIBLE);
WebSettings webSettings = post_contentHTML.getSettings();
post_contentHTML.getSettings().setJavaScriptEnabled(true);
post_contentHTML.getSettings().getJavaScriptEnabled();
post_contentHTML.addJavascriptInterface(this, "asiannews");
post_contentHTML.getSettings().setAllowContentAccess(true);
post_contentHTML.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
post_contentHTML.getSettings().setLoadsImagesAutomatically(true);
post_contentHTML.getSettings().setDefaultTextEncodingName("utf-8");
post_contentHTML.getSettings().setUseWideViewPort(true);
post_contentHTML.getSettings().setLoadWithOverviewMode(true);
post_contentHTML.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
post_contentHTML.setWebChromeClient(new WebChromeClient());
post_contentHTML.addJavascriptInterface(this, "AsianNews");
post_contentHTML.loadUrl("javascript:Android.getIds(Ids);");
post_contentHTML.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//post_contentHTML.loadDataWithBaseURL("http://www.asiannews.co.in/bp4a-api/v1/post/_STORY_ID_/", myString, "text/html", "UTF-8", null);
}
post_author = (TextView) findViewById(R.id.post_author);
postImageView = (ImageView) findViewById(R.id.image);
profilePic = (NetworkImageView) findViewById(R.id.profilePic);
//Setting up Post Image and Toolbar Activity
//final ImageView image = (ImageView) findViewById(R.id.image);
/*ViewCompat.setTransitionName(postImageView, TAG_SEL_POST_IMAGE);
Bitmap bitmap = ((BitmapDrawable) postImageView.getDrawable()).getBitmap();
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});*/
//Setting Up Post Admob Banner
////Standard Banner
mAdView = (AdView) findViewById(R.id.adView);
if (Const.ADMOBService_ACTIVE) {
//----------Exit Ad----------------------------------
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.unit_id_interstitial));
AdRequest adRequestInterstitial = new AdRequest.Builder().addTestDevice(Const.ADMOB_DEVICE_ID).build();
interstitial.loadAd(adRequestInterstitial);
//----------Exit Ad----------------------------------
AdRequest adRequest = new AdRequest.Builder().addTestDevice(Const.ADMOB_DEVICE_ID).build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
});
} else {
mAdView.setVisibility(View.GONE);
}
getPost();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initActivityTransitions() {
if (Utils.isLollipop()) {
Slide transition = new Slide();
transition.excludeTarget(android.R.id.statusBarBackground, true);
getWindow().setEnterTransition(transition);
getWindow().setReturnTransition(transition);
}
}
private void applyPalette(Palette palette, ImageView image) {
int primaryDark = getResources().getColor(R.color.primary_dark);
int primary = getResources().getColor(R.color.primary);
toolbar.setBackgroundColor(primary);
Utils.setStatusBarcolor(getWindow(), primaryDark);
initScrollFade(image);
ActivityCompat.startPostponedEnterTransition(this);
}
private void initScrollFade(final ImageView image) {
final View scrollView = findViewById(R.id.scroll);
setComponentsStatus(scrollView, image);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
setComponentsStatus(scrollView, image);
}
});
}
private void setComponentsStatus(View scrollView, ImageView image) {
int scrollY = scrollView.getScrollY();
image.setTranslationY(-scrollY / 2);
ColorDrawable background = (ColorDrawable) toolbar.getBackground();
int padding = scrollView.getPaddingTop();
double alpha = (1 - (((double) padding - (double) scrollY) / (double) padding)) * 255.0;
alpha = alpha < 0 ? 0 : alpha;
alpha = alpha > 255 ? 255 : alpha;
background.setAlpha((int) alpha);
float scrollRatio = (float) (alpha / 255f);
int titleColor = getAlphaColor(Color.WHITE, scrollRatio);
toolbar.setTitleTextColor(titleColor);
toolbar.setSubtitleTextColor(titleColor);
}
private int getAlphaColor(int color, float scrollRatio) {
return Color.argb((int) (scrollRatio * 255f), Color.red(color), Color.green(color), Color.blue(color));
}
/**
* It seems that the ActionBar view is reused between activities. Changes need to be reverted,
* or the ActionBar will be transparent when we go back to Main Activity
*/
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void restablishActionBar() {
if (Utils.isLollipop()) {
getWindow().getReturnTransition().addListener(new TransitionAdapter() {
#Override
public void onTransitionEnd(Transition transition) {
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setSubtitleTextColor(Color.WHITE);
toolbar.getBackground().setAlpha(255);
}
});
}
}
#Override
public void onBackPressed() {
restablishActionBar();
if (Const.ADMOBService_ACTIVE) {
displayInterstitial();
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
restablishActionBar();
}
return super.onOptionsItemSelected(item);
}
private void getPost() {
//Requesting The Story
String url = null;
url = Const.URL_STORY_PAGE.replace("_STORY_ID_", selectedPostID.replace("P", ""));
//Log.i(TAG, "Taging: " + url);
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.i(TAG, "Taging: " + response.toString());
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
if (response.has("error")) {
String error = response.getString("error");
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
} else {
parseJsonFeed(response);
}
} catch (JSONException es) {
es.printStackTrace();
Toast.makeText(getApplicationContext(), es.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/** Passing some request headers **/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("ApiKey", Const.AuthenticationKey);
return headers;
}
};
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
private void parseJsonFeed(JSONObject feedObj) {
try {
objTitle = feedObj.getString("name");
post_name.setText(Html.fromHtml(objTitle));
commentsCount = feedObj.getInt("comments");
if (feedObj.getString("can_comment") == "no") {
user_can_comment = false;
}
if (!Const.ShowPostAsWebView) {
post_contentHTML.setVisibility(View.GONE);
URLImageParser p = new URLImageParser(this, post_content);
spannedContent = Html.fromHtml(feedObj.getString("story_content"), p, null);
post_content.setText(trimTrailingWhitespace(spannedContent));
} else {
post_content.setVisibility(View.GONE);
post_contentHTML.setVisibility(View.VISIBLE);
String post_con = "<!DOCTYPE html>" +
"<html lang=\"en\">" +
" <head>" +
" <meta charset=\"utf-8\">" +
" </head>" +
" <body>" +
" #content# " +
" </body>" +
"</html>";
try {
InputStream in_s = getResources().openRawResource(R.raw.post_format);
byte[] b = new byte[in_s.available()];
in_s.read(b);
post_con = new String(b);
} catch (Exception e) {
e.printStackTrace();
}
post_con = post_con.replace("#title#", feedObj.getString("name"));
post_con = post_con.replace("#content#", feedObj.getString("story_content"));
//post_contentHTML.loadData(post_con, "text/html; charset=utf-8", "utf-8");
post_contentHTML.loadDataWithBaseURL(null,
post_con,
"text/html",
"UTF-8",
null);
}
if (feedObj.getString("story_content").length() <= 0) {
post_content.setVisibility(View.GONE);
post_contentHTML.setVisibility(View.GONE);
}
post_author.setText(feedObj.getString("author"));
getSupportActionBar().setSubtitle("By " + feedObj.getString("author"));
post_image = feedObj.getString("image");
objURL = feedObj.getString("url");
if (Const.Analytics_ACTIVE) {
AnalyticsUtil.sendEvent(this, "Post View", objTitle, objURL);
}
//Setting Up a Share Intent
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, objTitle + " - " + objURL);
startActivityForResult(Intent.createChooser(shareIntent, "Share via"), 300);
}
});
//setShareIntent(shareIntent);
//Comment Button Click
Button viewComments = (Button) findViewById(R.id.btnViewComments);
commentsNumber = Utils.formatNumber(commentsCount);
viewComments.setText(String.format(getString(R.string.comments_button), commentsNumber));
viewComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(PostViewActivity.this, PostComments.class);
i.putExtra("post_id", selectedPostID.replace("P", ""));
i.putExtra("post_title", getIntent().getStringExtra(TAG_SEL_POST_TITLE));
i.putExtra("commentsCount", commentsCount);
i.putExtra("user_can_comment", user_can_comment);
startActivityForResult(i, 1000);
}
});
//Button Click
Button viewWeb = (Button) findViewById(R.id.btnViewWeb);
if (Const.ShowPostOnExternalBrowser) {
viewWeb.setVisibility(View.VISIBLE);
viewWeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUrl(objURL);
}
});
}
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(feedObj.getString("timeStamp")),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
profilePic.setImageUrl(feedObj.getString("profilePic"), imageLoader);
loadConfig();
//pbLoader.setVisibility(View.GONE);
//llayout.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
private void loadConfig() {
if (post_image != null) {
ViewCompat.setTransitionName(postImageView, TAG_SEL_POST_IMAGE);
Picasso.with(this).load(post_image).into(postImageView, new Callback() {
#Override
public void onSuccess() {
Bitmap bitmap = ((BitmapDrawable) postImageView.getDrawable()).getBitmap();
new Palette.Builder(bitmap).generate(new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});
/*Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});*/
}
#Override
public void onError() {
}
});
} else {
postImageView.setVisibility(View.GONE);
}
}
#JavascriptInterface
public void resize(final float height) {
PostViewActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Trigger: " + height + " // " + (int) (height * getResources().getDisplayMetrics().density), Toast.LENGTH_LONG).show();
//post_contentHTML.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) (height * getResources().getDisplayMetrics().density)));
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
post_contentHTML.loadUrl("javascript:asiannews.resize(document.body.getBoundingClientRect().height)");
}
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null)
return "";
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
public class URLImageParser implements Html.ImageGetter {
#SuppressWarnings("deprecation")
class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if (drawable != null) {
drawable.draw(canvas);
}
}
}
class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
#Override
protected Drawable doInBackground(String... params) {
String source = params[0];
Uri uri = Uri.parse(source);
Bitmap bitmap = null;
try {
Picasso pic = new Picasso.Builder(mContext).build();
bitmap = pic.load(uri).get();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return new BitmapDrawable(mContext.getResources(), bitmap);
}
#Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.mView.invalidate();
}
}
private final Context mContext;
private final View mView;
public URLImageParser(Context context, View view) {
mContext = context;
mView = view;
}
#Override
public Drawable getDrawable(String source) {
Uri uri = Uri.parse(source);
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask task = new ImageGetterAsyncTask(urlDrawable);
task.execute(source);
return urlDrawable;
}
}
#Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(PostViewActivity.this).reportActivityStart(this);
}
#Override
protected void onStop() {
super.onStop();
GoogleAnalytics.getInstance(PostViewActivity.this).reportActivityStop(this);
}
}
I combined the functionality of webbrowsercontrol ObjectForScripting (source) to call C# functions from javascript and a proxy for that webbrowser control (source).
Each function on its own works. But when i combine them, the calls from javascript doesn't work anymore. Errormessage is
Object doesn't support property or method "Test"
Sourcecode for an example is on the bottom.
You can try both functionality when commenting and uncommenting this block in Form1_Load
// Comment this block for Callback working
object obj = webBrowser1.ActiveXInstance;
IOleObject oc = obj as IOleObject;
oc.SetClientSite(Proxy as IOleClientSite);
I guess the problem is the function QueryService from the interface IServiceProvider. I tried to pin it down with the GUID from Scriptmanager but found no solution.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ProxyTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
proxy Proxy = new proxy();
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("about:blank");
// Comment this block for Callback working
object obj = webBrowser1.ActiveXInstance;
IOleObject oc = obj as IOleObject;
oc.SetClientSite(Proxy as IOleClientSite);
//Proxy settings are not necessary
Proxy._currentUsername = ""; // Username
Proxy._currentPassword = ""; // Password
Proxy.SetProxyServer(""); //IP:PORT
webBrowser1.ObjectForScripting = new Scriptmanager();
Application.DoEvents();
webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"onclick=\"window.external.Test('called from script code')\">" +
"call client code from script code</button>" +
"</body></html>";
}
}
[ComVisible(true)]
public class Scriptmanager
{
public void Test(string text)
{
MessageBox.Show(text);
}
}
public class proxy : IOleClientSite, IServiceProvider, IAuthenticate
{
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption,
IntPtr lpBuffer, int lpdwBufferLength);
private Guid IID_IAuthenticate = new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
private const int INET_E_DEFAULT_ACTION = unchecked((int)0x800C0011);
private const int S_OK = unchecked((int)0x00000000);
private const int INTERNET_OPTION_PROXY = 38;
private const int INTERNET_OPEN_TYPE_DIRECT = 1;
private const int INTERNET_OPEN_TYPE_PROXY = 3;
internal string _currentUsername;
internal string _currentPassword;
internal void SetProxyServer(string proxy)
{
//Create structure
INTERNET_PROXY_INFO proxyInfo = new INTERNET_PROXY_INFO();
if (proxy == null)
{
proxyInfo.dwAccessType = INTERNET_OPEN_TYPE_DIRECT;
}
else
{
proxyInfo.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
proxyInfo.proxy = Marshal.StringToHGlobalAnsi(proxy);
proxyInfo.proxyBypass = Marshal.StringToHGlobalAnsi("local");
}
// Allocate memory
IntPtr proxyInfoPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(proxyInfo));
// Convert structure to IntPtr
Marshal.StructureToPtr(proxyInfo, proxyInfoPtr, true);
bool returnValue = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY,
proxyInfoPtr, Marshal.SizeOf(proxyInfo));
}
#region IOleClientSite Members
public void SaveObject()
{
// TODO: Add Form1.SaveObject implementation
}
public void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk)
{
// TODO: Add Form1.GetMoniker implementation
}
public void GetContainer(object ppContainer)
{
ppContainer = this;
}
public void ShowObject()
{
// TODO: Add Form1.ShowObject implementation
}
public void OnShowWindow(bool fShow)
{
// TODO: Add Form1.OnShowWindow implementation
}
public void RequestNewObjectLayout()
{
// TODO: Add Form1.RequestNewObjectLayout implementation
}
#endregion
#region IServiceProvider Members
public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)
{
int nRet = guidService.CompareTo(IID_IAuthenticate);
if (nRet == 0)
{
nRet = riid.CompareTo(IID_IAuthenticate);
if (nRet == 0)
{
ppvObject = Marshal.GetComInterfaceForObject(this, typeof(IAuthenticate));
return S_OK;
}
}
ppvObject = new IntPtr();
return INET_E_DEFAULT_ACTION;
}
#endregion
#region IAuthenticate Members
public int Authenticate(ref IntPtr phwnd, ref IntPtr pszUsername, ref IntPtr pszPassword)
{
IntPtr sUser = Marshal.StringToCoTaskMemAuto(_currentUsername);
IntPtr sPassword = Marshal.StringToCoTaskMemAuto(_currentPassword);
pszUsername = sUser;
pszPassword = sPassword;
return S_OK;
}
#endregion
}
public struct INTERNET_PROXY_INFO
{
public int dwAccessType;
public IntPtr proxy;
public IntPtr proxyBypass;
}
#region COM Interfaces
[ComImport, Guid("00000112-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleObject
{
void SetClientSite(IOleClientSite pClientSite);
void GetClientSite(IOleClientSite ppClientSite);
void SetHostNames(object szContainerApp, object szContainerObj);
void Close(uint dwSaveOption);
void SetMoniker(uint dwWhichMoniker, object pmk);
void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
void InitFromData(IDataObject pDataObject, bool
fCreation, uint dwReserved);
void GetClipboardData(uint dwReserved, IDataObject ppDataObject);
void DoVerb(uint iVerb, uint lpmsg, object pActiveSite,
uint lindex, uint hwndParent, uint lprcPosRect);
void EnumVerbs(object ppEnumOleVerb);
void Update();
void IsUpToDate();
void GetUserClassID(uint pClsid);
void GetUserType(uint dwFormOfType, uint pszUserType);
void SetExtent(uint dwDrawAspect, uint psizel);
void GetExtent(uint dwDrawAspect, uint psizel);
void Advise(object pAdvSink, uint pdwConnection);
void Unadvise(uint dwConnection);
void EnumAdvise(object ppenumAdvise);
void GetMiscStatus(uint dwAspect, uint pdwStatus);
void SetColorScheme(object pLogpal);
}
[ComImport, Guid("00000118-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleClientSite
{
void SaveObject();
void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
void GetContainer(object ppContainer);
void ShowObject();
void OnShowWindow(bool fShow);
void RequestNewObjectLayout();
}
[ComImport, GuidAttribute("6d5140c1-7436-11ce-8034-00aa006009fa"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)]
public interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject);
}
[ComImport, GuidAttribute("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)]
public interface IAuthenticate
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int Authenticate(ref IntPtr phwnd, ref IntPtr pszUsername, ref IntPtr pszPassword);
}
#endregion
}
Update 01.11.2016
This tip from Sheng Jiang 蒋晟 was really good. I almost have a working example. The messagebox is shown after the click. Sadly afterwards comes a InvalidVariant exception. Anybody has a guess what's wrong. I'm stuck again. Here is the current code.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ProxyTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
proxy Proxy = new proxy();
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("about:blank");
// Comment this block for Callback working
object obj = webBrowser1.ActiveXInstance;
IOleObject oc = obj as IOleObject;
oc.SetClientSite(Proxy as IOleClientSite);
//Proxy settings are not necessary
Proxy._currentUsername = ""; // Username
Proxy._currentPassword = ""; // Password
Proxy.SetProxyServer(""); //IP:PORT
webBrowser1.ObjectForScripting = new Scriptmanager();
Application.DoEvents();
webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"onclick=\"window.external.Test('called from script code')\">" +
"call client code from script code</button>" +
"</body></html>";
}
}
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IScriptmanager
{
void Test(string text);
}
[ComVisible(true)]
public class Scriptmanager : IScriptmanager
{
public void Test(string text)
{
MessageBox.Show(text);
}
}
public class proxy : IOleClientSite, IServiceProvider, IAuthenticate, IDocHostUIHandler
{
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption,
IntPtr lpBuffer, int lpdwBufferLength);
private Guid IID_IAuthenticate = new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
private const int INET_E_DEFAULT_ACTION = unchecked((int)0x800C0011);
private const int S_OK = unchecked((int)0x00000000);
private const int INTERNET_OPTION_PROXY = 38;
private const int INTERNET_OPEN_TYPE_DIRECT = 1;
private const int INTERNET_OPEN_TYPE_PROXY = 3;
internal string _currentUsername;
internal string _currentPassword;
IDocHostUIHandler _baseIDocHostUIHandler;
internal void SetProxyServer(string proxy)
{
//Create structure
INTERNET_PROXY_INFO proxyInfo = new INTERNET_PROXY_INFO();
if (proxy == null)
{
proxyInfo.dwAccessType = INTERNET_OPEN_TYPE_DIRECT;
}
else
{
proxyInfo.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
proxyInfo.proxy = Marshal.StringToHGlobalAnsi(proxy);
proxyInfo.proxyBypass = Marshal.StringToHGlobalAnsi("local");
}
// Allocate memory
IntPtr proxyInfoPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(proxyInfo));
// Convert structure to IntPtr
Marshal.StructureToPtr(proxyInfo, proxyInfoPtr, true);
bool returnValue = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY,
proxyInfoPtr, Marshal.SizeOf(proxyInfo));
}
#region IOleClientSite Members
public void SaveObject()
{
// TODO: Add Form1.SaveObject implementation
}
public void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk)
{
// TODO: Add Form1.GetMoniker implementation
}
public void GetContainer(object ppContainer)
{
ppContainer = this;
}
public void ShowObject()
{
// TODO: Add Form1.ShowObject implementation
}
public void OnShowWindow(bool fShow)
{
// TODO: Add Form1.OnShowWindow implementation
}
public void RequestNewObjectLayout()
{
// TODO: Add Form1.RequestNewObjectLayout implementation
}
#endregion
#region IServiceProvider Members
public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)
{
int nRet = guidService.CompareTo(IID_IAuthenticate);
if (nRet == 0)
{
nRet = riid.CompareTo(IID_IAuthenticate);
if (nRet == 0)
{
ppvObject = Marshal.GetComInterfaceForObject(this, typeof(IAuthenticate));
return S_OK;
}
}
ppvObject = new IntPtr();
return INET_E_DEFAULT_ACTION;
}
#endregion
#region IAuthenticate Members
public int Authenticate(ref IntPtr phwnd, ref IntPtr pszUsername, ref IntPtr pszPassword)
{
IntPtr sUser = Marshal.StringToCoTaskMemAuto(_currentUsername);
IntPtr sPassword = Marshal.StringToCoTaskMemAuto(_currentPassword);
pszUsername = sUser;
pszPassword = sPassword;
return S_OK;
}
#endregion
#region IDocHostUIHandler Members
public uint ShowContextMenu(uint dwID, ref tagPOINT ppt, [MarshalAs(UnmanagedType.IUnknown)] object pcmdtReserved, [MarshalAs(UnmanagedType.IDispatch)] object pdispReserved)
{
const int MenuNotHandled = 1;
return MenuNotHandled;
}
public void GetHostInfo(ref DOCHOSTUIINFO pInfo)
{
// turn three flags on
pInfo.dwFlags |= (uint)(DOCHOSTUIFLAG.DOCHOSTUIFLAG_SCROLL_NO |
DOCHOSTUIFLAG.DOCHOSTUIFLAG_NO3DBORDER |
DOCHOSTUIFLAG.DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE);
}
public void ShowUI(uint dwID, ref object pActiveObject, ref object pCommandTarget, ref object pFrame, ref object pDoc)
{
//throw new NotImplementedException();
}
public void HideUI()
{
// throw new NotImplementedException();
}
public void UpdateUI()
{
// throw new NotImplementedException();
}
public void EnableModeless(int fEnable)
{
//throw new NotImplementedException();
}
public void OnDocWindowActivate(int fActivate)
{
//throw new NotImplementedException();
}
public void OnFrameWindowActivate(int fActivate)
{
//throw new NotImplementedException();
}
public void ResizeBorder(ref tagRECT prcBorder, int pUIWindow, int fFrameWindow)
{
//throw new NotImplementedException();
}
public uint TranslateAccelerator(ref tagMSG lpMsg, ref Guid pguidCmdGroup, uint nCmdID)
{
const int KillAccelerator = 0;
const int AllowAccelerator = 1;
const int WM_KEYDOWN = 0x0100;
if (lpMsg.message != WM_KEYDOWN)
// allow message
return AllowAccelerator;
if ((Control.ModifierKeys & Keys.Control) != Keys.Control)
return AllowAccelerator;
// disable the Ctrl-N and Ctrl-P accelerators
lpMsg.wParam &= 0xFF; // get the virtual keycode
if ((lpMsg.wParam == 'N') || ((lpMsg.wParam == 'P')))
return KillAccelerator;
// allow everything else
return AllowAccelerator;
}
public void GetOptionKeyPath([MarshalAs(UnmanagedType.BStr)] ref string pchKey, uint dw)
{
// throw new NotImplementedException();
}
public uint GetDropTarget(int pDropTarget, ref int ppDropTarget)
{
const int S_OK = 0;
return S_OK;
}
//public object GetDropTarget(ref object pDropTarget)
//{
// return pDropTarget;
//}
public void GetExternal([MarshalAs(UnmanagedType.IDispatch)] out object ppDispatch)
{
ppDispatch = new Scriptmanager();
}
public uint TranslateUrl(uint dwTranslate, [MarshalAs(UnmanagedType.BStr)] string pchURLIn, [MarshalAs(UnmanagedType.BStr)] ref string ppchURLOut)
{
const int NotTranslated = 1;
return NotTranslated;
}
public IDataObject FilterDataObject(IDataObject pDO)
{
return null;
}
#endregion
}
public struct INTERNET_PROXY_INFO
{
public int dwAccessType;
public IntPtr proxy;
public IntPtr proxyBypass;
}
public struct tagRECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct tagPOINT
{
public int x;
public int y;
}
public enum DOCHOSTUITYPE
{
DOCHOSTUITYPE_BROWSE = 0,
DOCHOSTUITYPE_AUTHOR = 1
}
public enum DOCHOSTUIDBLCLK
{
DOCHOSTUIDBLCLK_DEFAULT = 0,
DOCHOSTUIDBLCLK_SHOWPROPERTIES = 1,
DOCHOSTUIDBLCLK_SHOWCODE = 2
}
[Flags()]
public enum DOCHOSTUIFLAG
{
DOCHOSTUIFLAG_DIALOG = 0x00000001,
DOCHOSTUIFLAG_DISABLE_HELP_MENU = 0x00000002,
DOCHOSTUIFLAG_NO3DBORDER = 0x00000004,
DOCHOSTUIFLAG_SCROLL_NO = 0x00000008,
DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE = 0x00000010,
DOCHOSTUIFLAG_OPENNEWWIN = 0x00000020,
DOCHOSTUIFLAG_DISABLE_OFFSCREEN = 0x00000040,
DOCHOSTUIFLAG_FLAT_SCROLLBAR = 0x00000080,
DOCHOSTUIFLAG_DIV_BLOCKDEFAULT = 0x00000100,
DOCHOSTUIFLAG_ACTIVATE_CLIENTHIT_ONLY = 0x00000200,
DOCHOSTUIFLAG_OVERRIDEBEHAVIORFACTORY = 0x00000400,
DOCHOSTUIFLAG_CODEPAGELINKEDFONTS = 0x00000800,
DOCHOSTUIFLAG_URL_ENCODING_DISABLE_UTF8 = 0x00001000,
DOCHOSTUIFLAG_URL_ENCODING_ENABLE_UTF8 = 0x00002000,
DOCHOSTUIFLAG_ENABLE_FORMS_AUTOCOMPLETE = 0x00004000,
DOCHOSTUIFLAG_ENABLE_INPLACE_NAVIGATION = 0x00010000,
DOCHOSTUIFLAG_IME_ENABLE_RECONVERSION = 0x00020000,
DOCHOSTUIFLAG_THEME = 0x00040000,
DOCHOSTUIFLAG_NOTHEME = 0x00080000,
DOCHOSTUIFLAG_NOPICS = 0x00100000,
DOCHOSTUIFLAG_NO3DOUTERBORDER = 0x00200000,
DOCHOSTUIFLAG_DISABLE_EDIT_NS_FIXUP = 0x400000,
DOCHOSTUIFLAG_LOCAL_MACHINE_ACCESS_CHECK = 0x800000,
DOCHOSTUIFLAG_DISABLE_UNTRUSTEDPROTOCOL = 0x1000000
}
[StructLayout(LayoutKind.Sequential)]
public struct DOCHOSTUIINFO
{
public uint cbSize;
public uint dwFlags;
public uint dwDoubleClick;
[MarshalAs(UnmanagedType.BStr)]
public string pchHostCss;
[MarshalAs(UnmanagedType.BStr)]
public string pchHostNS;
}
[StructLayout(LayoutKind.Sequential)]
public struct tagMSG
{
public IntPtr hwnd;
public uint message;
public uint wParam;
public int lParam;
public uint time;
public tagPOINT pt;
}
#region COM Interfaces
[ComImport, Guid("00000112-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleObject
{
void SetClientSite(IOleClientSite pClientSite);
void GetClientSite(IOleClientSite ppClientSite);
void SetHostNames(object szContainerApp, object szContainerObj);
void Close(uint dwSaveOption);
void SetMoniker(uint dwWhichMoniker, object pmk);
void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
void InitFromData(IDataObject pDataObject, bool
fCreation, uint dwReserved);
void GetClipboardData(uint dwReserved, IDataObject ppDataObject);
void DoVerb(uint iVerb, uint lpmsg, object pActiveSite,
uint lindex, uint hwndParent, uint lprcPosRect);
void EnumVerbs(object ppEnumOleVerb);
void Update();
void IsUpToDate();
void GetUserClassID(uint pClsid);
void GetUserType(uint dwFormOfType, uint pszUserType);
void SetExtent(uint dwDrawAspect, uint psizel);
void GetExtent(uint dwDrawAspect, uint psizel);
void Advise(object pAdvSink, uint pdwConnection);
void Unadvise(uint dwConnection);
void EnumAdvise(object ppenumAdvise);
void GetMiscStatus(uint dwAspect, uint pdwStatus);
void SetColorScheme(object pLogpal);
}
[ComImport, Guid("00000118-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleClientSite
{
void SaveObject();
void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
void GetContainer(object ppContainer);
void ShowObject();
void OnShowWindow(bool fShow);
void RequestNewObjectLayout();
}
[ComImport, GuidAttribute("6d5140c1-7436-11ce-8034-00aa006009fa"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)]
public interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject);
}
[ComImport, GuidAttribute("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)]
public interface IAuthenticate
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int Authenticate(ref IntPtr phwnd, ref IntPtr pszUsername, ref IntPtr pszPassword);
}
[ComImport()]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[GuidAttribute("bd3f23c0-d43e-11cf-893b-00aa00bdce1a")]
public interface IDocHostUIHandler
{
[PreserveSig]
uint ShowContextMenu(
uint dwID,
ref tagPOINT ppt,
[MarshalAs(UnmanagedType.IUnknown)] object pcmdtReserved,
[MarshalAs(UnmanagedType.IDispatch)] object pdispReserved
);
void GetHostInfo(ref DOCHOSTUIINFO pInfo);
void ShowUI(uint dwID, ref object pActiveObject, ref object pCommandTarget, ref object pFrame, ref object pDoc);
void HideUI();
void UpdateUI();
void EnableModeless(int fEnable);
void OnDocWindowActivate(int fActivate);
void OnFrameWindowActivate(int fActivate);
void ResizeBorder(ref tagRECT prcBorder, int pUIWindow, int fFrameWindow);
[PreserveSig]
uint TranslateAccelerator(ref tagMSG lpMsg, ref Guid pguidCmdGroup, uint nCmdID);
void GetOptionKeyPath([MarshalAs(UnmanagedType.BStr)] ref string pchKey, uint dw);
uint GetDropTarget(int pDropTarget, ref int ppDropTarget);
//object GetDropTarget(ref object pDropTarget);
[PreserveSig]
void GetExternal([MarshalAs(UnmanagedType.IDispatch)] out object ppDispatch);
[PreserveSig]
uint TranslateUrl(
uint dwTranslate,
[MarshalAs(UnmanagedType.BStr)] string pchURLIn,
[MarshalAs(UnmanagedType.BStr)] ref string ppchURLOut
);
IDataObject FilterDataObject(IDataObject pDO);
}
#endregion
}
webBrowser1.ObjectForScripting has no effect since you are replacing the client site. The default client site in WinForms implements IDocHostUIHandler::GetExternal and returns the value of ObjectForScripting. You can do the same thing in your Proxy class.
I have a code that plays a sound, records audio (by clicking one button) and plays the file recorded (by clicking another button). I want to know how to modify it in order to record and play the sound when I click the first button so when I click the second button I can heard the recorded sound that I played first.
That means: I want to know how to start record and play my audio file in record folder, both of them, only by clicking a button.
This is my code just now:
public class MediaPlayerExample2Activity extends Activity {
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording(); }
else {
stopRecording(); } }
private void onPlay(boolean start) {
if (start) {
startPlaying(); }
else {
stopPlaying(); } }
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start(); }
catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
} } private void stopPlaying() {
mPlayer.release();
mPlayer = null; }
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
}
catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
} mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
}
else {
setText("Start recording");
}
mStartRecording = !mStartRecording; }
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
} }
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
}
else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
} };
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
} }
public MediaPlayerExample2Activity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.pru);
mPlayer.start();
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0)); setContentView(ll);
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0)); setContentView(ll); }
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
} }}
Thanks!! I hope you understand my question!!! ;)