I am trying to read a value from a database but does not seem to be working. The purpose of the code is to take in a counter value from a user's UID in Firebase, that will change the source of an image. The counter is changed in another activity and works fine. I feel I am close but not sure what do do next. I have tried to print out the value but it does not print in the console.
Full disclaimer, I am new to android development and firebase so I apologise in advance if it is a simple mistake/correction.
Activity calling the database UPDATED:
public class Menu extends AppCompatActivity {
private static final String TAG = "Menu";
Button btn;
public ImageView image;
public static int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Add an image
image = findViewById(R.id.imageView2);
image.setImageResource(R.drawable.g1);
//image.setImageResource(getIntent().getIntExtra("myImageResource",R.drawable.g1));
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("counter");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
menuCounter uCount = dataSnapshot.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).getValue(menuCounter.class);
System.out.println("Simon says" + uCount.counter);
counter = uCount.counter;
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
System.out.println("Counter is: " + counter);
if (counter == 1) {
image.setImageResource(R.drawable.g2);
}
btn = findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent WIP = new Intent(Menu.this, WIP.class);
startActivity(WIP);
}
});
}
}
Getter class:
package com.alanlyne.tbm;
public class menuCounter {
int counter;
public menuCounter() {
}
public menuCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return counter;
}
}
Activity changing the counter value:
public class WIP extends AppCompatActivity {
Button btn;
DatabaseReference databaseName;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wip);
databaseName = FirebaseDatabase.getInstance().getReference("counter");
btn = findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Menu.counter = 1;
Intent act2= new Intent(WIP.this,Menu.class);
// act2.putExtra("myImageResource", R.drawable.g2);
startActivity(act2);
addCounter();
}
});
}
private void addCounter() {
Menu.counter = 1;
String id = databaseName.push().getKey();
menuCounter counter = new menuCounter(Menu.counter);
databaseName.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(counter);
}
}
Firebase image:
Related
Stories progress class
How can I show all my pictures in arraylist coming from firebase as it is displaying only last picture on storyprogressbar .Arraylist contains all pictures Url.problem is not displaying all images on storiesProgressbar .. please help me sorting out the problem.
Here is my firebase tree from where I am getting data(pictures) enter image description here
DetailStatusActivity
public class DetailStatusActivity extends AppCompatActivity implements StoriesProgressView.StoriesListener {
StoriesProgressView storiesProgressView;
ImageView image;
int counter = 0;
long pressTime = 0L;
long limit = 500L;
public View.OnTouchListener onTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
pressTime = System.currentTimeMillis();
storiesProgressView.pause();
return false;
case MotionEvent.ACTION_UP:
long now = System.currentTimeMillis();
storiesProgressView.resume();
return limit < now - pressTime;
}
return false;
}
};
private String currentUserID;
private DatabaseReference statusRef;
private String visit_id;
private DatabaseReference detailStatusRef;
private ArrayList<String> imagesArray;
private DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_detail_status);
image = (ImageView) findViewById(R.id.image);
storiesProgressView = (StoriesProgressView) findViewById(R.id.stories);
visit_id = getIntent().getStringExtra("uid");
Log.d("cominghereId", visit_id);
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
statusRef = FirebaseDatabase.getInstance().getReference().child("Statuses");
userRef = FirebaseDatabase.getInstance().getReference().child("Users");
detailStatusRef = FirebaseDatabase.getInstance().getReference();
View reverse = findViewById(R.id.reverse);
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storiesProgressView.reverse();
}
});
reverse.setOnTouchListener(onTouchListener);
View skip = findViewById(R.id.skip);
skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storiesProgressView.skip();
}
});
skip.setOnTouchListener(onTouchListener);
}
#Override
protected void onStart() {
super.onStart();
imagesArray=new ArrayList<>();
detailStatusRef.child("DetailStatusesImages").child(visit_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
imagesArray.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
DetailStatusModel Dupload = snapshot.getValue(DetailStatusModel.class);
imagesArray.add(Dupload.getImage());
}
Log.d("sizee", String.valueOf(imagesArray.size()));
storiesProgressView.setStoriesCount(imagesArray.size());
storiesProgressView.setStoryDuration(3000L);
storiesProgressView.setStoriesListener(DetailStatusActivity.this);
storiesProgressView.startStories(counter);
Glide.with(getApplicationContext()).load(imagesArray.get(counter)).into(image);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onNext() {
Glide.with(getApplicationContext()).load(imagesArray.get(++counter)).into(image);
Log.d("indexx", imagesArray.get(counter));
}
#Override
public void onPrev() {
if ((counter - 1) < 0) return;
Glide.with(getApplicationContext()).load(imagesArray.get(--counter)).into(image);
}
#Override
public void onComplete() {
finish();
}
#Override
protected void onDestroy() {
storiesProgressView.destroy();
super.onDestroy();
}
#Override
protected void onPause() {
storiesProgressView.pause();
super.onPause();
}
#Override
protected void onResume() {
storiesProgressView.resume();
super.onResume();
}
}
I've a problem with values from firebase database and a simple textview where to show them.
public class FindReportActivity extends Activity implements View.OnClickListener{
EditText editTextFindReport;
TextView textViewCommento;
TextView textViewGravita;
ImageView imageViewFindReport;
String cdt;
Report report;
ReportDAO reportDAO = new ReportDAO();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_report);
imageViewFindReport = (ImageView) findViewById(R.id.imageViewFindReport);
editTextFindReport = (EditText) findViewById(R.id.editTextCDT);
textViewCommento= (TextView) findViewById(R.id.textViewcommento);
textViewGravita= (TextView) findViewById(R.id.textViewgravita);
imageViewFindReport.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if( v == imageViewFindReport){
cdt = editTextFindReport.getText().toString().trim();
textViewCommento.setText(reportDAO.findReport(cdt));
}
}
}
here ReportDAO class
public class ReportDAO {
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference databaseReference = firebaseDatabase.getReference();
String commento = "non";
public ReportDAO(){ }
public String findReport(String cdt){
DatabaseReference refReport = databaseReference.child("Report").child(cdt).child("commento");
refReport.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
commento = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return commento;
}
when i click the imageview, the frist time is blank, second time is correct value... why?
You need to implement a listener that waits for the commento to get available, because the findReport method works asynchronous.
The Following is my main activity, in another activity the user can login and upload audio files to the firebase storage; after that it saves the link and the current date time in the firebase database in reverse order.
The structure of the database is Audios> Feb 26,2018> "http:// link to firebase storage"
What I am trying to achieve in this activity is to read the link from the database> Store the value in the string value> and play it on mediaplayer but the following code is not able to read the link from the database for the life of me Please help me I am a new bie
package com.shresthawebworks.dailydevotional;
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener{
private MediaPlayer mMediaplayer;
private ImageButton dplayButton;
private ImageButton dpauseButton;
private ImageButton dstopButton;
private SeekBar seekBar;
private Handler handler;
private Runnable runnable;
private TextView durl;
private TextView drealurl;
private String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
private static final String TAG = null;
private String value = "Udated";
FirebaseDatabase database = FirebaseDatabase.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dplayButton = findViewById(R.id.playButton);
dpauseButton = findViewById(R.id.pauseButton);
dstopButton = findViewById(R.id.stopButton);
durl = findViewById(R.id.dateString);
drealurl = findViewById(R.id.urlText);
handler = new Handler();
seekBar = findViewById(R.id.seekBar1);
mMediaplayer = new MediaPlayer();
mMediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
DatabaseReference myRef = database.getReference("Audios");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
value = (String) dataSnapshot.child(currentDateTimeString).getValue();
// do your stuff here with value
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
fetchAudioUrlFromFirebase();
//.setDataSource();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean input) {
if (input){
mMediaplayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
configureNextButton();}
public void playCycle(){
seekBar.setProgress(mMediaplayer.getCurrentPosition());
if (mMediaplayer.isPlaying()){
runnable =new Runnable() {
#Override
public void run() {
playCycle();
}
};
handler.postDelayed(runnable,1000);
}
}
#Override
protected void onResume() {
super.onResume();
// mMediaplayer.resu;
playCycle();
}
#Override
protected void onPause() {
super.onPause();
mMediaplayer.pause();
playCycle();
}
#Override
protected void onDestroy() {
super.onDestroy();
mMediaplayer.release();
handler.removeCallbacks(runnable);
}
private void fetchAudioUrlFromFirebase() {
final FirebaseStorage storage = FirebaseStorage.getInstance();
durl.setText(currentDateTimeString);
drealurl.setText(value);
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/dailydevotional-9f982.appspot.com/o/audios%2Ftwoprincess.mp3?alt=media&token=e3f98223-68e8-461a-8452-54eca96af4fd");
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
try {
// Download url of file
final String url = uri.toString();
mMediaplayer.setDataSource(url);
// wait for media player to get prepare
mMediaplayer.setOnPreparedListener(MainActivity.this);
mMediaplayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("TAG", e.getMessage());
}
});
}
#Override
public void onPrepared(final MediaPlayer mp) {
dplayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
seekBar.setMax(mp.getDuration());
mp.start();
playCycle();
}
});
dpauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
dstopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playCycle();
mp.stop();
mp.reset();
//fetchAudioUrlFromFirebase();
}
});
}
private void configureNextButton(){
ImageButton dButton= (ImageButton) findViewById(R.id.starLogin);
dButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, UploadActivity.class));
}
});
}
}
I have listed the code below, What i am trying to achieve is the int i to be updated from a dialog box (dialog2). I then want to check in the main activity if it has changed and if it has changed then call a method. How would i do this?
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int i = 0;
Dialog1 dialog1 = new Dialog1(this, i);
dialog1.show();
}
//Want to call this method whenever I is modified
private void iModified(){
}
}
Dialog 1 Class (This dialog just passes it to dialog2)
public class Dialog1 extends Dialog{
int integerI;
Button button;
public Dialog1(final Activity activity, final int i){
super(activity);
setContentView(R.layout.dialog1);
integerI = i;
button = findViewById(R.id.dialog1Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog2 dialog2 = new Dialog2(activity ,integerI);
dialog2.show();
closeDialog();
}
});
}
private void closeDialog(){
this.dismiss();
}
}
Dialog 2: This is where the integer is going to be changed and then i want it to be sent to the main activity and checked if it has changed and if so then replace the old integer with the new one.
public class Dialog2 extends Dialog {
int newI;
Button button;
public Dialog2(Activity activity, int i) {
super(activity);
setContentView(R.layout.dialog2);
newI= i + 12345;
button = findViewById(R.id.dialog2Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
close();
}
});
}
private void close(){
this.dismiss();
}
}
You can use interface.
your activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int i = 0;
Dialog1 dialog1 = new Dialog1(this, i, new ModifiedListener() {
#Override
public void notify(int i) {
iModified();
}
});
dialog1.show();
}
//Want to call this method whenever I is modified
private void iModified(){
}
}
your dialog1:
public class Dialog1 extends Dialog {
int integerI;
Button button;
public Dialog1(final Activity activity, final int i, final ModifiedListener listener) {
super(activity);
setContentView(R.layout.dialog1);
integerI = i;
button = findViewById(R.id.dialog1Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog2 dialog2 = new Dialog2(activity, integerI);
dialog2.show();
closeDialog();
}
});
}
private void closeDialog() {
this.dismiss();
}
}
your dialog 2:
public class Dialog2 extends Dialog {
int newI;
Button button;
public Dialog2(Activity activity, int i, final ModifiedListener listener) {
super(activity);
setContentView(R.layout.dialog2);
newI = i + 12345;
//when you modify int you have to call
listener.notify(newI);
button = findViewById(R.id.dialog2Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
close();
}
});
}
private void close() {
this.dismiss();
}
}
define interface similar to class:
public interface ModifiedListener {
public void notify(int i);
}
I have a simple app with 50 articles, my previous and next button work good in all choices BUT when the user goes to the end (at 50th article) the app can't load again from the beginning the 1st article.
Thanks for any help, here is my code:
I don't know if needs more cede for to be clear, cause I am a newbie.
public class StoryActivity extends AppCompatActivity {
public static final String TAG = StoryActivity.class.getSimpleName();
private Story mStory = new Story();
private ImageView mImageView;
private TextView mTextView;
private Page mCurrentPage;
private String mName;
private Button mPreviousButton;
private Button mNextButton;
private ScrollView mScrollView;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story2);
//Intent intent = getIntent();
//mName = intent.getStringExtra(getString(R.string.key_name));
if(mName == null){
mName = "";
}
Log.d(TAG, mName);
mImageView = (ImageView)findViewById(R.id.storyImageView);
mTextView = (TextView)findViewById(R.id.storyTextView);
mPreviousButton = (Button)findViewById(R.id.previousButton);
mNextButton = (Button)findViewById(R.id.nextButton);
mTextView.setMovementMethod(new ScrollingMovementMethod());
loadPage(0);
}
private void loadPage(int choice){
mCurrentPage = mStory.getPage(choice);
Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
mImageView.setImageDrawable(drawable);
String pageText = mCurrentPage.getText();
//add the name if placeholder included.
//pageText = String.format(pageText,mName);
mTextView.setText(pageText);
if(mCurrentPage.isSingle()){
mPreviousButton.setVisibility(View.VISIBLE);
mNextButton.setText("");
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadPage(0);
}
});
}else{
mPreviousButton.setText(mCurrentPage.getChoices().getText1());
mNextButton.setText(mCurrentPage.getChoices().getText2());
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousPage = mCurrentPage.getChoices().getPreviousPage();
loadPage(previousPage);
}
});
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoices().getNextPage();
loadPage(nextPage);
}
});
}}
}