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.
Related
I have been trying to add a Navigation Drawer Activity to my code, I followed an old tutorial that upon creation didn't create fragments, but I tried to make ti work none the less, I think I did everything right but when opening then emulator, the app doesn't take me to the activity but to the launcher one(?), is it the emulator or is it the code?
Navigation Drawer:
public class NavigationDrawerActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Options");
setSupportActionBar(toolbar);
//Init. Firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//Set name for User
View HeaderView = navigationView.getHeaderView(0);
txtFullName = findViewById(R.id.txtFullName);
if (Common.currentUser != null) {
txtFullName.setText(Common.currentUser.getName());
finish();
} else if (Common.CurrentFirebaseUser != null) {
txtFullName.setText(Common.CurrentFirebaseUser.getDisplayName());
finish();
}
//Load Options
recyclerView = findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadFilter();
}
private void loadFilter() {
FirebaseRecyclerAdapter<Category,FilterViewHolder> adapter = new FirebaseRecyclerAdapter<Category, FilterViewHolder>(Category.class, R.layout.filter_item, FilterViewHolder.class, category) {
#Override
protected void populateViewHolder(FilterViewHolder filterViewHolder, Category category, int i) {
FilterViewHolder.txtFilterName.setText(category.getName());
Picasso.with(getBaseContext()).load(category.getImage())
.into(filterViewHolder.imageView);
Category clickItem = category;
filterViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(NavigationDrawerActivity.this, ""+ clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
SignIn leading to the Navigation Drawer (ignore the login logic):
public class SignIn extends AppCompatActivity {
private static final int RC_SIGN_IN = 1;
Button btnSignIn;
ImageView btnGoogle;
EditText edtTxtPhone, edtTxtPassword;
private static final String TAG = "SignIn";
private FirebaseAuth mAuth;
private boolean noError = false;
private GoogleSignInClient mGoogleSignInClient;
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Intent intent = new Intent(SignIn.this, NavigationDrawerActivity.class);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
btnSignIn = findViewById(R.id.btnSignIn);
btnGoogle = findViewById(R.id.btnGoogle);
edtTxtPhone = findViewById(R.id.edtTxtPhone);
edtTxtPassword = findViewById(R.id.edtTxtPassword);
//Initialize Firebase
FirebaseDatabase database = FirebaseDatabase.getInstance("https://app-delivery-tutorial-default-rtdb.europe-west1.firebasedatabase.app");
DatabaseReference table_user = database.getReference("User");
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkCredentials();
ProgressDialog mDialog = new ProgressDialog(SignIn.this);
mDialog.setMessage("Signin In...");
mDialog.show();
if (noError) {
table_user.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
mDialog.dismiss();
//Check If User Does Exist First
if (snapshot.child(edtTxtPhone.getText().toString()).exists()) {
//Get User Information
User user = snapshot.child(edtTxtPhone.getText().toString()).getValue(User.class);
if (user.getPassword().equals(edtTxtPassword.getText().toString())) {
Intent successfulLogIn = new Intent(SignIn.this, NavigationDrawerActivity.class);
Common.currentUser = user;
startActivity(successfulLogIn);
} else {
Toast.makeText(SignIn.this, "Sign In Failed", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(SignIn.this, "User Not Found, Please Register First", Toast.LENGTH_SHORT).show();
Log.w(TAG, "Failed to read value.");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(SignIn.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
});
} else {
mDialog.dismiss();
Toast.makeText(SignIn.this, "Wrong Phone Number Or Password Input", Toast.LENGTH_SHORT).show();
}
}
});
//Initialize Google Firebase
mAuth = FirebaseAuth.getInstance();
createRequestGoogle();
btnGoogle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SignInGoogle();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
Toast.makeText(this, "Activity Has Been Succesful", Toast.LENGTH_SHORT).show();
} catch (ApiException e) {
Log.w(TAG, "Google Sign In Failed", e);
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(SignIn.this, NavigationDrawerActivity.class);
Common.CurrentFirebaseUser = user;
startActivity(intent);
}
}
});
}
private void SignInGoogle() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void createRequestGoogle() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void checkCredentials() {
String username = edtTxtPhone.getText().toString();
String password = edtTxtPassword.getText().toString();
if (username.isEmpty() || username.length() < 9) {
showError(edtTxtPhone, "Your Phone Number must have at least 9 character");
} else if (password.isEmpty() || password.length() < 4) {
showError(edtTxtPassword, "Your password must have at least 4 character");
} else {
noError = true;
}
}
private void showError(EditText editText, String s) {
editText.setError(s);
editText.requestFocus();
}
}
I tried to see if the fragments created were the problem, if the NavigationDrawerActivity should use an other xml file or if I was missing some logic, but I still don't understand why it would take me to the Launcher Activity instead of the NavigationDrawer one, the SignIn logic does work with other activities other than the NavigationDrawer one
I have created an application where it scans bar codes and QR codes on the phone and send an email of the collected data to my personal email which is a gmail. However, recently it stopped sending emails and prompted me an error as shown below:
javax.mail.authenticationfailedexception: [EOF]
NOTE: I am relatively new at this
I have been told to change it from SMTP to SSL but I cant seem to fix the issue.
package com.example.createexcelsample;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.nio.charset.Charset;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import static android.content.ContentValues.TAG;
public class SendMail extends AsyncTask<Void, Void, Void> {
private Context context;
private Session session;
private String email;
private String subject;
private String message;
private String fileName;
private MyWebServiceResult listener;
public String SendError = "";
private ProgressDialog progressDialog;
private String email_uid = "EMAIL";//Email written here
private String email_pwd = "123456";
/*URL url = new URL("https://office365.com");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
//copyInputStreamToOutputStream(in, System.out);*/
public interface MyWebServiceResult {
public void onSendIsComplete();
public void onSendError(String Error);
}
public void setWebServiceResult(MyWebServiceResult listener) {
this.listener = listener;
}
public SendMail(Context context, String email, String subject, String message,String fileName,String email_uid, String email_pwd){
//this.email_uid = email_uid;
//this.email_pwd = email_pwd;
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
this.fileName = fileName;
this.listener = null;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//props.put("mail.smtp.host", "smtp.gmail.com");
/* props.put("mail.smtp.host", "212.12.184.20");
props.put("mail.smtp.port", "110");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");*/
//props.put("mail.smtp.ssl.trust", "212.12.184.20");
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email_uid, email_pwd);
}
});
try {
MimeMessage mm = new MimeMessage(session);
mm.setFrom(new InternetAddress(email_uid));
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
mm.setSubject(subject);
mm.setText("body");
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
mm.setContent(multipart);
SendError = "";
Transport.send(mm);
}
catch (MessagingException e) {
SendError = e.toString().toString();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// progressDialog.dismiss();
if (SendError.toString().isEmpty()){
listener.onSendIsComplete();
} else {
listener.onSendError(SendError);
}
}
/* public void hideSoftKeyboard(AutoProgramingValid activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
AutoProgramingValid.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}*/
}
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
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!
When I click the ListView, I'd like to start a new Activity
Here is my MainActivity.java
package com.theheran.listviewicon;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
//Declarasi Array Menu dan gambar
ListView list;
String[] menu = {
"#The_Heran",
"www.theheran.com",
"Add",
"Delete",
"Next",
"Back",
"Find",
"Warning"
} ;
Integer[] imageId = {
R.drawable.ic_launcher,
R.drawable.signal,
R.drawable.add,
R.drawable.trash,
R.drawable.next,
R.drawable.back,
R.drawable.find,
R.drawable.warning
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomListView adapter = new
CustomListView(MainActivity.this, menu, imageId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +menu[+ position], Toast.LENGTH_SHORT).show();
// HERE THE PROBLEM (Intent)
Intent intent = new CustomListView(MainActivity.this,);
startActivity(intent);
}
});
}
}
My CustomListView
package com.theheran.listviewicon;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomListView extends ArrayAdapter<String> {
//Declarasi
private final Activity context;
private final String[] web;
private final Integer[] imageId;
public CustomListView(Activity context,String[] web, Integer[] imageId) {
super(context, R.layout.list_single_data, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
//Load Custom Layout untuk list
View rowView= inflater.inflate(R.layout.list_single_data, null, true);
//Declarasi komponen
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtList);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgIcon);
//Set Parameter Value
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
// HERE THE PROBLEM (Intent)
Intent intent = new CustomListView(MainActivity.this,);
startActivity(intent);
Here you are trying to use a wrong structure.
Use this:
Intent intent = new Intent(MainActivity.this, NextActivity.class);
MainActivity.this.startActivity(intent );
Try this way ,
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +position , Toast.LENGTH_SHORT).show();
Intent MoveToNext = new Intent(getApplicationContext(), Your_Next_Activity.class);
startActivity(MoveToNext);
}
});
This is how I have done it. You start a new activity using the startActivityForResult(intent, 2); Where you throw a intent and a number (number that you check for when you go back to the starting page).
private void registerButtonClickList() {
ListView list = (ListView) findViewById(R.id.listView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(InThisClass.this, GoingToThisClass.class);
intent.putExtra("Position", position);
startActivityForResult(intent, 0);
}
});
}
Use this where in the same class as you started the other one form the list. This is needed since you are expecting a return when you start with startActivityForResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
//See what u should do using the requestCode
//and check if it ended OK
}
if (resultCode == Activity.RESULT_CANCELED) {
//what you do when canceled
}
}
}
And in the activity that you started you need to end with this because you are expected to return something. This you do by using setResult().
Button btn = (Button) findViewById(R.id.btn);
btnCANCEL.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
public void onClick(View v) {
Intent intent = new Intent();
setResult(Activity.RESULT_OK, intent);
//intent.putExtra("something", something); if you need to send something back
finish();
}
});
Hope this helps!