I'm following this Tutorial to create blog and I successfully Created the blog. In give Tutorial, he has used Empty Activity but I used Navigation drawer Activity.
So now I would like to put the User image and User name in nav header if he is signed in if not use the default image and name from drawable folder.
My Blog Recycle Adapter is
package com.nepalpolice.cdp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.android.volley.VolleyLog.TAG;
import static com.nepalpolice.cdp.webfaq.isNetworkStatusAvialable;
public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {
public List<BlogPost> blog_list;
public Context context;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private PopupWindow popWindow;
public BlogRecyclerAdapter(List<BlogPost> blog_list){
this.blog_list = blog_list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
context = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
final String blogPostId = blog_list.get(position).BlogPostId;
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);
String image_url = blog_list.get(position).getImage_url();
String thumbUri = blog_list.get(position).getImage_thumb();
holder.setBlogImage(image_url, thumbUri);
String user_id = blog_list.get(position).getUser_id();
//User Data will be retrieved here...
firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
String userName = task.getResult().getString("name");
String userImage = task.getResult().getString("image");
holder.setUserData(userName, userImage);
} else {
//Firebase Exception
}
}
});
try {
long millisecond = blog_list.get(position).getTimestamp().getTime();
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
holder.setTime(dateString);
} catch (Exception e) {
Toast.makeText(context, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
//Get Likes Count
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(((Main2Activity) context),new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e!=null) {
Log.w(TAG, "listening failed",e);
return;
}
if(!documentSnapshots.isEmpty()){
int count = documentSnapshots.size();
holder.updateLikesCount(count);
} else {
holder.updateLikesCount(0);
}
}
});
if (InternetStatus.getInstance(holder.blogLikeBtn.getContext()).isOnline()) {
//Get Likes
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context), new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "listening failed", e);
return;
}
if (documentSnapshot.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));
}
}
}
});
//Likes Feature
holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(!task.getResult().exists()){
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
} else {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
}
else{
Toast.makeText(context, "Check Internet", Toast.LENGTH_SHORT).show();
}
holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent commentIntent = new Intent(context, CommentsActivity.class);
context.startActivity(commentIntent);
}
});
}
#Override
public int getItemCount() {
return blog_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView descView;
private ImageView blogImageView;
private TextView blogDate;
private TextView blogUserName;
private CircleImageView blogUserImage;
private ImageView blogLikeBtn;
private TextView blogLikeCount;
private ImageView blogCommentBtn;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
blogLikeBtn = mView.findViewById(R.id.blog_like_btn);
blogCommentBtn = mView.findViewById(R.id.blog_comment_icon);
}
public void setDescText(String descText){
descView = mView.findViewById(R.id.blog_desc);
descView.setText(descText);
}
public void setBlogImage(String downloadUri, String thumbUri){
blogImageView = mView.findViewById(R.id.blog_image);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.image_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).thumbnail(
Glide.with(context).load(thumbUri)
).into(blogImageView);
}
}
public void setTime(String date) {
blogDate = mView.findViewById(R.id.blog_date);
blogDate.setText(date);
}
public void setUserData(String name, String image) {
blogUserImage = mView.findViewById(R.id.blog_user_image);
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
RequestOptions placeholderOption = new RequestOptions();
placeholderOption.placeholder(R.drawable.profile_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
}
}
public void updateLikesCount(int count){
blogLikeCount = mView.findViewById(R.id.blog_like_count);
blogLikeCount.setText(count + " Likes");
}
}
}
and my Mainactivity is
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
final Context context = this;
private boolean exit = false;
Dialog dialog;
private Menu mymenu;
private TextView blogUserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Fragment fragment = new main();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
//Create Dialog
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mymenu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
Intent intent = new Intent(MainActivity.this, UpdateService.class);
startService(intent);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
item.setActionView(iv);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
new UpdateTask(this).execute();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void resetUpdating()
{
// Get our refresh item from the menu
MenuItem m = mymenu.findItem(R.id.action_refresh);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if(m.getActionView()!=null)
{
// Remove the animation.
m.getActionView().clearAnimation();
m.setActionView(null);
}
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.store) {
String url = "https://play.google.com/store/apps/developer?id=Sagar%20Rawal&hl=en";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else if (id == R.id.contact) {
Intent activity_about = new Intent(this, profile.class);
startActivity(activity_about);
} else if (id == R.id.weather) {
Intent activity_weather = new Intent(this, com.nepalpolice.cdp.weather.MainActivity.class);
startActivity(activity_weather);
}
else if (id == R.id.resistor) {
Intent activity_weather = new Intent(this, com.nepalpolice.cdp.resistor.MainActivity.class);
startActivity(activity_weather);
}
else if (id == R.id.result) {
result fragment = new result();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_frame, fragment, "Main");
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
else if (id == R.id.pacman) {
Intent activity_about = new Intent(this, pacman.class);
startActivity(activity_about);
}
else if (id == R.id.tetris) {
Intent activity_about = new Intent(this, MenuActivity.class);
startActivity(activity_about);
}
else if (id == R.id.retro) {
Intent intent500 = new Intent(this, com.nepalpolice.cdp.brickgame.GameActivity.class);
startActivity(intent500);
}
else if (id == R.id.hangman) {
Intent activity_about = new Intent(this, GameActivity.class);
startActivity(activity_about);
}
else if (id == R.id.tictac) {
Intent activity_about = new Intent(this, MainMenuScreen.class);
startActivity(activity_about);
}
else if (id == R.id.home) {
main fragment = new main();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_frame, fragment, "Main");
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
else if (id == R.id.email) {
Intent activity_about = new Intent(this, Sendemail.class);
startActivity(activity_about);
} else if (id == R.id.call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+9779868336847"));
startActivity(intent);
} else if (id == R.id.share) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
"Hey check out this awesome app at: https://play.google.com/store/apps/details?id=com.nepalpolice.cdp");
sendIntent.setType("text/plain");
startActivity(sendIntent);
} else if (id == R.id.rate) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.nepalpolice.mnemonics&hl=en" + getPackageName())));
}
catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
(Uri.parse("https://play.google.com/store/apps/details?id=com.faraksoch.sagar.eroutine&hl=en"))));
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (exit)
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// MainActivity.super.onBackPressed();
finish();
moveTaskToBack(true);
}
}).create().show();
else {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
if (getSupportFragmentManager().getBackStackEntryCount() ==1) {
finish();
}
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 800);
}
}
}
I have no clue if it is possible or not but if it is please help. I have followed several post but none of it helped.
My Firebase Structure is
Related
I have fragment (FragmentUpload) containing several textviews and edittext. when user click on upload button (shown in image), user is sent to different fragment where user can chose from the options and the chosen string is displayed in appropriate textviews in Fragment Upload. My problem is when user click on different upload button to chose different string for different textview (from separate fragment), the code do not save the previous value. For instance, when user chooses artist from artist fragment, the textview displays the chosen artist. Now when user click on upload album button to choose album, the code only shows chosen album in textview associated with album but previously chosen string (artist string) is no longer available. please help me ( I am new to android and java)
package com.example.realsungjoen;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Handler;
import android.provider.OpenableColumns;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.Set;
public class FragmentUpload extends Fragment {
private static final int PICK_IMAGE_REQUEST = 1;
private final static int PICK_SONG_REQUEST = 2;
private Button mBtnChooseImg;
private Button mBtnUpload;
private Button mBtnChooseSong;
private Button cancelButton;
private ImageView addselectArtists;
private ImageView addSelectGenre;
private ImageView addSelectAlbum;
private ImageView addSelectLanguage;
private ImageView mImageView;
private EditText mEditTextFileName;
private TextView mSongFile;
private TextView selectedArtist;
private TextView selectedAlbum;
private TextView selectedGenre;
private TextView selectedLanguage;
private ProgressBar mProgressBar;
private Uri mImageUri;
private Uri uriImage;
private Uri mSongUri;
private StorageReference mStorageImageRef;
private DatabaseReference mDatabaseRef;
private DatabaseReference mDatabaseRefArtist;
private StorageReference mStorageSongRef;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View uploadViews = inflater.inflate(R.layout.fragment_upload, container,false);
mBtnChooseImg = uploadViews.findViewById(R.id.btn_chose_img);
mBtnChooseSong = uploadViews.findViewById(R.id.btn_choose_song);
mBtnUpload = uploadViews.findViewById(R.id.btn_upload);
cancelButton = uploadViews.findViewById(R.id.cancel_button);
mEditTextFileName = uploadViews.findViewById(R.id.edit_text_file_name);
mSongFile = uploadViews.findViewById(R.id.track_file_view);
mProgressBar = uploadViews.findViewById(R.id.progress_bar);
mImageView = uploadViews.findViewById(R.id.image_view);
addselectArtists = uploadViews.findViewById(R.id.addArtist_img);
addSelectGenre = uploadViews.findViewById(R.id.addGenre_img);
addSelectAlbum = uploadViews.findViewById(R.id.addAlbum_img);
addSelectLanguage = uploadViews.findViewById(R.id.addLanguage_img);
selectedArtist = uploadViews.findViewById(R.id.artists);
selectedAlbum = uploadViews.findViewById(R.id.album);
selectedGenre = uploadViews.findViewById(R.id.genre);
selectedLanguage = uploadViews.findViewById(R.id.language);
mStorageImageRef = FirebaseStorage.getInstance().getReference("Images");
mStorageSongRef = FirebaseStorage.getInstance().getReference("Songs");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("Data Uploads");
mDatabaseRefArtist = FirebaseDatabase.getInstance().getReference("Artists");
uriImage = Uri.parse("https://media.kasperskydaily.com/wp-content/uploads/sites/92/2019/12/09084248/android-device-identifiers-featured.jpg");
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
final Toolbar toolbar = uploadViews.findViewById(R.id.toolbar_upload);
toolbar.setTitle("Upload Songs");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySongFragment mySongFragment = new MySongFragment();
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (fragment == null){
fragmentManager.beginTransaction()
.add(R.id.fragment_container, mySongFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}else {
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, mySongFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}
((AppCompatActivity)getActivity()).getSupportActionBar().show();
}
});
mBtnChooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImageChooser();
}
});
mBtnChooseSong.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openSongChooser();
}
});
addselectArtists.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChooseArtistFragment chooseArtistFragment = new ChooseArtistFragment();
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, chooseArtistFragment)
.addToBackStack(null)
.commit();
}
});
addSelectGenre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//go to choose/select genre here
ChooseGenreFragment chooseGenreFragment = new ChooseGenreFragment();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container,chooseGenreFragment)
.addToBackStack(null)
.commit();
}
});
addSelectAlbum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChooseAlbumFragment chooseAlbumFragment = new ChooseAlbumFragment();
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, chooseAlbumFragment)
.addToBackStack(null)
.commit();
}
});
addSelectLanguage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChooseLanguageFragment chooseLanguageFragment = new ChooseLanguageFragment();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container,chooseLanguageFragment)
.addToBackStack(null)
.commit();
}
});
mBtnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadFile();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new MySongFragment())
.remove(new FragmentUpload())
.addToBackStack(null)
.commit();
ViewGroup mContainer = getActivity().findViewById(R.id.uploadFragment);
mContainer.removeAllViews();
((AppCompatActivity)getActivity()).getSupportActionBar().show();
}
});
return uploadViews;
}
#Override
public void onStart() {
super.onStart();
Bundle bundle = this.getArguments();
if (bundle == null){
selectedArtist.setText("No Artist Selected");
selectedGenre.setText("No Genre Selected");
selectedLanguage.setText("No Language Selected");
selectedAlbum.setText("No Album Selected");
return;
}
String string = "";
for (String key : bundle.keySet()){
string += key;
switch (string){
case "artistList":
String myValue = bundle.getString("artistList");
selectedArtist.setText(myValue);
break;
case "albumList":
String myValue1 = bundle.getString("albumList");
selectedAlbum.setText(myValue1);
break;
case "langaugeList":
String myValue2 = bundle.getString("languageList");
selectedLanguage.setText(myValue2);
break;
case "genreList":
String myValue3 = bundle.getString("genreList");
selectedGenre.setText(myValue3);
break;
}
}
}
private void openSongChooser(){
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_SONG_REQUEST);
}
private void openImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK
&& data != null && data.getData() != null){
mImageUri = data.getData();
Picasso.get().load(mImageUri).resize(1000,1000).centerCrop().into(mImageView);
// mImageView.setImageURI(mImageUri);
}
if (requestCode == PICK_SONG_REQUEST && resultCode ==Activity.RESULT_OK
&& data != null && data.getData() != null){
mSongUri = data.getData();
Cursor cursor = getActivity().getContentResolver().query(mSongUri,null,null,null,null);
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
String mimeType = getFileExtension(mSongUri);
cursor.moveToFirst();
mSongFile.setText(cursor.getString(nameIndex)+"."+ mimeType);
}
}
private String getFileExtension(Uri uri){
ContentResolver cR = getActivity().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile(){
if (mImageUri != null){
StorageReference fileReferece = mStorageImageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
fileReferece.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 5000);
Toast.makeText(getActivity(), "Image Upload Successful", Toast.LENGTH_SHORT).show();
Task<Uri> uriTaskImage = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTaskImage.isSuccessful());
Uri downloadUriImage = uriTaskImage.getResult();
uriImage = downloadUriImage;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int)progress);
}
});
}else{
Toast.makeText(getActivity(), "No Image File Selected", Toast.LENGTH_SHORT).show();
}
if (mSongUri != null){
StorageReference fileRef = mStorageSongRef.child(System.currentTimeMillis()
+"." + getFileExtension(mSongUri));
fileRef.putFile(mSongUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 5000);
Toast.makeText(getActivity(), "Track Upload Successful", Toast.LENGTH_SHORT).show();
Task<Uri> uriTaskSong = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTaskSong.isSuccessful());
Uri downloadUriSong = uriTaskSong.getResult();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
downloadUriSong.toString(),uriImage.toString(), selectedArtist.getText().toString().trim());
String uploadIdSong = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadIdSong).setValue(upload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int)progress);
}
});
}else {
Toast.makeText(getActivity(), "No Song File Selected", Toast.LENGTH_SHORT).show();
}
}
}
refrence image
Here is my code.
I try to add OnItenClickListener to "lastCommand" listView but it is not responde. Any errors at compile.
package pl.globoox.sprawdzsprzedawce;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import pl.globoox.sprawdzsprzedawce.Utils.LastCommentHome;
import pl.globoox.sprawdzsprzedawce.Utils.QueryCheck;
import static pl.globoox.sprawdzsprzedawce.R.id.buttonCheckButton;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ListView lastComments;
LoginButton loginButton;
CallbackManager callbackManager;
ArrayList<String> comments_userList = new ArrayList();
ArrayList<String> comments_olxUserList = new ArrayList();
ArrayList<String> comments_dateList = new ArrayList();
ArrayList<String> comments_messageList = new ArrayList();
ArrayList<String> comments_statusList = new ArrayList();
ImageView imageViewFBUser;
TextView textViewFBName;
TextView textViewFBEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
initializeControls();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
loginWithFb();
// MENU DRAWER
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
textViewFBName = headerView.findViewById(R.id.textViewFBName);
textViewFBEmail = headerView.findViewById(R.id.textViewFBEmail);
imageViewFBUser = headerView.findViewById(R.id.imageViewFBUser);
imageViewFBUser.setVisibility(View.INVISIBLE);
textViewFBName.setText("");
textViewFBEmail.setText("");
// MAIN CONTENT APP
final SearchView editTextOfferLink = (SearchView) findViewById(R.id.editTextOfferLink);
final Button buttonCheck = (Button) findViewById(buttonCheckButton);
lastComments = (ListView) findViewById(R.id.listViewLastComments);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String offerLink = editTextOfferLink.getQuery().toString();
boolean error = false;
// CHECK FORM EMPTY
if (offerLink.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.formEmpty).setNegativeButton(R.string.tryAgain, null).create().show();
error = true;
return;
}
if (error == false) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
String userID = jsonResponse.getString("userID");
// CANT CONNECT TO DATABASE
if (errorCode == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.cantConnectToDatabase).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER NOT FOUND
else if (errorCode == 2) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), AddNewUserActivity.class);
if (isBank == true) {
i.putExtra("isBank", "true");
} else {
i.putExtra("isBank", "false");
}
String userName = jsonResponse.getString("userName");
String registerDate = jsonResponse.getString("registerDate");
i.putExtra("userID", userID);
i.putExtra("userName", userName);
i.putExtra("registerDate", registerDate);
finish();
startActivity(i);
}
// EMPTY OFFER VARIABLE
else if (errorCode == 3) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.omptyOfferVariable).setNegativeButton(R.string.tryAgain, null).create().show();
}
// BAD LINK
else if (errorCode == 4) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.badOfferLink).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER FOUND!
else if (errorCode == 5) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), UserAreaActivity.class);
i.putExtra("userID", userID);
i.putExtra("isBank", isBank.toString());
finish();
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
QueryCheck offerQueryRequest = new QueryCheck(offerLink, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(offerQueryRequest);
}
}
});
// LAST COMMENTS SHOW
Response.Listener<String> responseListenerLastComments = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
int count = jsonResponse.getInt("count");
Log.d("Tag", String.valueOf(errorCode));
JSONArray commentsArray = jsonResponse.getJSONArray("comments");
Log.d("TAG", String.valueOf(commentsArray));
for (int i = 0; i < count; i++) {
JSONObject jsonObject = commentsArray.getJSONObject(i);
comments_userList.add(jsonObject.getString("user"));
comments_olxUserList.add(jsonObject.getString("olxUser"));
comments_dateList.add(jsonObject.getString("date"));
comments_messageList.add(jsonObject.getString("message"));
comments_statusList.add(jsonObject.getString("status"));
}
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
lastComments.setAdapter(customAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LastCommentHome lastCommentHome = new LastCommentHome("3", responseListenerLastComments);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(lastCommentHome);
}
private void loginWithFb() {
// LOGIN MANAGER FACEBOOK
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
String name = me.optString("name");
String picture = me.optString("picture");
imageViewFBUser.setVisibility(View.VISIBLE);
imageViewFBUser.setImageURI(Uri.parse(picture));
textViewFBName.setText(name);
textViewFBEmail.setText(email);
}
}
}).executeAsync();
}
#Override
public void onCancel() {
textViewFBName.setText("Login canceled!");
}
#Override
public void onError(FacebookException error) {
textViewFBName.setText("Login error: " + error.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
// FACEBOOK INITALZIZE LOGIN
private void initializeControls() {
callbackManager = CallbackManager.Factory.create();
loginButton = findViewById(R.id.login_button);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_search) {
// Handle the camera action
} else if (id == R.id.nav_best) {
} else if (id == R.id.nav_worst) {
} else if (id == R.id.nav_comments) {
} else if (id == R.id.nav_policy) {
} else if (id == R.id.nav_rules) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contact) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
lastComments.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Log.d("asdasdxxxxx", String.valueOf(position));
}});
return convertView;
}
}
}
You can create your own interface :
private interface OnListItemClickListener
{
void onListItemClicked(View view, int position);
}
Then use it in your adapter class this way:
class CustomAdapter extends BaseAdapter {
//create an instance
private OnListItemClickListener onListItemClickListener;
//define the object setter
void setOnListItemClickListener(OnListItemClickListener listener)
{
this.onListItemClickListener=listener;}
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
//Then here trigger
convertView.setOnClickListener(new View.OnClickListener()
{
#override
void onClick(View v)
{
onListItemClickListener.onListItemClicked(v,position);
//you may be asked to set position as final
}
});
return convertView;
}
}
Then in your onCreate method where you attached the adapter, set the listener to your adapter:
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
customAdapter.setOnListItemClickListener(new OnListItemClickListener()
{
#override
void onListItemClicked(View view,int position)
{
//then here place your desired action
}
});
lastComments.setAdapter(customAdapter);
I hope this may be helpful. You can still ask for clarifications in comment
I have a webview fragment in my MainActivity. I am trying to add Swipetoview inside it. But when I load the fragment it doesn't load the url.
My fragment:
// Inflate the layout for this fragment
View vDriver=inflater.inflate(R.layout.fragment_drivers, container, false);
mWebView = vDriver.findViewById(R.id.drivers_webview);
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
// Enable Javascript
//WebSettings webSettings = mWebView.getSettings();
//webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
swipeLayout = vDriver.findViewById(R.id.fragment_drivers);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
});
return vDriver;
My fragment layout:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_drivers"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Drivers">
<WebView
android:id="#+id/drivers_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
I tried different things and this is the last code I tried. What am I doing wrong?
Thanks for your time in advance.
EDIT: MainActivity
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, HomeFragment.OnFragmentNavListener,Drivers.OnDriverNavigationListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 0 ;
private SignInButton btn_signin;
private TextView nameText;
private TextView emailText;
private ImageView imgProfilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment fragment = new HomeFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navHeader1 = navigationView.getHeaderView(0);
btn_signin = navHeader1.findViewById(R.id.signin_btn);
View navHeader3 = navigationView.getHeaderView(0);
nameText = navHeader3.findViewById(R.id.name);
View navHeader4 = navigationView.getHeaderView(0);
emailText = navHeader4.findViewById(R.id.email);
View navHeader5 = navigationView.getHeaderView(0);
imgProfilePic = navHeader5.findViewById(R.id.imgProfilePic);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
btn_signin.setVisibility(View.GONE);
if(user.getDisplayName() != null) {
nameText.setText(user.getDisplayName());
nameText.setVisibility(View.VISIBLE);
}
emailText.setText(user.getEmail());
emailText.setVisibility(View.VISIBLE);
imgProfilePic.setVisibility(View.VISIBLE);
Picasso.get().load(user.getPhotoUrl())
.into(imgProfilePic);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(false);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(true);
}
else {
nameText.setVisibility(View.GONE);
emailText.setVisibility(View.GONE);
btn_signin.setVisibility(View.VISIBLE);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(true);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(false);
imgProfilePic.setVisibility(View.GONE);
}
}
};
btn_signin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn () {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// deneme
}
}
}
#Override
public void onStop() {
super.onStop();
if(mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
signIn();
} else if (id == R.id.nav_send2) {
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "Çıkış yaptınız.", Toast.LENGTH_SHORT).show();
}
});
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentNav(int position) {
Fragment navFragment = null;
switch (position) {
case 0:
navFragment = new HomeFragment();
break;
case 1:
navFragment = new Drivers();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, navFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onDriverNavigation(int asd) {
}
}
HomeFragment.java
package com.ahmetbarpa.grandprix;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class HomeFragment extends Fragment {
private OnFragmentNavListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v1 =inflater.inflate(R.layout.fragment_home, container, false);
Button profile= v1.findViewById(R.id.button1);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
onButtonSelected(1);
}
});
Button education= v1.findViewById(R.id.button2);
education.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Takımlar ve arabalar",Toast.LENGTH_SHORT).show();
}
});
Button health= v1.findViewById(R.id.button3);
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Pistler",Toast.LENGTH_SHORT).show();
}
});
Button goals= v1.findViewById(R.id.button4);
goals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Sıralama",Toast.LENGTH_SHORT).show();
}
});
Button finance= v1.findViewById(R.id.button5);
finance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Grand Prix Tarihi",Toast.LENGTH_SHORT).show();
}
});
Button comfort= v1.findViewById(R.id.button6);
comfort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"GP kart oyunu",Toast.LENGTH_SHORT).show();
}
});
return v1;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonSelected(int position) {
if (mListener != null) {
mListener.onFragmentNav(position);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentNavListener) {
mListener = (OnFragmentNavListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentNav");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentNavListener {
void onFragmentNav(int position);
}
}
Instead of reload()
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
Try it..
If this is not the way you want, the second method is:
make a new class as:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
then, Instead of this:
mWebView.setWebViewClient(new WebViewClient());
write this:
mWebView.setWebViewClient(new MyBrowser());
Hopefully your problem will be solved
I got my MainActivity class extends as AppCompatActivity but I want to add a new activity as below. I tried to use intent to add it into the MainActivity. However, when I open the app, it crashes when I trigger the function. Here are the codes for two activities.
MainActivity.java
package com.michael.jared.navigationdrawerloginsqlite;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.michael.jared.navigationdrawerloginsqlite.database.DatabaseManagerUser;
import com.michael.jared.navigationdrawerloginsqlite.entity.User;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DatabaseManagerUser databaseManagerUser;
private User itemUsuario;
private String ident;
public ViewPagerActivity vpa;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//se agrego codigo del 39 al 68
Bundle b = getIntent().getExtras();
ident = b.getString("IDENT");
databaseManagerUser= new DatabaseManagerUser(getApplicationContext());
itemUsuario = databaseManagerUser.getUsuario(ident); // encuentra al usuario registrado en la bbdd
View header = ((NavigationView)findViewById(R.id.nav_view)).getHeaderView(0);
((TextView) header.findViewById(R.id.tv_nombre_usuario_menu)).setText(itemUsuario.getNombre());
((TextView) header.findViewById(R.id.tv_correo_menu)).setText(itemUsuario.getCorreo());
Bitmap bitmapsinfoto = BitmapFactory.decodeResource(getResources(),R.drawable.imagen);
RoundedBitmapDrawable roundedBitmapDrawablesinfoto = RoundedBitmapDrawableFactory.create(getResources(), bitmapsinfoto);
roundedBitmapDrawablesinfoto.setCircular(true);
((ImageView) header.findViewById(R.id.imageView)).setImageDrawable(roundedBitmapDrawablesinfoto);
if(itemUsuario.getBytes()!=null){
byte[] foodImage = itemUsuario.getBytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
((ImageView) header.findViewById(R.id.imageView)).setImageBitmap(bitmap);
Bitmap bitmap2 = ((BitmapDrawable)((ImageView) header.findViewById(R.id.imageView)).getDrawable()).getBitmap();
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap2);
roundedBitmapDrawable.setCircular(true);
((ImageView) header.findViewById(R.id.imageView)).setImageDrawable(roundedBitmapDrawable);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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 = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
} else if (id == R.id.nav_fourth_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FourthFragment())
.commit();
} else if (id == R.id.nav_share) {
startActivity(new Intent(this, ViewPagerActivity.class));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
ViewPagerActivity.java
package com.michael.jared.navigationdrawerloginsqlite;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;
#SuppressLint("NewApi")
public class ViewPagerActivity extends FragmentActivity implements
ScrollTabHolder, ViewPager.OnPageChangeListener {
public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK_INT).intValue() < 11;
private View mHeader;
private PagerSlidingTabStrip mPagerSlidingTabStrip;
private ViewPager mViewPager;
private PagerAdapter mPagerAdapter;
private int mMinHeaderHeight;
private int mHeaderHeight;
private int mMinHeaderTranslation;
private TextView info;
private int mLastY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
mMinHeaderTranslation = -mMinHeaderHeight;
setContentView(R.layout.activity_main);
mHeader = findViewById(R.id.header);
info = (TextView) findViewById(R.id.info);
mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(4);
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mPagerAdapter.setTabHolderScrollingContent(this);
mViewPager.setAdapter(mPagerAdapter);
mPagerSlidingTabStrip.setViewPager(mViewPager);
mPagerSlidingTabStrip.setOnPageChangeListener(this);
mLastY=0;
}
#Override
public void onPageScrollStateChanged(int arg0) {
// nothing
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffsetPixels > 0) {
int currentItem = mViewPager.getCurrentItem();
SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
ScrollTabHolder currentHolder;
if (position < currentItem) {
currentHolder = scrollTabHolders.valueAt(position);
} else {
currentHolder = scrollTabHolders.valueAt(position + 1);
}
if (NEEDS_PROXY) {
// TODO is not good
currentHolder.adjustScroll(mHeader.getHeight() - mLastY);
mHeader.postInvalidate();
} else {
currentHolder.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()));
}
}
}
#Override
public void onPageSelected(int position) {
SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
ScrollTabHolder currentHolder = scrollTabHolders.valueAt(position);
if(NEEDS_PROXY){
//TODO is not good
currentHolder.adjustScroll(mHeader.getHeight()-mLastY);
mHeader.postInvalidate();
}else{
currentHolder.adjustScroll((int) (mHeader.getHeight() +mHeader.getTranslationY()));
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount, int pagePosition) {
if (mViewPager.getCurrentItem() == pagePosition) {
int scrollY = getScrollY(view);
if(NEEDS_PROXY){
//TODO is not good
mLastY=-Math.max(-scrollY, mMinHeaderTranslation);
info.setText(String.valueOf(scrollY));
mHeader.scrollTo(0, mLastY);
mHeader.postInvalidate();
}else{
mHeader.setTranslationY(Math.max(-scrollY, mMinHeaderTranslation));
}
}
}
#Override
public void adjustScroll(int scrollHeight) {
// nothing
}
public int getScrollY(AbsListView view) {
View c = view.getChildAt(0);
if (c == null) {
return 0;
}
int firstVisiblePosition = view.getFirstVisiblePosition();
int top = c.getTop();
int headerHeight = 0;
if (firstVisiblePosition >= 1) {
headerHeight = mHeaderHeight;
}
return -top + firstVisiblePosition * c.getHeight() + headerHeight;
}
public static float clamp(float value, float max, float min) {
return Math.max(Math.min(value, min), max);
}
public class PagerAdapter extends FragmentPagerAdapter {
private SparseArrayCompat<ScrollTabHolder> mScrollTabHolders;
private final String[] TITLES = { "Page 1", "Page 2", "Page 3", "Page 4"};
private ScrollTabHolder mListener;
public PagerAdapter(FragmentManager fm) {
super(fm);
mScrollTabHolders = new SparseArrayCompat<ScrollTabHolder>();
}
public void setTabHolderScrollingContent(ScrollTabHolder listener) {
mListener = listener;
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
ScrollTabHolderFragment fragment = (ScrollTabHolderFragment) SampleListFragment.newInstance(position);
mScrollTabHolders.put(position, fragment);
if (mListener != null) {
fragment.setScrollTabHolder(mListener);
}
return fragment;
}
public SparseArrayCompat<ScrollTabHolder> getScrollTabHolders() {
return mScrollTabHolders;
}
}
}
I am trying to get the result value in a string after there has been scanned.
but it wont work.
I already figured out how to put it in a toast(maketext) that works but a string I cant figure it out.
here's the code please help me.
cpackage com.example.stage.absa;
import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.Result;
import java.io.IOException;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.net.Uri;
import java.net.URL;
public class MainActivity extends AbsRuntimePermission {
String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZxingScannerResultHandler());
setContentView(scannerView);
scannerView.startCamera();
}
class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}
remove the String declaration and instead move it as a class member
public void handleResult(Result result) {
//String resultCode = result.getText();
resultCode = result.getText();
like:
myClass extends Activity... {
String resultCode;
}
now you can assign the result code in the hadnleResult callback and use it in the same activity whenever you need it!
Edit:
you have an inner class, i would get rid of that and directly implement the ZXingScannerView.ResultHandler interface:
example:
public class MainActivity extends AbsRuntimePermission implements ZXingScannerView.ResultHandler{
private String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
//scannerView.setResultHandler(new ZxingScannerResultHandler());
scannerView.setResultHandler(this);
setContentView(scannerView);
scannerView.startCamera();
}
//class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
//}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}
I will go with this or something similar, depending on how you are handling the scanner view
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private String resultCode;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
resultCode = rawResult.getText();
//now use resultCode
}
}