When react native require this native ui component multiple time, starting from the second one, the previous became black.
Any ideas?
#Override
public String getName()
{
return "JWPlayer";
}
#Override
public JWPlayerView createViewInstance(ThemedReactContext context)
{
PlayerConfig playerConfig = new PlayerConfig.Builder().build();
playerView = new JWPlayerView(context.getCurrentActivity(), playerConfig);
playerView.setFullscreen(false, false);
playerView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
playerView.addOnFullscreenListener(this);
playerView.addOnPauseListener(this);
playerView.addOnPlayListener(this);
playerView.addOnSetupErrorListener(this);
playerView.addOnErrorListener(this);
return playerView;
}
I also met this question.
I solved the problem.
see same question ,
this
JWView.java :
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.longtailvideo.jwplayer.JWPlayerView;
import com.longtailvideo.jwplayer.configuration.PlayerConfig;
public class JWView extends FrameLayout {
private final Context _context;
private Activity activity = null;
public JWView(Context context) {
super(context);
this._context = context;
this.activity = ((ReactContext) getContext()).getCurrentActivity();
PlayerConfig playerConfig = new PlayerConfig.Builder()
.file("http://img.ksbbs.com/asset/Mon_1605/25d705200a4eab4.mp4")
.autostart(false)
.build();
JWPlayerView playerView = new JWPlayerView(this.activity, playerConfig);
addView(playerView);
}
private final Runnable measureAndLayout = new Runnable() {
#Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
#Override
public void requestLayout() {
super.requestLayout();
// The spinner relies on a measure + layout pass happening after it calls requestLayout().
// Without this, the widget never actually changes the selection and doesn't call the
// appropriate listeners. Since we override onLayout in our ViewGroups, a layout pass never
// happens after a call to requestLayout, so we simulate one here.
post(measureAndLayout);
}
}
JWPlayerViewManager.java:
import java.util.List;
import java.util.ArrayList;
import android.app.Activity;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.longtailvideo.jwplayer.JWPlayerView;
import com.longtailvideo.jwplayer.configuration.PlayerConfig;
public class JWPlayerViewManager extends SimpleViewManager<JWView>
{
#Override
public String getName()
{
return "Jwplayer";
}
#Override
public JWView createViewInstance(ThemedReactContext context)
{
return new JWView(context);
}
}
Related
Here is my NativScript code for android
package com.chetti; // replace com.your-app-name with your app’s name
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.app.Activity;
public class CalendarModule extends ReactContextBaseJavaModule {
CalendarModule(ReactApplicationContext context) {
super(context);
}
#Override
public String getName() {
return "CalendarModule";
}
#ReactMethod
public String createCalendarEvent() {
// I am not sure about how to get TelephonyManager instance!
TelephonyManager manager=(TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber1 = manager.getLine1Number();
return phoneNumber1;
}
}
Error throwing are follows->
error: cannot find symbol
TelephonyManager manager=(TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
^
symbol: method getActivity()
location: class CalendarModule
My requirement is to get the mobile numbers using Native Module for android?.
My specs:
1, React Native 0.68.0
2, node 17
Just putting here a function so that you can get an idea:
#Override
public void onReceive(final Context context, final Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String phoneNumber) {
Log.d("RINGER_IID", phoneNumber);
onCustomCallStateChanged(context, state, phoneNumber);
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
https://developer.android.com/reference/android/telephony/TelephonyManager
Got through this. Hope this helps.
This is the interface of my application, my question is, if I click on "video lecture" then it should go to Video Lecture Activity and if i click on "Detail Notes" then it should go in Detail Notes Activity. Similarly, i want to do with all recyclerView items.
This is my Adapter code
package com.example.motionofknowledge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.motionofknowledge.databinding.ActivityMaterialsBinding;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class Materials extends AppCompatActivity {
ActivityMaterialsBinding binding;
FirebaseFirestore database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMaterialsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
String head = getIntent().getStringExtra("subName");
TextView textView = findViewById(R.id.headingMat);
textView.setText(new String(head));
database = FirebaseFirestore.getInstance();
ArrayList<MatModel> materials = new ArrayList<>();
MatAdapter adapter = new MatAdapter(this,materials);
String subId = getIntent().getStringExtra("subId");
database.collection("subjects")
.document(subId)
.collection("mat")
.orderBy("index")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
materials.clear();
for (DocumentSnapshot snapshot:value.getDocuments()){
MatModel model = snapshot.toObject(MatModel.class);
model.setMatId(snapshot.getId());
materials.add(model);
}
adapter.notifyDataSetChanged();
}
});
binding.matList.setLayoutManager(new GridLayoutManager(this,2));
binding.matList.setAdapter(adapter);
binding.matHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Materials.this,MainActivity.class);
startActivity(intent);
}
});
}
}
This is my adapter code
package com.example.motionofknowledge;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MatAdapter extends RecyclerView.Adapter<MatAdapter.MatViewHolder>{
Context context;
ArrayList<MatModel> matModels;
public MatAdapter(Context context, ArrayList<MatModel> matModels){
this.context = context;
this.matModels = matModels;
}
#NonNull
#Override
public MatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_category,null);
return new MatViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MatViewHolder holder, int position) {
MatModel model = matModels.get(position);
holder.textView.setText(model.getMatName());
Glide.with(context)
.load(model.getMatImage())
.into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,Chapters.class);
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return matModels.size();
}
public class MatViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView;
public MatViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
textView = itemView.findViewById(R.id.category);
}
}
}
You did not post your adapter code, but your activity code. Anyway: I understand that you have a recyclerView with different kind of items in it (Video Lecture, Detail Notes, and more). Depending on which item the user clicks, you want to do different things.
This is done by using the onBindViewHolder method in your MatAdapter. This method does not only bind the data to the UI layout, but it should also be used to bind a click listener to the UI layout.
If you have only a few items in your RecyclerView, you could use the getItem(position) method of your adapter to find out what specific item you are dealing with within onBindViewHolder. As soon as you know what kind of item the Adapter wants to bind, you can set the according click listener.
See this suggestion:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = null
if (model.type == VIDEO) {
intent = new Intent(context,Video.class);
} else if (model.type == DETAILS) {
intent = new Intent(context,Details.class);
} else {
...
}
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
model is the current MatModel that you want to bind.
model.type is any way to distinguish the different items. I do not know the details of the MatModel class, but you somehow need to be able to distinguish the different models, of course.
I've written native module for React Native, everything was done according to official documentation, but something went wrong, and Native Modules returns only empty object.
importing Native Modules in Component Home.js
All Module code was writen according to official docs
import {
NativeModules
} from 'react-native';
const { OptionsPackage } = NativeModules;
console.log(NativeModules) // {}
MainApplication.java file
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new OptionsPackage());
return packages;
}
OptionsPackage.java file
package package.name;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OptionsPackage implements ReactPackage {
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new OptionsModule(reactContext));
return modules;
}
}
OptionsModule.java
package com.downloadmanager;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.io.InputStream;
...
public class OptionsModule extends ReactContextBaseJavaModule {
ActivityManager activityManager;
int currentSDK;
ReactApplicationContext context;
OptionsModule(ReactApplicationContext context) {
super(context);
this.activityManager = ((ActivityManager) context.getSystemService(ReactApplicationContext.ACTIVITY_SERVICE));
context = context;
currentSDK = android.os.Build.VERSION.SDK_INT;
}
#Override
public String getName() {
return "123";
}
private Map packageInfoToMap(PackageInfo pi) {
PackageManager pm = this.context.getPackageManager();
long longVersionCode;
Map<String, Object> AppInfo = new HashMap<String, Object>();
if(Build.VERSION.SDK_INT >= 28) {
longVersionCode = pi.getLongVersionCode();
} else
{
longVersionCode = pi.versionCode; }
AppInfo.put("packageName", pi.packageName);
AppInfo.put("versionName", pi.versionName);
AppInfo.put("getLongVersionCode", longVersionCode);
AppInfo.put("lastUpdateTime", (pi.lastUpdateTime));
AppInfo.put("firstInstallTime", pi.firstInstallTime);
String title = pi.applicationInfo.loadLabel(pm).toString();
String description = pi.applicationInfo.loadDescription(pm).toString();
Drawable icon = pi.applicationInfo.loadIcon(pm);
AppInfo.put("title", title);
AppInfo.put("description", description);
AppInfo.put("icon", icon);
//get folder
String apkDir = pi.applicationInfo.publicSourceDir;
File file = new File(apkDir);
double size = file.length();
AppInfo.put("filePath", apkDir);
AppInfo.put("size", size);
return AppInfo;
}
#ReactMethod
public List listOfApps(String type) {
List<PackageInfo> packages = this.context.getPackageManager().getInstalledPackages(0);
List<Map<String, Object>> listOfApps = new ArrayList();
for (PackageInfo isPackage : packages) {
boolean isSystem = (isPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM;
if(type == "systemOnly" && isSystem) {
listOfApps.add(this.packageInfoToMap(isPackage));
} else if (type == "nonSystem" && !isSystem) {
listOfApps.add(this.packageInfoToMap(isPackage));
} else {
listOfApps.add(this.packageInfoToMap(isPackage));
}
}
return listOfApps;
}
}
Your getName() override method in OptionsModule is returning "123"
#Override
public String getName() {
return "123";
}
This is how react native gets the name of your module that should show up on react native side.
Try changing it to "OptionsModule" and then in your Home.js do
const {OptionsModule} = NativeModules
Also try calling your #ReactMethod in js to see if it works, don't rely on console logging NativeModules.
I am facing issue in calling my java class methods (android native code) from JS.
I have already followed https://facebook.github.io/react-native/docs/native-modules-android.html but its not working. Please find below the issues which I am facing.
Where we should export android module, I have done it in index.js
import {NativeModules} from 'react-native';
const { ScannerInteractor } = NativeModules;
export default ScannerInteractor;
or
import {NativeModules} from 'react-native';
module.exports = NativeModules.ScannerInteractor;
In a javascript class where I want to call this method how should I import my class, I have written following code. Does it matter if index.js are at same level as of my javascript class?
import ScannerInteractor from "./ScannerInteractor"
I have created member methods then how to call them? As per example, it need to be call as static method call.
ScannerInteractor.startScan(this, null, null);
How to pass context variable from JS, will passing 'this' parameter will work?
I am not getting any error or log messages in the logcat but method is also not getting triggered.
NativeModule class
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.kohl.scan.common.ScannerInteractor;
public class ModuleInjector implements ReactPackage {
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ScannerInteractor(reactContext));
return modules;
}
}
ApplicationClass
import com.facebook.react.ReactPackage;
import java.util.Arrays;
import java.util.List;
import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;
import com.reactnativenavigation.NavigationApplication;
import com.oblador.vectoricons.VectorIconsPackage;
import com.rfpproject.ModuleInjector;
public class MainApplication extends NavigationApplication {
#Override
public boolean isDebug() {
// Make sure you are using BuildConfig from your own application
return BuildConfig.DEBUG;
}
protected List<ReactPackage> getPackages() {
// Add additional packages you require here
// No need to add RnnPackage and MainReactPackage
return Arrays.<ReactPackage>asList(
// eg. new VectorIconsPackage()
new ReactNativeConfigPackage(),
new VectorIconsPackage(),
new ModuleInjector()
);
}
#Override
public String getJSMainModuleName() {
return "index";
}
#Override
public List<ReactPackage> createAdditionalReactPackages() {
return getPackages();
}
}
I am calling it from JS script as mentioned below:
onClick1(){
ScannerInteractor.startScan(this, null, null);
//alert('cllllll');
}
It has worked after using
import {NativeModules} from 'react-native';
module.exports = NativeModules.ScannerInteractor;
and
import {NativeModules} from 'react-native'; in the JS class and calling using NativeModules.ScannerInteractor.check()
Still not clear about how to pass context variable as an argument.
I need to create an app that involves browsing pdf from phone and then reading it (which will be executed later, once the browsing part is done) and I'm having trouble with it's code. I have gone through the following link I found on stackoverflow, but unfortunately it is not working,
Browse and upload pdf or word file in Android
Here is my MainActivity.java class
import java.io.File;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
Button btnAttach;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAttach = (Button) findViewById(R.id.button1);
//button1 is the id of the only button I have in my activity_main.xml
// view products click event
btnAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button1_OnClick(view);
// Launching All products Activity
}
});
}
public void button1_OnClick(View view) {
getDocument();
}
private void getDocument() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/msword,application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
}
protected void onActivityResult ( int req, int result, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(req, result, data);
if (result == RESULT_OK) {
Uri fileuri = data.getData();
String docFilePath = getFileNameByUri(this, fileuri);
}
}
// get file path
private String getFileNameByUri(Context context, Uri uri) {
String filepath = "";//default fileName
File file;
if (uri.getScheme().toString().compareTo("content") == 0) {
Cursor cursor = context.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION}, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String mImagePath = cursor.getString(column_index);
cursor.close();
filepath = mImagePath;
} else if (uri.getScheme().compareTo("file") == 0) {
try {
file = new File(new URI(uri.toString()));
if (file.exists())
filepath = file.getAbsolutePath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
filepath = uri.getPath();
}
return filepath;
}
}
As #CherryDT pointed out, startActivityForResult(intent, REQUEST_CODE_DOC); was missing. Added it and fixed the issue.