How to fix this Java code to upload file with webview element android studio - java

Developing very basic app for my site to upload files to server using a webview to emulate the desktop process, failing to get it to work.
I have copied code from GitHub to form this app, however when I press the input button on the HTML form I am prompted to select a file from my phone's storage, after doing so the selected file doesn't show up in the HTML form, and pressing the button again results in no action. I've no idea why and I really don't know Java, can anyone help? (YouTube video of original GitHub poster - https://www.youtube.com/watch?v=oFGQbXdWv-g) (Github page - https://github.com/tarikul1988/WebViewFileUploadWorking)
The entire project code is as follows;
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.xyz.imagedrop.MainActivity">
<WebView
android:id="#+id/webview_sample"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
MainActivity.java:
package com.xyz.imagedrop;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview_sample);
if (Build.VERSION.SDK_INT >= 23 &&(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
//webView.loadUrl("https://infeeds.com/");
webView.loadUrl("http://imagedrop.xyz");
webView.setWebChromeClient(new WebChromeClient() {
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
// Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent contentSelectionIntent = new
Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
// Intent[] intentArray;
//
// if (takePictureIntent != null) {
// intentArray = new Intent[]{takePictureIntent};
// } else {
// intentArray = new Intent[0];
// }
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT,
contentSelectionIntent);
// chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image
Chooser");
// chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
});
}
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String
description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!",
Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xyz.imagedrop">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
</uses-permission>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Related

Issue in making UPI payment request from android

UPI payment failed in PhonePe while testing my android application.
The error it is showing is - For security reasons, you are not allowed to send money from your bank account for this payment. You don't have to enter UPI PIN to receive money/cashback.
MainActivity.java contains -
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button pay_btn;
final int UPI_PAYMENT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pay_btn = (Button) findViewById(R.id.pay_btn);
pay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
payUsingUpi("1","Test Payment","Ratnadeep Parya","parya.ratnadeep125#okaxis");
}
});
}
private void payUsingUpi(String amounttxt, String notetxt, String nametxt, String upitxt) {
Uri uri = Uri.parse("upi://pay").buildUpon()
.appendQueryParameter("pa",upitxt)
.appendQueryParameter("pn",nametxt)
.appendQueryParameter("tn",notetxt)
.appendQueryParameter("am",amounttxt)
.appendQueryParameter("cu","INR")
.build();
Intent upi_payment = new Intent(Intent.ACTION_VIEW);
upi_payment.setData(uri);
Intent chooser = Intent.createChooser(upi_payment,"Pay with");
if (null!=chooser.resolveActivity(getPackageManager())){
startActivityForResult(chooser,UPI_PAYMENT);
}
else {
Toast.makeText(this, "No UPI app found!", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case UPI_PAYMENT:
if ((RESULT_OK==resultCode|| (resultCode==11))){
if (data!=null){
String txt = data.getStringExtra("response");
Log.d("UPI", "onActivityResult: "+ txt);
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
else {
Log.d("UPI", "onActivityResult: "+ "Return data is null!");
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
}
else {
Log.d("UPI", "onActivityResult: "+ "Return data is null!");
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
break;
}
}
private void upipaymentdataoperation(ArrayList<String> data) {
if (isConnectionAvailable(MainActivity.this)){
String str = data.get(0);
Log.d("UPIPAY", "upipaymentdataoperation: "+str);
String paymentCancel="";
if (str==null)str="discard";
String status = "";
String approvalref = "";
String response[]=str.split("&");
for (int i=0;i<response.length;i++){
String equalStr[]=response[i].split("=");
if (equalStr.length>=2){
if (equalStr[0].toLowerCase().equals("Status".toLowerCase())){
status=equalStr[1].toLowerCase();
}
else if(equalStr[0].toLowerCase().equals("approval Ref".toLowerCase())||
equalStr[0].toLowerCase().equals("txnRef".toLowerCase()))
{
approvalref=equalStr[1];
}
}
else {
paymentCancel="Payment cancelled by user";
if (status.equals("success")){
Toast.makeText(this, "Transaction success", Toast.LENGTH_SHORT).show();
Log.d("UPI", "responsestr: "+approvalref);
}
else if ("Payment cancelled by user".equals(paymentCancel)){
Toast.makeText(this, "Payment cancelled by user", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Transaction failed", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText(this, "No internet", Toast.LENGTH_SHORT).show();
}
}
private boolean isConnectionAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager!=null){
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null && networkInfo.isConnected() && networkInfo.isConnectedOrConnecting() && networkInfo.isAvailable()){
return true;
}
}
return false;
}
}
AndroidManifest.xml contains -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.UpiTesting"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml contains -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context=".MainActivity">
<Button
android:id="#+id/pay_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pay_with_upi"
android:backgroundTint="#android:color/holo_green_dark"
android:layout_centerInParent="true"
android:textSize="20sp"/>
</RelativeLayout>
Please assist me to get rid of this issue.
I was trying to test UPI payment by sending request in UPI application.
In PhonePe it is showing that - For security reasons, you are not allowed to send money from your bank account for this payment. You don't have to enter UPI PIN to receive money/cashback.

Why my Android App is not scanning Bluetooth device?

In my Bluetooth App I have created two buttons one for getting paired devices and the other to scan the Bluetooth device. When I click the scan button Toast message shows no device found, the code always goes to else part in my broadcast receiver. Can someone explain to me what's happening*
** MainActivity.java **
package com.example.broadcast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_ENABLE_BT = 2;
private Button scanButton;
private Button discoverButton;
private MyBroadcast broadcast;
private MyBroadcastdiscover broadcastdiscover;
public BluetoothAdapter bluetoothAdapter;
public Set<BluetoothDevice> pairedDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcast=new MyBroadcast();
broadcastdiscover=new MyBroadcastdiscover();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
scanButton=(Button) findViewById(R.id.scan_btn);
discoverButton=(Button) findViewById(R.id.discover_btn);
scanButton.setOnClickListener(this);
discoverButton.setOnClickListener(this);
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(getApplicationContext(),"Device doesn't support bluetooth", Toast.LENGTH_LONG).show();
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(broadcast, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcast);
unregisterReceiver(broadcastdiscover);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcast);
unregisterReceiver(broadcastdiscover);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.scan_btn:
{
pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
ArrayList list = new ArrayList();
list.add(device.getName());
Toast.makeText(getApplicationContext(),deviceName,Toast.LENGTH_LONG).show();
}
break;
}
}
case R.id.discover_btn:
{
Toast.makeText(getApplicationContext(),"SCAN",Toast.LENGTH_LONG).show();
/* Intent discoverableIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
startActivity(discoverableIntent);*/
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
checkBTPermission();
bluetoothAdapter.startDiscovery();
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
if(!bluetoothAdapter.isDiscovering())
{
bluetoothAdapter.startDiscovery();
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
break;
}
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkBTPermission() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d("TAG", "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
}
** MyBroadcastdiscover.java**
package com.example.broadcast;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
public class MyBroadcastdiscover extends BroadcastReceiver {
public ArrayList<BluetoothDevice> mBTDevices=new ArrayList<>();
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Toast.makeText(context,action,Toast.LENGTH_LONG).show();
if(action.equals(BluetoothDevice.ACTION_FOUND))
{
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Toast.makeText(context,deviceName,Toast.LENGTH_LONG).show();
Log.d("TAG",deviceHardwareAddress);
}
else {
Toast.makeText(context,"NO DEVICE YET FOuND",Toast.LENGTH_LONG).show();
Log.d("TAG","DEVICE NOT FOUND");
}
}
}
** AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcast">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- If your app targets Android 9 or lower, you can declare
ACCESS_COARSE_LOCATION instead. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Broadcast">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
** activitymain.xml**
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.119" />
<Button
android:id="#+id/scan_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="108dp"
android:text="#string/scanDevice"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<Button
android:id="#+id/discover_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="92dp"
android:text="#string/scanningdevice"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/scan_btn" />
</androidx.constraintlayout.widget.ConstraintLayout>
You must declare the service inside aplication in Manifest.xml like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Broadcast">
...
<receiver android:name="com.example.broadcast.MyBroadcastdiscover" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACTION_FOUND" />
</intent-filter>
</receiver>
</application>

onActivityResult is not getting called in MainActivity.Java

I am trying to make an app which shows a user selected image which can be set by double-clicking on the button. The app does ask me for an image (which is good) but I don't know how to set it on ImageView if this onActivityResult is not getting called.
MainActivity:
package com.forever.bobby.cheater20;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.tomerrosenfeld.customanalogclockview.CustomAnalogClock;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE = 100;
Button hiddenOnClickListener;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = findViewById(R.id.imageView);
CustomAnalogClock customAnalogClock = (CustomAnalogClock) findViewById(R.id.analog_clock);
customAnalogClock.setAutoUpdate(true);
hiddenOnClickListener = (Button) findViewById(R.id.touchButtonHidden);
hiddenOnClickListener.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.e ("mPressesOnce -_-","..");
}
#Override
public void onDoubleClick(View v) {
Log.e ("mPressesTwice -_-","..");
openGallery();
}
});
}
private void openGallery () {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 0);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode,data);
Log.e ("SHould Be Steeted","");
if (requestCode == 0) {
Uri imgUri;
imgUri = data.getData();
// img.setImageURI(imgUri);
}
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.forever.bobby.cheater20">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Any Kind of help is appreciated as I am a newbie
With android sdk >= 23, some permissions e.g. WRITE_EXTERNAL_STORE, READ_EXTERNAL_STORE, etc. you must request it in java code.
Therefore, when user starts using feature need permission, android will show a dialog and user can grant or cancel a permission. You can read more about it on developer.android.com.

App works on emulator but not on device?

MyApp simply doesn't launch. It starts to open and just shuts off. I am guessing I have screwed something here in the Build when Google Developers asked me to change the Code Version, although I am not sure. Any help is deeply appreciated. I am positive I am making some very basic mistake,although I cannot put my finger on it. It works perfectly on a Nexus Emulator though.
Earlier it was just a splash screen which led to a webview. Then I added a page with two options(Buttons) to choose the webview after the splash animation. Thats the change that I made although if it is working on Emulator I am not sure if the activity code is the issdue.
Build.Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.utilities.livegoldsilverusd"
minSdkVersion 16
targetSdkVersion 26
versionCode 3
versionName "1.3"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-ads:11.0.4'
testCompile 'junit:junit:4.12'
}
Manifest.XML
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.utilities.livegoldsilverusd">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/newicon"
android:label="LiveMCXRates"
android:roundIcon="#mipmap/newicon"
android:supportsRtl="false"
android:theme="#style/AppTheme">
<!-- Splash screen -->
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".Welcome_Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".options"
android:label="#string/app_name"></activity>
<activity
android:name=".Bitcoin"
android:label="#string/app_name">
</activity>
</application>
</manifest>
MainActivity.Java
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
else {
Toast.makeText(MainActivity.this, "Let's Make Money! WooHoo", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
}
{
myWebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
myWebView.loadUrl("http://viralonworld.com/m1/runtmfultb.php");
myWebView.setWebViewClient(new WebViewClient());
}
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or wifi to access this. Press ok to Exit");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder;
}
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}
Options.Java
package com.utilities.livegoldsilverusd;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import static com.utilities.livegoldsilverusd.R.id.button1;
import static com.utilities.livegoldsilverusd.R.layout.activity_options;
public class options extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_options);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(options.this, MainActivity.class);
startActivity(myIntent);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(options.this, Bitcoin.class);
startActivity(myIntent);
}
});
}
}
Bitcoin.java
package com.utilities.livegoldsilverusd;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class Bitcoin extends Activity {
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isConnected(Bitcoin.this)) buildDialog(Bitcoin.this).show();
else {
Toast.makeText(Bitcoin.this, "Let's Make Money! WooHoo", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
}
{
myWebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
myWebView.loadUrl("http://bitcointicker.co/");
myWebView.setWebViewClient(new WebViewClient());
}
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting()))
return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or wifi to access this. Press ok to Exit");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder;
}
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}
activity_options.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_dark">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginBottom="146dp"
android:background="#drawable/buttonshape"
android:onClick="goToMainActivity"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:text="Live MCX Rates"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginBottom="74dp"
android:background="#drawable/buttonshape"
android:onClick="goTobitcoin"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:text="BitCoin"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:layout_above="#+id/button1"
android:layout_alignLeft="#+id/button1"
android:layout_alignStart="#+id/button1" />
</RelativeLayout>
activity_bitcoin.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.utilities.livegoldsilverusd.MainActivity">
<WebView
android:id="#+id/myWebView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
I think problem is due to we are setting content view of activity_main, which loads a layout file that contains a WebView with android:id="#+id/myWebView...
The problem solves when setting WebView in activity_main;
Write this in your activity_main.I think problem will be solved...
<WebView
android:id="#+id/myWebView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
Also modify your Manifest.xml by making MainActivity as launcher instead of Welcome
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.utilities.livegoldsilverusd">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/newicon"
android:label="LiveMCXRates"
android:roundIcon="#mipmap/newicon"
android:supportsRtl="false"
android:theme="#style/AppTheme">
<!-- Splash screen -->
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".options"
android:label="#string/app_name"></activity>
<activity
android:name=".Bitcoin"
android:label="#string/app_name">
</activity>
</application>
</manifest>

Android NFC not opening correct class on tap

I have an app with 2 classes, I need my app to open the second class CardActivity when the NFC tag tapped/swiped. The app opens fine, but MainActivity is run, instead of CardActivity.
I would hazard a guess that this is an issue with my manifest, but it looks correct. Here it is regardless:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spotsofmagic.spotsofmagic"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CardActivity"
android:label="#string/app_name" >
<!-- Handle a collectable card NDEF record -->
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<data android:mimeType="application/vnd.spotsofmagic.spotsofmagic"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
I'm confident the tag itself is correct, as I have opened it in another app to view it's contents.
Below are the two classes.
CardActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.bluetooth.*;
public class CardActivity extends Activity implements OnClickListener {
private static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.card_activity);
// see if app was started from a tag and show game console
Intent intent = getIntent();
Log.e(TAG, "Hello world. Intent Type: "+ intent.getType());
if(intent.getType() != null && intent.getType().equals(MimeType.NFC_DEMO)) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
NdefRecord cardRecord = msg.getRecords()[0];
String payload = new String(cardRecord.getPayload());
turnBluetoothOn(payload);
}
}
private void turnBluetoothOn(String payload) {
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Alert Dialog");
builder.setMessage(payload);
builder.setIcon(android.R.drawable.ic_dialog_alert);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
android.os.Process.killProcess(android.os.Process.myPid());
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
MainActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Activity...";
private NfcAdapter mAdapter;
private TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// grab our NFC Adapter
mAdapter = NfcAdapter.getDefaultAdapter(this);
// TextView that we'll use to output messages to screen
mTextView = (TextView)findViewById(R.id.text_view);
displayMessage("Loading payload...");
}
private void displayMessage(String message) {
mTextView.setText(message);
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Here is the code I used to write the tag. This is done on a different app incidentally:
NdefRecord appRecord = NdefRecord.createApplicationRecord("com.spotsofmagic.spotsofmagic");
// record that contains our custom "retro console" game data, using custom MIME_TYPE
byte[] payload = getPayload().getBytes();
byte[] mimeBytes = MimeType.NFC_DEMO.getBytes(Charset.forName("US-ASCII"));
NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes,
new byte[0], payload);
NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, appRecord});
// Some code here removed for readability
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
Does the NDEF message on the tag contain an Android Application Record? That could explain how MainActivity is launched. However, that can only be the cause if the AAR is the first record of the NDEF message on the tag or if the first record does not match the intent filter.

Categories

Resources