Java Android Studio: value changes when I flip the screen - java

So I am trying to create a quiz game however, whenever I flip my screen around I come across the following issues:
1. When I rotate the screen and it changes to landscape, even if I choose the wrong answer, I get the wrong message but the score still gets incremented.
2. The question and choices changes rather than staying the same whenever I turn the screen.
here is my code:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class quiz extends AppCompatActivity {
Button answer1, answer2, answer3, answer4;
TextView score,question;
int count=0;
String text="Wrong";
private question mq= new question();
private String manswer;
private int mScore=0;
private int mquestionLength= mq.nquestion.length;
Random r;
private static final String Sscore="";
private static final String nums="";
private String Ques;
private int num;
ArrayList<Integer> list = new ArrayList<Integer>();
private String arr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz);
num=0;
r = new Random();
answer1 = (Button) findViewById(R.id.answer1);
answer2 = (Button) findViewById(R.id.answer2);
answer3 = (Button) findViewById(R.id.answer3);
answer4 = (Button) findViewById(R.id.answer4);
score = (TextView) findViewById(R.id.score);
question = (TextView) findViewById(R.id.question);
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mquestionLength));
answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num++;
if (answer1.getText() == manswer) {
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mquestionLength));
}
else {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
updateQuestion(r.nextInt(mquestionLength));
}
if(num>8){
GameOver();
}
}
}
);
answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num++;
if (answer2.getText() == manswer) {
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mquestionLength));
} else {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
updateQuestion(r.nextInt(mquestionLength));
}
if(num>8){
GameOver();
}
}
}
);
answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num++;
if (answer3.getText() == manswer) {
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mquestionLength));
} else {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
updateQuestion(r.nextInt(mquestionLength));
}
if(num>8){
GameOver();
}
}
}
);
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num++;
if (answer4.getText() == manswer) {
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mquestionLength));
} else {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
updateQuestion(r.nextInt(mquestionLength));
}
if(num>8){
GameOver();
}
}
}
);
}
private void updateQuestion ( int nextInt){
if(count==0) {
question.setText(mq.getQuestion(nextInt));
answer1.setText(mq.getChoice(nextInt));
answer2.setText(mq.getChoice2(nextInt));
answer3.setText(mq.getChoice3(nextInt));
answer4.setText(mq.getChoice4(nextInt));
manswer = mq.getAnswer(nextInt);
}
else{
if(!list.contains(nextInt)){
question.setText(mq.getQuestion(nextInt));
answer1.setText(mq.getChoice(nextInt));
answer2.setText(mq.getChoice2(nextInt));
answer3.setText(mq.getChoice3(nextInt));
answer4.setText(mq.getChoice4(nextInt));
manswer = mq.getAnswer(nextInt);
}
else{
updateQuestion(r.nextInt(mquestionLength));
}
}
list.add(nextInt);
count++;
}
private void GameOver() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(quiz.this);
alertDialogBuilder.setMessage("Game Over! Your Score is "+mScore).setCancelable(false).setPositiveButton(
"NEW GAME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(),quiz.class));
}
}).setNegativeButton("EXIT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog=alertDialogBuilder.create();
alertDialog.show();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(Sscore,mScore);
outState.putInt(nums,num);
outstate.putIntegerArrayList(arr,list);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mScore=savedInstanceState.getInt(Sscore);
num=savedInstanceState.getInt(nums);
score.setText("Score: "+mScore);
list.addAll(savedInstanceState.getIntegerArrayList(arr));
}
}

The default behaviour of the android's apps is when you rotate the screen and you don't set a unice orientation(landscape or portrait) the actual activity is destroyed and recreated again.
You have 2 options if you want to avoid this:
you can add on the manifest on the activity the following attribute :
android:configChanges="orientation|screenSize"
You can set the orientation of the activity or the all the app with this:
android:screenOrientation="portrait"
or
android:screenOrientation="landscape"

Your code behaves unexpected because you use onRestoreInstanceState which is called long after onCreate in the lifecycle.
But you do all your important stuff already in onCreate.
As far as I know, onRestoreInstanceState is called after onStart.
You have two options:
1) do your stuff in a private method that you call from onCreate and onRestoreInstanceState (not-so-good)
2) you can simply use the savedInstanceState parameter directly in onCreate. It contains the bundle you saved in the onSaveInstanceState callback. (better)
protected void onSaveInstanceState(Bundle instanceState) {
super.onSaveInstanceState(instanceState);
instanceState.putString("your_first_value", value1);
instanceState.putString("your_second_value", value2);
// ... save all your variables you want to keep ...
}
Then, later, when the activity is re-created you get this bundle you just saved supplied in the savedInstanceState parameter:
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(...); // This creates your controls
// if savedInstanceState is not null, you have a saved state here...
// so you can restore it
if (savedInstanceState != null) {
value1 = savedInstanceState.getString("your_first_value");
value2 = savedInstanceState.getString("your_second_value");
// ... here you restore all your values ...
}
}

Related

Whe button continueButton isnt working? It should start the new Activity if I have a text in EditText or make a Toast

I work with a program which should make parameters for character. A person writes a name then generate force and health by clicking the button. After all, he click the continueButton which should start the MainActivity if name exists or make a Toast text. But it's not working. The problem should be in the end of onClick method.
There is a code
public class CreateActivity extends AppCompatActivity
implements View.OnClickListener {
final Random random = new Random();
String toastText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
}
#Override
public void onClick(View v) {
Button continueButton = findViewById(R.id.continueButton);
Button getData = findViewById(R.id.getData);
final EditText newName = findViewById(R.id.newName);
TextView newHealth = findViewById(R.id.newHealth);
TextView newForce = findViewById(R.id.newForce);
continueButton.setOnClickListener(this);
getData.setOnClickListener(this);
newName.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()== KeyEvent.ACTION_DOWN &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
Character.name = newName.getText().toString();
return true;
}
return false;
}
});
switch (v.getId()){
case R.id.getData: {
Character.health = random.nextInt(100);
newHealth.setText(String.valueOf(Character.health));
Character.force = random.nextInt(100);
newForce.setText(String.valueOf(Character.force));
}
// THERE IS A PROBLEM
if (newName.getText().toString().equals("")) {
switch (v.getId()) {
case R.id.continueButton:
startActivity(new Intent(this, MainActivity.class));
finish();
return;
}
} else{
switch (v.getId()) {
case R.id.continueButton:
Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
}
Initialize your Button inside onCreate method. Like this:
public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
private Button yourButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourButton= findViewById(R.id.your_button_id);
yourButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
switch (view.getId()) {
case R.id.your_button_id:
// Do something
}
}
}

Cannot solve method makeText

I'm new to developing and i bought a book, Big Nerd Ranch Guide to Android Programming. I finished chapter 2 and everything worked fine on this app it showed me how to make. Now im trying to do the challenges at the end and it wont work. Its giving me an error for something i didnt change at all, and it worked yesterday. The challenge wanted me to add a Previous button to the mix.
"Cannot solve method 'makeText(anonymous android.view.View.OnClickListener, int, int)'
The error is at the very bottom where im trying to create a Toast.
package com.example.lthol.geoquiz;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mPrevButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_australia, true),
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
mPrevButton = (Button) findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
}
The mPrevButton onClick listener is actually contained in the mNextButton implementation. You need to close the bracket so that they are separate.

My button "close" don't close but hide the page

Hello all, My button (close) in the closeListener (in my java code). When I push this button (close) I go back correctly in my first page but it don't close correctly my Rent page (second page), my second page remain open below my first page (hide behind the first page), how can I do for close correctly the second page (Rent) ?
package albencreation.realestateapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Rent extends AppCompatActivity {
EditText price = null;
EditText profit = null;
TextView result = null;
Button envoyer = null;
Button close = null;
Button info = null;
Button clear = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rent);
price = (EditText) findViewById(R.id.price);
profit = (EditText) findViewById(R.id.profit);
result = (TextView) findViewById(R.id.result);
envoyer = (Button) findViewById(R.id.buttcalculate);
close = (Button) findViewById(R.id.buttclose);
info = (Button) findViewById(R.id.buttinfo);
clear = (Button) findViewById(R.id.buttclear);
envoyer.setOnClickListener(envoyerListener);
close.setOnClickListener(closeListener);
info.setOnClickListener(infoListener);
clear.setOnClickListener(clearListener);
}
private OnClickListener envoyerListener = new OnClickListener() {
#Override
public void onClick(View v) {
String p = price.getText().toString();
String o = profit.getText().toString();
float pValue;
if (p.isEmpty()) {
pValue = 0;
} else {
pValue = Float.valueOf(p);
}
float oValue;
if (o.isEmpty()) {
oValue = 0;
} else {
oValue = Float.valueOf(o);
}
float resultat = oValue * pValue / 100;
result.setText("the rent is " + String.valueOf(resultat) + " currency");
}
};
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, MainActivity.class);
startActivity(jumpage);
}
};
private OnClickListener infoListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, Inforent.class);
startActivity(jumpage);
}
};
private OnClickListener clearListener = new OnClickListener() {
#Override
public void onClick(View v) {
price.getText().clear();
profit.getText().clear();
String defaut = "result rent";
result.setText(defaut);
}
};
}
You can call the finish() method to finish your activity for good:
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, MainActivity.class);
startActivity(jumpage);
Rent.this.finish();
}
};
Instead of this
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, MainActivity.class);
startActivity(jumpage);
}
};
Just write as below
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
this.finish();
}
};
Just call finish() to close Rent activity.
Try this:
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, MainActivity.class);
startActivity(jumpage);
finish();
}
};

Progress bar in quiz (Android Studio)

I am creating a quiz game and I have added progress bar. I want the progress bar to give 10 seconds to answer each question and if the time runs out it should display the results screen. How do I this?
package com.example.sqz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class QuestionActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQuestion;
TextView txtQuestion, times, scored;
Button Answer1, Answer2, Answer3, Answer4;
QuizHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//level difficulty
int level;
level = getIntent().getIntExtra("level",-1); //get LEVEL from intent. If no LEVEL in intent, LEVEL=-1.
//if level not equal "-1" (so level was in intent), get questions for this level from database
if(level!=-1) {
db=new QuizHelper(this);
quesList=db.getAllQuestionsByLevel(level);
}
currentQuestion = quesList.get(qid); // current question
txtQuestion = (TextView) findViewById(R.id.txtQuestion); // textview to view the question
// the four answer buttons
Answer1 = (Button) findViewById(R.id.btnAnswer1);
Answer2 = (Button) findViewById(R.id.btnAnswer2);
Answer3 = (Button) findViewById(R.id.btnAnswer3);
Answer4 = (Button) findViewById(R.id.btnAnswer4);
// text view to show score
scored = (TextView) findViewById(R.id.score);
// textview for timer
times = (TextView) findViewById(R.id.timers);
// method to set the game
setQuestionView();
times.setText(R.string.timertext);
final ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
final int[] i = {0};
mProgressBar=(ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setProgress(i[0]);
mCountDownTimer=new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i[0] + millisUntilFinished);
i[0]++;
mProgressBar.setProgress(i[0]);
}
#Override
public void onFinish() {
//Do what you want
i[0]++;
mProgressBar.setProgress(i[0]);
}
};
mCountDownTimer.start();;
// button click listeners
Answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // method to check if the answer is correct
getAnswer(Answer1.getText().toString());
}
});
Answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer2.getText().toString());
}
});
Answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer3.getText().toString());
}
});
Answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer4.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQuestion.getANSWER().equals(AnswerString)) {
score = score + 5; // increase the sore by 5 if the answer is correct
scored.setText("Score : " + score); // set text of textview to score
} else { //load the result screen if wrong answer is selected
Intent intent;
intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b;
b = new Bundle();
b.putInt("score", score);
intent.putExtras(b); // Put your score to your next
startActivity(intent); // starts the activity
finish();
}
if (qid < 20) { // 20 questions for each level
// until the questions are over do this
currentQuestion = quesList.get(qid);
setQuestionView();
} else {
// once the questions are finished show results screen
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put questions and answers together
txtQuestion.setText(currentQuestion.getQUESTION());
Answer1.setText(currentQuestion.getA1());
Answer2.setText(currentQuestion.getA2());
Answer3.setText(currentQuestion.getA3());
Answer4.setText(currentQuestion.getA4());
qid++;
}
}
You could use a running Thread or AsyncTask
1)For a running Thread,
In your activity xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:progress="100"
android:id="#+id/progress"/>
</LinearLayout>
In your activity
public class TestActivity extends AppCompatActivity{
private ProgressBar moveBar;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
moveBar = (ProgressBar)findViewById(R.id.progress);
moveBar.setProgress(100);
startProgress();
}
private void startProgress() {
Thread sleep = new Thread(new Runnable() {
#Override
public void run() {
for(count =10; count >=0; count --) {
try {
Thread.sleep(1000); //every 1sec
// here you check for the result if correct
//i use count == 5 as an example, uncomment to see
/*if(count == 5){
count = 10;
moveBar.setProgress(100);
startProgress();
break;
}*/
}catch (Exception i){
i.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
moveBar.setProgress(10 * count);
Log.e("Count", " " + count);
if(count == 0){
Toast.makeText(getApplicationContext(),
"Result screen", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});sleep.start();
}
}
2) For AsyncTask, use these links to guide you
http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.Vz7rW3yrS6k
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

Android List View Is not Updating

I am a beginner, When i add music files to Sd card the list view in my Music app isn't updating untill i reboot the device or my genymotion emulator. and the songs are also playing with lagging.
Here is my main Acivity.java code :
import com.techdsk.musicdsk.musicdsk.adapter.CustomAdapter;
import com.techdsk.musicdsk.musicdsk.controls.Controls;
import com.techdsk.musicdsk.musicdsk.service.SongService;
import com.techdsk.musicdsk.musicdsk.util.MediaItem;
import com.techdsk.musicdsk.musicdsk.util.PlayerConstants;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class MainActivity extends Activity {
String LOG_CLASS = "MainActivity";
CustomAdapter customAdapter = null;
static TextView playingSong;
Button btnPlayer;
static Button btnPause, btnPlay, btnNext, btnPrevious;
Button btnStop;
LinearLayout mediaLayout;
static LinearLayout linearLayoutPlayingSong;
ListView mediaListView;
ProgressBar progressBar;
TextView textBufferDuration, textDuration;
static ImageView imageViewAlbumArt;
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
}
private void init() {
getViews();
setListeners();
playingSong.setSelected(true);
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
if(PlayerConstants.SONGS_LIST.size() <= 0){
PlayerConstants.SONGS_LIST = UtilFunctions.listOfSongs(getApplicationContext());
}
setListItems();
}
private void setListItems() {
customAdapter = new CustomAdapter(this,R.layout.custom_list, PlayerConstants.SONGS_LIST);
mediaListView.setAdapter(customAdapter);
mediaListView.setFastScrollEnabled(true);
}
private void getViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
btnPlayer = (Button) findViewById(R.id.btnMusicPlayer);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
mediaLayout = (LinearLayout) findViewById(R.id.linearLayoutMusicList);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id){
Log.d("TAG", "TAG Tapped INOUT(IN)");
PlayerConstants.SONG_PAUSED = false;
PlayerConstants.SONG_NUMBER = position;
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(),SongService.class);
startService(i);
} else {
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
Log.d("TAG", "TAG Tapped INOUT(OUT)");
}
});
btnPlayer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AudioPlayerActivity.class);
startActivity(i);
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SongService.class);
stopService(i);
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
imageViewAlbumArt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AudioPlayerActivity.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try{
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}else{
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerConstants.PROGRESSBAR_HANDLER = new Handler(){
#Override
public void handleMessage(Message msg){
Integer i[] = (Integer[])msg.obj;
textBufferDuration.setText(UtilFunctions.getDuration(i[0]));
textDuration.setText(UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}catch(Exception e){}
}
#SuppressWarnings("deprecation")
public static void updateUI() {
try{
MediaItem data = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER);
playingSong.setText(data.getTitle() + " " + data.getArtist() + "-" + data.getAlbum());
Bitmap albumArt = UtilFunctions.getAlbumart(context, data.getAlbumId());
if(albumArt != null){
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(albumArt));
}else{
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
}catch(Exception e){}
}
public static void changeButton() {
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
}else{
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public static void changeUI(){
updateUI();
changeButton();
}
}
Here is my Audioplayer Activity.java Code :
package com.techdsk.musicdsk.musicdsk;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.techdsk.musicdsk.musicdsk.controls.Controls;
import com.techdsk.musicdsk.musicdsk.service.SongService;
import com.techdsk.musicdsk.musicdsk.util.PlayerConstants;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class AudioPlayerActivity extends Activity {
Button btnBack;
static Button btnPause;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
ProgressBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.audio_player);
context = this;
init();
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
PlayerConstants.PROGRESSBAR_HANDLER = new Handler(){
#Override
public void handleMessage(Message msg){
Integer i[] = (Integer[])msg.obj;
textBufferDuration.setText(UtilFunctions.getDuration(i[0]));
textDuration.setText(UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI(){
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
}else{
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try{
String songName = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getTitle();
String artist = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getArtist();
String album = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbum();
String composer = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if(composer != null && composer.length() > 0){
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
}else{
textComposer.setVisibility(View.GONE);
}
}catch(Exception e){
e.printStackTrace();
}
try{
long albumId = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = UtilFunctions.getAlbumart(context, albumId);
if(albumArt != null){
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
}else{
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
custom adapter .java code :
package com.techdsk.musicdsk.musicdsk.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.techdsk.musicdsk.musicdsk.R;
import com.techdsk.musicdsk.musicdsk.util.MediaItem;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class CustomAdapter extends ArrayAdapter<MediaItem>{
ArrayList<MediaItem> listOfSongs;
Context context;
LayoutInflater inflator;
public CustomAdapter(Context context, int resource, ArrayList<MediaItem> listOfSongs) {
super(context, resource, listOfSongs);
this.listOfSongs = listOfSongs;
this.context = context;
inflator = LayoutInflater.from(context);
}
private class ViewHolder{
TextView textViewSongName, textViewArtist, textViewDuration;
}
ViewHolder holder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = convertView;
if(convertView == null){
myView = inflator.inflate(R.layout.custom_list, parent, false);
holder = new ViewHolder();
holder.textViewSongName = (TextView) myView.findViewById(R.id.textViewSongName);
holder.textViewArtist = (TextView) myView.findViewById(R.id.textViewArtist);
holder.textViewDuration = (TextView) myView.findViewById(R.id.textViewDuration);
myView.setTag(holder);
}else{
holder = (ViewHolder)myView.getTag();
}
MediaItem detail = listOfSongs.get(position);
holder.textViewSongName.setText(detail.toString());
holder.textViewArtist.setText(detail.getAlbum() + " - " + detail.getArtist());
holder.textViewDuration.setText(UtilFunctions.getDuration(detail.getDuration()));
return myView;
}
}
when you add the file you can use NotifyDatasetChanged(). this will tell your adapter to refresh its data. So when your source array is updated after adding a new file you can call NotifyDatasetChanged() method.
as Ex. if you have a method named Add() inside your adapter then.
public void Add (item e){
items.add (e);
NotifyDatasetChanged();
}
will refresh your data.
Your list is not getting updated because it is not informed about the data change,
the documentation in the ADW explains:
notifyDataSetChanged() Notifies the attached observers that the
underlying data has been changed and any View reflecting the data set
should refresh itself.
Solution
Notify yor adapter:
customAdapter.notifyDataSetChanged();

Categories