after logging into an account in my webview application, it automatically exits the account 5 minutes after closing the application. Can anyone help with this? I need to solve this problem.
Hello, after logging into an account in my webview application, it automatically exits the account 5 minutes after closing the application. Can anyone help with this? I need to solve this problem
package com.igtr.webview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.KeyEvent;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void onBackPressed(){
if(websitem.canGoBack()){
websitem.goBack();
}else {
final Dialog exitDialog=new Dialog(MainActivity.this);
exitDialog.getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
exitDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
exitDialog.setCancelable(false);
exitDialog.setContentView(R.layout.cikis_diyalog);
Button evetBtn=exitDialog.findViewById(R.id.evetBtn);
Button hayirBtn=exitDialog.findViewById(R.id.hayirBtn);
evetBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
System.exit(0);
}
});
hayirBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
exitDialog.dismiss();
}
});
exitDialog.show();
}
}
private SwipeRefreshLayout swipeRefreshLayout;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
private Object ValueCallback;
#SuppressLint("SetJavaScriptEnabled")
WebView websitem;
Context context;
ImageView noconnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.sitem);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new com.panelimws.webview.FullScreenClient(MainActivity.this){
#Override
public void onHideCustomView() {
hideFullScreen(webView);
}
#Override
public Bitmap getDefaultVideoPoster() {
return videoBitmap();
}
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
showFullScreen(view,callback);
}
});
goster();
yukle();
noconnection = (ImageView) findViewById(R.id.noconnection);
if (!isConnected()){
noconnection.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "İnternet Bağlantısı Bulunamadı",Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(MainActivity.this, "Dünya'nın 1 Numaralı SMM Paneline Hoşgeldiniz!",Toast.LENGTH_SHORT).show();
}
}
public void goster(){
websitem=findViewById(R.id.sitem);
}
public void yukle(){
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
websitem.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
websitem.getSettings().setJavaScriptEnabled(true);
websitem.getSettings().setBuiltInZoomControls(true);
websitem.getSettings().setSupportZoom(true);
websitem.loadUrl("url");
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
websitem.reload();
}
});
websitem.setWebChromeClient(new WebChromeClient()
{
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
private static class xWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && websitem.canGoBack()) {
websitem.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean isConnected(){
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo()!=null && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
Here is my mainactivity code i waiting your help.
I tried but didn't work.
Related
I have been trying to do lock task mode or lock into my app without being able to access other apps with still being able to disable the feature. I have looked at tutorials and documentation but some methods were deprecated since they were made around 5 years ago (onActivityResult). I have tried to change to the new methods (registerForActivityResult) that I found, however when I launch my app and try to enable admin permission by tapping on the enable button, the admin permissions don't pop up, so I cannot check it. So, when I try to lock my phone from other apps nothing happens because I don't have admin permissions.My Code for MainActivity.class below:
package com.example.myapplication;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.myapplication.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.myapplication.helper.MqttHelper;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button lock, disable, enable;
private static final int RESULT_ENABLE = 11;
private DevicePolicyManager devicePolicyManager;
private ActivityManager activityManager;
private ComponentName componentName;
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
MqttHelper mqttHelper;
//ChartHelper mChart;
//LineChart chart;
TextView dataReceived;
private Button btnPublish;
// Allowlist two apps.
private static final String KIOSK_PACKAGE = "com.example.myapplication";
private static final String[] APP_PACKAGES = {KIOSK_PACKAGE};
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//setContentView(R.layout.activity_main);
devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
componentName = new ComponentName(this, Controller.class);
lock = (Button) findViewById(R.id.lock);
enable = (Button) findViewById(R.id.enable);
disable = (Button) findViewById(R.id.disable);
lock.setOnClickListener(this);
enable.setOnClickListener(this);
disable.setOnClickListener(this);
dataReceived = (TextView) findViewById(R.id.textview_first);
startMqtt();
}
#Override
protected void onResume() {
super.onResume();
boolean isActive = devicePolicyManager.isAdminActive(componentName);
}
#Override
public void onClick(View view) {
if (view == lock) {
boolean active = devicePolicyManager.isAdminActive(componentName);
if(active) {
devicePolicyManager.lockNow();
} else {
Toast.makeText(this, "You need to enable the Admin Device Features", Toast.LENGTH_SHORT).show();
}
} else if (view == enable) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"You Should Enable the app!");
//someActivityResultLauncher.launch(intent);
// Caller
mGetContent.launch(intent);
// Receiver
//startActivityForResult(intent, RESULT_ENABLE);
} else if (view == disable) {
devicePolicyManager.removeActiveAdmin(componentName);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
}
ActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// Here, no request code
Intent data = result.getData();
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode== Activity.RESULT_OK && requestCode == RESULT_ENABLE){
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
/*#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case RESULT_ENABLE:
if(resultCode== Activity.RESULT_OK ){
//btn_unblock.setText("Dissable");
//btn_block.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
// MQTT Code
private void startMqtt(){
mqttHelper = new MqttHelper(getApplicationContext());
mqttHelper.mqttAndroidClient.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean b, String s) {
Log.w("Debug","Connected");
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Debug",mqttMessage.toString());
dataReceived.setText(mqttMessage.toString());
//mChart.addEntry(Float.valueOf(mqttMessage.toString()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
}
I have fragment (FragmentUpload) containing several textviews and edittext. when user click on upload button (shown in image), user is sent to different fragment where user can chose from the options and the chosen string is displayed in appropriate textviews in Fragment Upload. My problem is when user click on different upload button to chose different string for different textview (from separate fragment), the code do not save the previous value. For instance, when user chooses artist from artist fragment, the textview displays the chosen artist. Now when user click on upload album button to choose album, the code only shows chosen album in textview associated with album but previously chosen string (artist string) is no longer available. please help me ( I am new to android and java)
package com.example.realsungjoen;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Handler;
import android.provider.OpenableColumns;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.Set;
public class FragmentUpload extends Fragment {
private static final int PICK_IMAGE_REQUEST = 1;
private final static int PICK_SONG_REQUEST = 2;
private Button mBtnChooseImg;
private Button mBtnUpload;
private Button mBtnChooseSong;
private Button cancelButton;
private ImageView addselectArtists;
private ImageView addSelectGenre;
private ImageView addSelectAlbum;
private ImageView addSelectLanguage;
private ImageView mImageView;
private EditText mEditTextFileName;
private TextView mSongFile;
private TextView selectedArtist;
private TextView selectedAlbum;
private TextView selectedGenre;
private TextView selectedLanguage;
private ProgressBar mProgressBar;
private Uri mImageUri;
private Uri uriImage;
private Uri mSongUri;
private StorageReference mStorageImageRef;
private DatabaseReference mDatabaseRef;
private DatabaseReference mDatabaseRefArtist;
private StorageReference mStorageSongRef;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View uploadViews = inflater.inflate(R.layout.fragment_upload, container,false);
mBtnChooseImg = uploadViews.findViewById(R.id.btn_chose_img);
mBtnChooseSong = uploadViews.findViewById(R.id.btn_choose_song);
mBtnUpload = uploadViews.findViewById(R.id.btn_upload);
cancelButton = uploadViews.findViewById(R.id.cancel_button);
mEditTextFileName = uploadViews.findViewById(R.id.edit_text_file_name);
mSongFile = uploadViews.findViewById(R.id.track_file_view);
mProgressBar = uploadViews.findViewById(R.id.progress_bar);
mImageView = uploadViews.findViewById(R.id.image_view);
addselectArtists = uploadViews.findViewById(R.id.addArtist_img);
addSelectGenre = uploadViews.findViewById(R.id.addGenre_img);
addSelectAlbum = uploadViews.findViewById(R.id.addAlbum_img);
addSelectLanguage = uploadViews.findViewById(R.id.addLanguage_img);
selectedArtist = uploadViews.findViewById(R.id.artists);
selectedAlbum = uploadViews.findViewById(R.id.album);
selectedGenre = uploadViews.findViewById(R.id.genre);
selectedLanguage = uploadViews.findViewById(R.id.language);
mStorageImageRef = FirebaseStorage.getInstance().getReference("Images");
mStorageSongRef = FirebaseStorage.getInstance().getReference("Songs");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("Data Uploads");
mDatabaseRefArtist = FirebaseDatabase.getInstance().getReference("Artists");
uriImage = Uri.parse("https://media.kasperskydaily.com/wp-content/uploads/sites/92/2019/12/09084248/android-device-identifiers-featured.jpg");
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
final Toolbar toolbar = uploadViews.findViewById(R.id.toolbar_upload);
toolbar.setTitle("Upload Songs");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySongFragment mySongFragment = new MySongFragment();
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (fragment == null){
fragmentManager.beginTransaction()
.add(R.id.fragment_container, mySongFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}else {
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, mySongFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}
((AppCompatActivity)getActivity()).getSupportActionBar().show();
}
});
mBtnChooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImageChooser();
}
});
mBtnChooseSong.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openSongChooser();
}
});
addselectArtists.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChooseArtistFragment chooseArtistFragment = new ChooseArtistFragment();
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, chooseArtistFragment)
.addToBackStack(null)
.commit();
}
});
addSelectGenre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//go to choose/select genre here
ChooseGenreFragment chooseGenreFragment = new ChooseGenreFragment();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container,chooseGenreFragment)
.addToBackStack(null)
.commit();
}
});
addSelectAlbum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChooseAlbumFragment chooseAlbumFragment = new ChooseAlbumFragment();
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, chooseAlbumFragment)
.addToBackStack(null)
.commit();
}
});
addSelectLanguage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChooseLanguageFragment chooseLanguageFragment = new ChooseLanguageFragment();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container,chooseLanguageFragment)
.addToBackStack(null)
.commit();
}
});
mBtnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadFile();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new MySongFragment())
.remove(new FragmentUpload())
.addToBackStack(null)
.commit();
ViewGroup mContainer = getActivity().findViewById(R.id.uploadFragment);
mContainer.removeAllViews();
((AppCompatActivity)getActivity()).getSupportActionBar().show();
}
});
return uploadViews;
}
#Override
public void onStart() {
super.onStart();
Bundle bundle = this.getArguments();
if (bundle == null){
selectedArtist.setText("No Artist Selected");
selectedGenre.setText("No Genre Selected");
selectedLanguage.setText("No Language Selected");
selectedAlbum.setText("No Album Selected");
return;
}
String string = "";
for (String key : bundle.keySet()){
string += key;
switch (string){
case "artistList":
String myValue = bundle.getString("artistList");
selectedArtist.setText(myValue);
break;
case "albumList":
String myValue1 = bundle.getString("albumList");
selectedAlbum.setText(myValue1);
break;
case "langaugeList":
String myValue2 = bundle.getString("languageList");
selectedLanguage.setText(myValue2);
break;
case "genreList":
String myValue3 = bundle.getString("genreList");
selectedGenre.setText(myValue3);
break;
}
}
}
private void openSongChooser(){
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_SONG_REQUEST);
}
private void openImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK
&& data != null && data.getData() != null){
mImageUri = data.getData();
Picasso.get().load(mImageUri).resize(1000,1000).centerCrop().into(mImageView);
// mImageView.setImageURI(mImageUri);
}
if (requestCode == PICK_SONG_REQUEST && resultCode ==Activity.RESULT_OK
&& data != null && data.getData() != null){
mSongUri = data.getData();
Cursor cursor = getActivity().getContentResolver().query(mSongUri,null,null,null,null);
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
String mimeType = getFileExtension(mSongUri);
cursor.moveToFirst();
mSongFile.setText(cursor.getString(nameIndex)+"."+ mimeType);
}
}
private String getFileExtension(Uri uri){
ContentResolver cR = getActivity().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile(){
if (mImageUri != null){
StorageReference fileReferece = mStorageImageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
fileReferece.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 5000);
Toast.makeText(getActivity(), "Image Upload Successful", Toast.LENGTH_SHORT).show();
Task<Uri> uriTaskImage = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTaskImage.isSuccessful());
Uri downloadUriImage = uriTaskImage.getResult();
uriImage = downloadUriImage;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int)progress);
}
});
}else{
Toast.makeText(getActivity(), "No Image File Selected", Toast.LENGTH_SHORT).show();
}
if (mSongUri != null){
StorageReference fileRef = mStorageSongRef.child(System.currentTimeMillis()
+"." + getFileExtension(mSongUri));
fileRef.putFile(mSongUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 5000);
Toast.makeText(getActivity(), "Track Upload Successful", Toast.LENGTH_SHORT).show();
Task<Uri> uriTaskSong = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTaskSong.isSuccessful());
Uri downloadUriSong = uriTaskSong.getResult();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
downloadUriSong.toString(),uriImage.toString(), selectedArtist.getText().toString().trim());
String uploadIdSong = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadIdSong).setValue(upload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int)progress);
}
});
}else {
Toast.makeText(getActivity(), "No Song File Selected", Toast.LENGTH_SHORT).show();
}
}
}
refrence image
I m trying to create an webapp with file upload possibility.
I have gone through some queries listed in StackOverflow as well for solution no this like
File Upload in WebView
However when applied the same in my mainactivity, couldn't resolve some errors showing with red underlines.
Here's my MainActivity.java:
package com.pack.packname;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webviewid);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://google.com/");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setDomStorageEnabled(true);
}
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
if(webView.canGoBack()){
webView.goBack();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
protected class CustomWebChromeClient extends WebChromeClient {
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
context.mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
context.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE);
}
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
}
}
}
I have added an image as well to check the errors that are causing as well.
Any help is greatly appreciated..
package com.pack.packname;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_SELECT_FILE = 100;
private final static int FILE_CHOOSER_RESULT_CODE = 1;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> uploadMessage;
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webviewid);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://google.com/");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setDomStorageEnabled(true);
webView..setWebChromeClient(new WebChromeClient() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
}
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
if(webView.canGoBack()){
webView.goBack();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
try this code
I have removed AdMob from my source code of Android Studio, but still, it's showing an empty space at the bottom in the app.
It's always occupying an empty space at the bottom. I do not know how to make that bottom space disappear completely and show a normal preview of the app without ads.
How can I do this?
Here is the code.
Mainactivity.java
package com.dshgh.webview;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.dshgh.webview.Fragments.WebViewFragment;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mRegistrationBroadcastReceiver;
boolean doubleBackToExitPressedOnce = false;
private FirebaseAnalytics mFirebaseAnalytics;
RelativeLayout rel_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//ButterKnife.bind(this);
rel_layout = (RelativeLayout)findViewById(R.id.rel_layout);
// Obtain the FirebaseAnalytics instance.
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
WebViewFragment webViewFragment = new WebViewFragment();
bundle.putString("url", Config.homeUrl);
webViewFragment.setArguments(bundle);
loadFragment(webViewFragment, false, "webViewFragment");
try {
Intent intent = getIntent();
String message = intent.getStringExtra("message");
String url = intent.getStringExtra("url");
Log.d("notification Data", message + url);
if (url.length() > 0) {
bundle.putString("url", url);
webViewFragment.setArguments(bundle);
loadFragment(webViewFragment, false, "webViewFragment");
}
}
catch (Exception e) {
Log.d("error notification data", e.toString());
}
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
displayFirebaseRegId();
}
private void displayFirebaseRegId() {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
String regId = pref.getString("regId", null);
Log.e("FCM", "Firebase reg id: " + regId);
if (!TextUtils.isEmpty(regId)) {
//txtRegId.setText("Firebase Reg Id: " + regId);
}
else
Log.d("Firebase", "Firebase Reg Id is not received yet!");
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
if(fragment != null && fragment instanceof WebViewFragment) {
if(((WebViewFragment) fragment).onBackPressed()) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
// Toast.makeText(this, "Press back once more to exit", Toast.LENGTH_SHORT).show();
Snackbar snackbar = Snackbar
.make(rel_layout, "Press back once more to exit", Snackbar.LENGTH_LONG);
snackbar.setActionTextColor(Color.RED);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.DKGRAY);
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
}
public void loadFragment(Fragment fragment, Boolean bool) {
loadFragment(fragment, bool, null);
}
public void loadFragment(Fragment fragment, Boolean bool, String TAG) {
showAds();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if(TAG == null) {
transaction.replace(R.id.frameLayout, fragment);
}else {
transaction.replace(R.id.frameLayout, fragment, TAG);
}
if (bool)
transaction.addToBackStack(null);
transaction.commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
if(fragment != null && fragment instanceof WebViewFragment) {
((WebViewFragment)fragment).onActivityResult(requestCode, resultCode, intent);
}
super.onActivityResult(requestCode, resultCode, intent);
}
public void hideAds() {
}
public void showAds() {
}
}
I think you forgot to remove <com.google.android.gms.ads.AdView......./> from your XML page.
Please remove it.
I found that my function of the app is not working for certain android phone.
I think maybe is the problem of android version? My app is working fine on an other Android phone, so how can I solve this issue?
public class StartActivity extends AppCompatActivity {
private Button btnupload,btnchoose;
private ImageView imgprofile;
Uri filepath;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
btnchoose = (Button)findViewById(R.id.btn_addphoto);
btnupload = (Button)findViewById(R.id.btn_upload);
imgprofile = (ImageView)findViewById(R.id.imageView);
btnchoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseimage();
}
});
btnupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
private void chooseimage() {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
filepath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
Toast.makeText(StartActivity.this, "YES!", Toast.LENGTH_SHORT).show();
bitmap = Bitmap.createScaledBitmap(bitmap, imgprofile.getWidth(),imgprofile.getHeight(),true);
imgprofile.setImageBitmap(bitmap);
} else {
Toast.makeText(StartActivity.this, "YES!!!!", Toast.LENGTH_SHORT).show();
imgprofile.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I run my app on the phone which is version 5.0.2 it does not show any response of toast.
This is the code works for me. I just change the position of the function, the code still the same.
package com.example.user8.letseat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
import java.util.UUID;
public class StartActivity extends AppCompatActivity {
private Button btnupload,btnchoose;
private ImageView imgprofile;
Uri filepath;
private static final int PICK_IMAGE_REQUEST = 1;
FirebaseStorage firebaseStorage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
btnchoose = (Button)findViewById(R.id.btn_addphoto);
btnupload = (Button)findViewById(R.id.btn_upload);
imgprofile = (ImageView)findViewById(R.id.imageView);
btnchoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
}
});
btnupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadimage();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
{
filepath = data.getData();
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
imgprofile.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadimage() {
if (filepath != null)
{
final ProgressDialog pg = new ProgressDialog(this);
pg.setTitle("Uploading...");
pg.show();
StorageReference ref = storageReference.child("image/" + UUID.randomUUID().toString());
ref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pg.dismiss();
DatabaseReference databaseReference ;
databaseReference= FirebaseDatabase.getInstance().getReference("Imageeee");
String ImageUploadId = databaseReference.push().getKey();
String imageurl = taskSnapshot.getDownloadUrl().toString();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageurl);
Toast.makeText(StartActivity.this, "FINISH", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pg.dismiss();
Toast.makeText(StartActivity.this, "FAIL"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
pg.setMessage("Uploaded" + (int)progress+"%");
}
});
}
}
}
MyActivity.xml
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_x="13dp"
android:layout_y="112dp" />
MainActivity.java
public class MainActivityextends Activity {
Button imageUpload;
ImageView imageView;
static final int PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
imageUpload= (Button) findViewById(R.id.buttonImage);
imageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,PICTURE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==PICTURE && resultCode==RESULT_OK && null !=data)
{
Uri uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(prjection[0]);
String path=cursor.getString(columnIndex);
cursor.close();
Bitmap selectFile = BitmapFactory.decodeFile(path);
Drawable d = new BitmapDrawable(selectFile);
imageView.setBackground(d);
// imageView.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
Check Simple code of get image from gallery and display hopr this may help you.
Example