I have problem when i play video it's not working - javascript

Anyways Part of the tutorial makes use of a RecyclerView and I can't access it on my activity_main.xml file stating that v7 is an unresolved package. android.support.v7.widget.RecyclerView shows up with v7 onwards as red text. I know I can revert it back to older versions but I guess I am trying to make this work since moving forward its expected to know how to use androidx right?
I don't know how to add the RecyclerView to the project with my current project migrated to androidx.
What I've tried:
Adding implementation 'com.android.support:recyclerview-v7:28.0.0' based on the docs
Invalidating cache and restarting
My Dependencies:
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.kdapps.videoplayer.hdmaxplayer.video.player"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-process:2.3.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
implementation "androidx.work:work-runtime:2.6.0"
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
implementation 'com.google.android.gms:play-services-ads:19.8.0'
implementation 'com.facebook.android:audience-network-sdk:6.3.0'
implementation 'com.wang.avi:library:2.1.3'
implementation 'org.greenrobot:eventbus:3.2.0'
implementation 'com.amitshekhar.android:android-networking:1.0.2'
implementation 'com.specyci:residemenu:1.6+'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
}
package com.kdapps.videoplayer.hdmaxplayer.video.player.Fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kdapps.videoplayer.hdmaxplayer.video.player.Adapter.VideoAdapter;
import com.kdapps.videoplayer.hdmaxplayer.video.player.Model.EventBus;
import com.kdapps.videoplayer.hdmaxplayer.video.player.R;
import com.kdapps.videoplayer.hdmaxplayer.video.player.Util.VideoPlayerManager;
import com.kdapps.videoplayer.hdmaxplayer.video.player.Extra.MediaData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class RecentFragment extends Fragment {
#SuppressLint("StaticFieldLeak")
public static ImageView ivnodata;
public static RecyclerView recentrecycler;
ArrayList<MediaData> mediadataslist = new ArrayList<>();
private ProgressBar progress;
private View view;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
org.greenrobot.eventbus.EventBus.getDefault().register(this);
}
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
this.view = layoutInflater.inflate(R.layout.fragment_recent, viewGroup, false);
#SuppressLint("WrongConstant")
NetworkInfo activeNetworkInfo = ((ConnectivityManager) getActivity().getSystemService("connectivity")).getActiveNetworkInfo();
if (activeNetworkInfo != null) {
activeNetworkInfo.isConnected();
}
initView();
getVideo();
return this.view;
}
#Override
public void onDestroy() {
super.onDestroy();
org.greenrobot.eventbus.EventBus.getDefault().unregister(this);
}
#SuppressLint("WrongConstant")
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(EventBus event_Bus) {
int type = event_Bus.getType();
if (type == 0) {
initAdapter(this.mediadataslist, event_Bus.getValue());
} else if (type == 1) {
this.progress.setVisibility(0);
recentrecycler.setVisibility(8);
new Thread(new Runnable() {
public void run() {
RecentFragment.this.getVideo();
}
}).start();
} else if (type == 2) {
int value = event_Bus.getValue();
if (value == 0) {
Collections.sort(this.mediadataslist, new Comparator<MediaData>() {
public int compare(MediaData media_Data, MediaData media_Data2) {
return (Long.compare(Long.parseLong(media_Data2.getLength()), Long.parseLong(media_Data.getLength())));
}
});
initAdapter(this.mediadataslist, VideoPlayerManager.getViewBy());
} else if (value == 1) {
Collections.sort(this.mediadataslist, new Comparator<MediaData>() {
public int compare(MediaData media_Data, MediaData media_Data2) {
return Long.compare(Integer.parseInt(media_Data2.getDuration()), Integer.parseInt(media_Data.getDuration()));
}
});
initAdapter(this.mediadataslist, VideoPlayerManager.getViewBy());
} else if (value == 2) {
Collections.sort(this.mediadataslist, new Comparator<MediaData>() {
public int compare(MediaData media_Data, MediaData media_Data2) {
return media_Data.getName().compareTo(media_Data2.getName());
}
});
initAdapter(this.mediadataslist, VideoPlayerManager.getViewBy());
} else if (value == 3) {
Collections.sort(this.mediadataslist, new Comparator<MediaData>() {
public int compare(MediaData media_Data, MediaData media_Data2) {
return media_Data2.getModifieddate().compareTo(media_Data.getModifieddate());
}
});
initAdapter(this.mediadataslist, VideoPlayerManager.getViewBy());
}
} else if (type == 3) {
this.progress.setVisibility(0);
recentrecycler.setVisibility(8);
new Thread(new Runnable() {
public void run() {
RecentFragment.this.getVideo();
}
}).start();
}
}
#SuppressLint("WrongConstant")
public void getVideo() {
this.mediadataslist.clear();
if (!TextUtils.isEmpty(VideoPlayerManager.getRecentPlay())) {
final ArrayList arrayList = (ArrayList) new Gson().fromJson(VideoPlayerManager.getRecentPlay(), new TypeToken<List<MediaData>>() {
}.getType());
Collections.reverse(arrayList);
this.mediadataslist.addAll(arrayList);
getActivity().runOnUiThread(new Runnable() {
public void run() {
RecentFragment.this.initAdapter(arrayList, VideoPlayerManager.getViewBy());
}
});
return;
}
this.progress.setVisibility(8);
recentrecycler.setVisibility(8);
ivnodata.setVisibility(0);
}
#SuppressLint("WrongConstant")
public void initAdapter(ArrayList<MediaData> arrayList, int i) {
this.progress.setVisibility(8);
if (arrayList.size() > 0) {
recentrecycler.setVisibility(0);
ivnodata.setVisibility(8);
VideoAdapter video_Adapter = new VideoAdapter(getActivity(), arrayList, i, 2);
if (i == 0) {
recentrecycler.setLayoutManager(new LinearLayoutManager(getActivity(), 1, false));
} else {
recentrecycler.setLayoutManager(new GridLayoutManager((Context) getActivity(), 3, 1, false));
}
recentrecycler.setAdapter(video_Adapter);
return;
}
recentrecycler.setVisibility(8);
ivnodata.setVisibility(0);
}
private void initView() {
recentrecycler = (RecyclerView) this.view.findViewById(R.id.hide_recycler);
progress = (ProgressBar) this.view.findViewById(R.id.progress);
ivnodata = (ImageView) this.view.findViewById(R.id.iv_nodata);
}
}

v7 RecyclerView is legacy now and you should use the androidx package instead.
to do this, add the androidx RecyclerView dependency to build.gradle(Module:app) like this
dependencies {
...
implementation "androidx.recyclerview:recyclerview:1.2.1"
...
}
and then change it's head name in xml layout to this :
<androidx.recyclerview.widget.RecyclerView
... />
and it will work as intended.
N.B : three dots (...) in my code means that I don't care the code written here and you should include your code instead.
for more information about how to deal with androidx RecyclerView check this Android Developers Tutorial

Related

JS interface doesn't work with Android Kotlin

I am trying to implement JS interface in my WebView. I created a separate class with a method which calls listener, subsequently the string caught by listener should be put in the intent (in MainActivity) and intent finishes.
MainActivity.kt:
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import sbs.pros.app.databinding.ActivityMainBinding
typealias IDListener = (qr: String) -> Unit
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val answerIntent = Intent()
#SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPayBinding.inflate(layoutInflater)
val WebView = binding.webView
val webSettings: WebSettings = WebView.settings
WebView.settings.javaScriptEnabled = true
WebView.settings.javaScriptCanOpenWindowsAutomatically = true
webSettings.builtInZoomControls = false
WebView.webViewClient = WebViewClient()
WebView.webChromeClient = WebChromeClient()
WebView.addJavascriptInterface(WebAppInterface(this
) { id ->
answerIntent.putExtra("pay", id)
setResult(RESULT_OK)
finish()
}, "AndroidInterface")
WebView.setInitialScale(160)
WebView.loadUrl("https://pros.sbs/payment/create_payment.php?apicall=one_address")
setContentView(binding.root)
}
}
class WebAppInterface internal constructor(c: Context, listener: IDListener) {
var mContext: Context = c
fun WebAppInterface(context: Context) {
this.mContext = context
}
#JavascriptInterface
#SuppressWarnings("unused")
fun getID(id: String?, listener: IDListener) {
if (id != null) {
listener(id)
}
}
}
create_payment.php:
<script src="javascript.js">
function giveID(id) {
AndroidInterface.getID(id);
}
</script>
<?php
if(null !==filter_input(INPUT_GET, 'apicall')){
switch(filter_input(INPUT_GET, 'apicall')){
case 'one_address':
?>
<script src="javascript.js">
giveID('some_id');
</script>
<?php
break;
}
}
The intent then should finish, showing a result (String) in a separate TextView. Unfortunately, that does not happen and the result returned is null. Please help me to find the problem with the interface.

Populating Cards from Firebase to Kotlin App

Afternoon! For starters, I'm using Kotlin to build a tinder-like app with cards and a swiping function inside Android Studio.
I'm trying to populate these cards with an image and 2 text-fields with data from Firebase.. And I can't seem to do it. My difficulty with it seems trivial but it's tripping me up pretty bad.
It looks to me like the app is correctly reading the only 2 datasets currently in the database, evident by only showing 2 cards - but I can't get it to read and display the name, location and image of each of the datasets.
I've attached the CardAdapter.kt file where the values aren't getting read / updated here:
package com.sit708.coupledApp.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.sit708.coupledApp.R
import com.sit708.coupledApp.util.Dates
import com.sit708.coupledApp.activities.UserInfoActivity
class CardsAdapter(context: Context?, resourceId: Int, dates: List<Dates>): ArrayAdapter<Dates>(
context!!, resourceId, dates) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val date = getItem(position)
val finalView = convertView ?: LayoutInflater.from(context).inflate(R.layout.item, parent, false)
val name = finalView.findViewById<TextView>(R.id.nameTV)
val userInfo = finalView.findViewById<LinearLayout>(R.id.userInfoLayout)
val image = finalView.findViewById<ImageView>(R.id.photoIV)
/*THESE VALUES AREN'T GETTING READ, UPDATED OR DISPLAYED*/
name.text = "${date?.dateName}, ${date?.dateLocation}"
Glide.with(context)
.load(date?.dateImg)
.into(image)
userInfo.setOnClickListener {
finalView.context.startActivity(UserInfoActivity.newIntent(finalView.context, date?.dateID))
}
return finalView
}
}
Here you can see that the comma is being displayed but not the name or location
Here is my SwipeFragment.kt just in case this proves useful:
package com.sit708.coupledApp.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ValueEventListener
import com.lorentzos.flingswipe.SwipeFlingAdapterView
import com.sit708.coupledApp.R
import com.sit708.coupledApp.util.Dates
import com.sit708.coupledApp.activities.TinderCallback
import com.sit708.coupledApp.adapters.CardsAdapter
import com.sit708.coupledApp.databinding.FragmentSwipeBinding
import com.sit708.coupledApp.util.*
class SwipeFragment : Fragment() {
private var _binding: FragmentSwipeBinding? = null
private val binding get() = _binding!!
private var callback: TinderCallback? = null
private lateinit var dateId: String
private lateinit var dateDatabase: DatabaseReference
private lateinit var chatDatabase: DatabaseReference
private lateinit var userDatabase: DatabaseReference
private var cardsAdapter: ArrayAdapter<Dates>? = null
private var rowItems = ArrayList<Dates>()
private var dateName: String? = null
private var dateImg: String? = null
private var dateLocation: String? = null
fun setCallback(callback: TinderCallback) {
this.callback = callback
dateId = callback.onGetUserId()
userDatabase = callback.getUserDatabase()
chatDatabase = callback.getChatDatabase()
dateDatabase = callback.getDateDatabase()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSwipeBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dateDatabase.child(dateId).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
val date = p0.getValue(Dates::class.java)
dateName = date?.dateName
dateImg = date?.dateImg
dateLocation = date?.dateLocation
populateItems()
}
})
cardsAdapter = CardsAdapter(context, R.layout.item, rowItems)
binding.frame.adapter = cardsAdapter
binding.frame.setFlingListener(object : SwipeFlingAdapterView.onFlingListener {
override fun removeFirstObjectInAdapter() {
rowItems.removeAt(0)
cardsAdapter?.notifyDataSetChanged()
}
override fun onLeftCardExit(p0: Any?) {
var date = p0 as Dates
dateDatabase.child(date.dateID.toString()).child(DATA_SWIPES_LEFT).child(dateId).setValue(true)
}
override fun onRightCardExit(p0: Any?) {
val selectedDates = p0 as Dates
val selectedDateId = selectedDates.dateID
if (!selectedDateId.isNullOrEmpty()) {
dateDatabase.child(dateId).child(DATA_SWIPES_RIGHT)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
if (p0.hasChild(selectedDateId)) {
Toast.makeText(context, "Match!", Toast.LENGTH_SHORT).show()
val chatKey = chatDatabase.push().key
if (chatKey != null) {
dateDatabase.child(dateId).child(DATA_SWIPES_RIGHT).child(selectedDateId)
.removeValue()
dateDatabase.child(dateId).child(DATA_MATCHES).child(selectedDateId)
.setValue(chatKey)
dateDatabase.child(selectedDateId).child(DATA_MATCHES).child(dateId)
.setValue(chatKey)
chatDatabase.child(chatKey).child(dateId).child(DATA_DATE_NAME).setValue(dateName)
chatDatabase.child(chatKey).child(dateId).child(DATA_DATE_IMAGE)
.setValue(dateImg)
chatDatabase.child(chatKey).child(selectedDateId).child(DATA_NAME)
.setValue(selectedDates.dateName)
}
} else {
dateDatabase.child(selectedDateId).child(DATA_SWIPES_RIGHT).child(dateId)
.setValue(true)
}
}
})
}
}
override fun onAdapterAboutToEmpty(p0: Int) {
}
override fun onScroll(p0: Float) {
}
})
binding.likeButton.setOnClickListener {
if (rowItems.isNotEmpty()) {
binding.frame.topCardListener.selectRight()
}
}
binding.dislikeButton.setOnClickListener {
if (rowItems.isNotEmpty()) {
binding.frame.topCardListener.selectLeft()
}
}
}
fun populateItems() {
binding.noUsersLayout.visibility = View.GONE
binding.progressLayout.visibility = View.VISIBLE
val cardsQuery = dateDatabase
cardsQuery.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach { child ->
val date = child.getValue(Dates::class.java)
if (date != null) {
var showDate = true
if (child.child(DATA_SWIPES_LEFT).hasChild(dateId) ||
child.child(DATA_SWIPES_RIGHT).hasChild(dateId) ||
child.child(DATA_MATCHES).hasChild(dateId)
) {
showDate = false
}
if (showDate) {
rowItems.add(Dates())
cardsAdapter?.notifyDataSetChanged()
}
}
}
binding.progressLayout.visibility = View.GONE
if (rowItems.isEmpty()) {
binding.noUsersLayout.visibility = View.VISIBLE
}
}
})
}
}
Here is a screenshot of my database with only 2 sets of data that I'd like it to read from
If you need anymore info let me know and but any guidance would be greatly appreciated!
Small screenshot of my Data.kt file

Problem with user registration through Firebase - not saving data in Realtime Database‏

I'm developing a social networking app that uses subscribing and building a user profile through FareBas.
Unfortunately, the program works and when the user presses the register button, an error appears and the information does not go into real-time.
!I would be very grateful for the help.
Registration page:
package com.example.myapplicationfire;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Patterns;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
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.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class reg extends AppCompatActivity implements View.OnClickListener
{
EditText name, pass, email, bio;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
Button b,b1;
ProgressDialog p;
DatabaseReference myref = firebaseDatabase.getReference("Users");
ImageView pic;
Uri uri;
StorageReference storageReference;
String picName;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
name = findViewById(R.id.et1);
pass = findViewById(R.id.et2);
email = findViewById(R.id.et3);
bio = findViewById(R.id.et5);
b = findViewById(R.id.b1);
b.setOnClickListener(this);
b1 = findViewById(R.id.b2);
b1.setOnClickListener(this);
pic =findViewById(R.id.pic1);
pic.setImageResource(R.drawable.person);
pic.setOnClickListener(this);
sp=getSharedPreferences("details",0);
firebaseAuth = FirebaseAuth.getInstance();
}
public void createUser() {
p = new ProgressDialog(this);
p.setMessage("Registration...");
p.show();
if (isValidate())
firebaseAuth.createUserWithEmailAndPassword(email.getText().toString
(), pass.getText().toString()).addOnCompleteListener(this,
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull
Task<AuthResult> task) {
if (task.isSuccessful()) {
storageReference =
FirebaseStorage.getInstance().getReference("Image/Users/"+email.getText().toString().replace('.',' '));
storageReference = storageReference.child(picName);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener <UploadTask.TaskSnapshot>() {
#Override
public void
onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(reg.this, "תמונה הועלתה", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(reg.this, "" +
e.getMessage(), Toast.LENGTH_LONG).show(); }
});
myref=firebaseDatabase.getReference("users").push();
User u = new
User(name.getText().toString(), pass.getText().toString(),
email.getText().toString(), myref.getKey(),picName,bio.getText().toString());
myref.setValue(u);
p.dismiss();
Toast.makeText(reg.this, "ההרשמה הצליחה!", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(reg.this,
"" + e.getMessage(), Toast.LENGTH_LONG).show();
p.dismiss();
}
});
}
public boolean isValidate() {
if (!
Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches()) {
email.setError("Invalid email");
email.setFocusable(true);
return false;
} else if (pass.getText().toString().length() < 6) {
pass.setError("password length at least 6 characters");
pass.setFocusable(true);
return false;
}
else if (bio.getText().toString().length() < 10) {
bio.setError("bio length should be 10-100 characters");
bio.setFocusable(true);
return false;
}
return true;
}
#Override
public void onClick(View view) {
if (view == pic) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
}
if (view == b) {
createUser();
if(isValidate()){
sp=getSharedPreferences("details",0);
SharedPreferences.Editor editor=sp.edit();
editor.putBoolean("isChecked",true);
editor.putString("name",name.getText().toString());
editor.putString("bio",bio.getText().toString());
editor.putString("email",email.getText().toString());
editor.commit();
Intent intent = new Intent(reg.this, homepage.class);
intent.putExtra("email", email.getText().toString());
startActivity(intent);
}
}
if(view==b1){
Intent intent = new Intent(reg.this, login.class);
startActivity(intent);
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && requestCode == 0 && data.getData() != null) {
uri = data.getData();
if (uri != null) {
pic.setImageURI(uri);
picName = System.currentTimeMillis() + "." + getFileExtension(uri);
}
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public void ShowHidePass(View view) {
if (view.getId() == R.id.show_pass_btn) {
if (pass.getTransformationMethod().equals(PasswordTransformationMethod.getInstance())) {
((ImageView) (view)).setImageResource(R.drawable.showeye1);
//Show Password
pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
((ImageView) (view)).setImageResource(R.drawable.showeye);
//Hide Password
pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
}}
Error:
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.

How to insert a string after a specific section of another string

I'm working with a specific API that returns a class as a string to me. I need to insert a string at a certain block of the string that is given to me. So basically a function that takes the whole string, and appends the string I want to add to it after a specific block.
The string passed to me is a java class, and I want to basically enter my own function at the end of it after all of the existing functions. Incase you are confused.. I don't have access to the java file, this is the only way to modify the file when you are using config plugins in expo react native.
I believe some sort of regex is supposed to be used to get this result ? but really I have no idea how to target the specific part of the string.
The string I want to add:
'#Override\nprotected List getPackages() {\nreturn Arrays.asList(\nnew MainReactPackage(), // <---- add comma\nnew RNFSPackage() // <---------- add package\n);\n}'
The string that is passed to me
import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import androidx.annotation.NonNull;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import expo.modules.ApplicationLifecycleDispatcher;
import expo.modules.ReactNativeHostWrapper;
import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHostWrapper(
this,
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return DevLauncherController.getInstance().getUseDeveloperSupport();
}
#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());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
#Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();
}
});
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
DevLauncherController.initialize(this, getReactNativeHost());
if (BuildConfig.DEBUG) {
DevLauncherController.getInstance().setUpdatesInterface(UpdatesDevLauncherController.initialize(this));
}
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
ApplicationLifecycleDispatcher.onApplicationCreate(this);
}
#Override
public void onConfigurationChanged(#NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig);
}
<--- I WANT TO INSERT MY STRING HERE
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* #param context
* #param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.haibert.GitTest.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
const addToMainApp = (content) => {
const regexpPackagingOptions = /\s*?(?=\/\*\*\n \* Loads Flipper)/
const insertLocation = content.match(regexpPackagingOptions)
const newContent =
content.substring(0, insertLocation.index) +
'//INSERTED \n#Override\nprotected List<ReactPackage> getPackages() {\nreturn Arrays.<ReactPackage>asList(\nnew MainReactPackage(), // <---- add comma\nnew RNFSPackage() // <---------- add package\n);\n}' +
content.substring(insertLocation.index, content.length)
return newContent
}

Call php script inside java activity after click

I am parsing a JSON title, URL etc. from a PHP script. I want to give a reward with PHP script after the user click my link. Reward code -
String awr = Config.Base_Url+"videos/award.php";
Now everything is working, there is just no reward, no call to my PHP script...
How do i need modify my script to get correct reward? My java activity -
package com.uabclousy.pjanidemo;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.uabclousy.pjanidemo.app.App;
import com.uabclousy.pjanidemo.constants.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.content.Intent;
public class ItemsActivity extends BaseActivity {
private PrefManager prf;
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "https://pjani.com/ImageJsonData.php";
String Image_Name_JSON = "image_title";
String Image_Decription_JSON = "app_description";
String Image_URL_JSON = "image_url";
String App_URL_JSON = "app_url";
String App_Message_JSON = "app_message";
String App_Points = "app_points";
String App_Id = "videoId";
String App_sec = "id";
public static final String EXTRA_VIDEO_ID = "id";
public static final String EXTRA_ID = "id";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
ArrayList<String> AppmessageArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_items);
prf = new PrefManager(this);
getSupportActionBar().setIcon(R.drawable.ic_back_icon);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ImageTitleNameArrayListForClick = new ArrayList<>();
AppmessageArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
validate();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(ItemsActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(ItemsActivity.this, AppmessageArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
String url = ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition);
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra("points", App_Points);
intent.putExtra("vid", App_Id);
intent.putExtra("id", App_sec);
intent.putExtra("yourreq4", "fuck13");
setResult(RESULT_OK, intent);
finish();
startActivity(intent);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
void award_items(final String points, final String tostore, final String type){
String awr = Config.Base_Url+"videos/award.php";
final String v1 ="1";
final String v0 ="0";
final String v2 ="2";
StringRequest stringRequest = new StringRequest(Request.Method.POST, awr,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Enable this only on testing - yash
//Toast.makeText(VideosActivity.this, response, Toast.LENGTH_LONG).show();
if(response.intern() == v1.intern()) {
Toast.makeText(ItemsActivity.this, points+" "+getString(R.string.points_received), Toast.LENGTH_SHORT).show();
prf.setBoolean(tostore, true);
Intent intent = getIntent();
finish();
startActivity(intent);
}
if(response.intern() == v0.intern()) {
Toast.makeText(ItemsActivity.this, getString(R.string.already_watched), Toast.LENGTH_SHORT).show();
prf.setBoolean(tostore, true);
Intent intent = getIntent();
finish();
startActivity(intent);
}
if(response.intern() == v2.intern()){
Toast.makeText(ItemsActivity.this,getString(R.string.server_problem),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ItemsActivity.this,getString(R.string.server_problem),Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", App.getInstance().getUsername());
params.put("points",App_Points);
params.put("type",type);
params.put("videoid",Image_Name_JSON);
params.put("date","hehe");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_about, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
case R.id.share:
shareURL();
return true;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
// sharing
void shareURL() {
try
{ Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
String sAux = getString(R.string.share_text)+"\n";
sAux = sAux + "https://play.google.com/store/apps/details?id="+getApplicationContext().getPackageName()+"\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, getString(R.string.choose_one)));
}
catch(Exception e)
{ //e.toString();
}
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(ItemsActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageDescription(json.getString(Image_Decription_JSON));
// Opening link in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(App_URL_JSON));
// Adding message in array to display on RecyclerView click event.
AppmessageArrayListForClick.add(json.getString(App_Message_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setAppPoints(json.getString(App_Points));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
void validate(){
if (Config.Base_Url.intern() == Constants.API_License && !BuildConfig.DEBUG && Constants.release) {
App.getInstance().logout();
Intent i = new Intent(getApplicationContext(), AppActivity.class);
startActivity(i);
finish();
ActivityCompat.finishAffinity(ItemsActivity.this);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
award_items(data.getStringExtra("points"),data.getStringExtra("id"),getString(R.string.webpanel_credit));
// Toast.makeText(getApplicationContext(), data.getStringExtra("id"), Toast.LENGTH_SHORT).show();
}
}
}
}
Thank you very much for helping!

Categories

Resources