Cannot solve method makeText - java

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.

Related

How do I fix this NullPointError? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am new to coding and enthusiastically learning Android Studio, following on videos to do coding.
I have already gone through that article - What is NullPointerException and understood the concept in few more related articles but I am unable to fix though I understand the error is on which code but if not that, then what is my question.
I am facing this NullPointerException after pressing any button on calculator app:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.blogeomics.calcee.MainActivity.numberPressed(MainActivity.java:167)
at com.blogeomics.calcee.MainActivity$7.onClick(MainActivity.java:97)
Code is below:
package com.blogeomics.calcee;
import android.app.Activity;
import android.media.Image;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import static android.R.string.no;
import static android.os.Build.VERSION_CODES.O;
public class MainActivity extends AppCompatActivity {
String runningNumber = "0";
TextView resultsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button oneBtn = (Button) findViewById(R.id.button1);
Button twoBtn = (Button) findViewById(R.id.button2);
Button threeBtn = (Button) findViewById(R.id.button3);
Button fourBtn = (Button) findViewById(R.id.button4);
Button fiveBtn = (Button) findViewById(R.id.button5);
Button sixBtn = (Button) findViewById(R.id.button6);
Button sevenBtn = (Button) findViewById(R.id.button7);
Button eightBtn = (Button) findViewById(R.id.button8);
final Button nineBtn = (Button) findViewById(R.id.button9);
Button zeroBtn = (Button) findViewById(R.id.button0);
ImageButton calcBtn = (ImageButton) findViewById(R.id.buttonEqual);
ImageButton divideBtn = (ImageButton) findViewById(R.id.buttonDivide);
ImageButton multiplyBtn = (ImageButton) findViewById(R.id.buttonMultiply);
ImageButton addBtn = (ImageButton) findViewById(R.id.buttonAdd);
ImageButton subtractBtn = (ImageButton) findViewById(R.id.buttonSubtract);
Button clearBtn = (Button) findViewById(R.id.buttonClear);
TextView resultsView = (TextView) findViewById(R.id.result_view);
resultsView.setText("");
oneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(1);
}
});
twoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(2);
}
});
threeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(3);
}
});
fourBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(4);
}
});
fiveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(5);
}
});
sixBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(6);
}
});
sevenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(7);
}
});
eightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(8);
}
});
nineBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(9);
}
});
zeroBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberPressed(0);
}
});
calcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
subtractBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
multiplyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
divideBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
clearBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
void numberPressed(int number) {
runningNumber = runningNumber + String.valueOf(number);
resultsView.setText(runningNumber);
}
}
I have gone through lot of posts about this error but still unable to figure out how to SOLVE my problem, I know it should be a minor thing yet I can't comprehend, please help.
Change this line:
TextView resultsView = (TextView) findViewById(R.id.result_view);
to
resultsView = (TextView) findViewById(R.id.result_view);
now your resultsView will be global

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();

my android app works very slow

Hello i'm creating an app to scan buisness cards, it has lot of views but one works very slow it has 19 buttons. Is it possible that slow working of my app is caused by this number of buttons? I've tried to put listeners outside of onCreate but it didn't help. This is my java file conected to this view:
public class Szczegoly extends Activity {
long contactID;
Bitmap contactFoto;
int imagebig=0;
int w;
Contact contact;
EditText tv1;
EditText tv2;
EditText tv3;
EditText tv4;
EditText tv5;
ImageView i;
Button b1;
Button b2;
Button b3;
Button b4;
Button b5;
Button b6;
Button b7;
Button b8;
Button b9;
Button b10;
Context to;
Button accept1;
Button accept2;
Button accept3;
Button accept4;
Button accept5;
Button cancel1;
Button cancel2;
Button cancel3;
Button cancel4;
Button cancel5;
Context context;
OnClickListener accept1listener = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==1)
{
contact.savedata_nr(edit_nr,tv1,tv2,tv3,tv4,tv5,context);
closeEdit();
}
}
};
OnClickListener accept2listener = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==2)
{
contact.savedata_nr(edit_nr,tv1,tv2,tv3,tv4,tv5,context);
closeEdit();
}
}
};
OnClickListener accept3listener = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==3)
{
contact.savedata_nr(edit_nr,tv1,tv2,tv3,tv4,tv5,context);
closeEdit();
}
}
};
OnClickListener accept4listener = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==4)
{
contact.savedata_nr(edit_nr,tv1,tv2,tv3,tv4,tv5,context);
closeEdit();
}
}
};
OnClickListener accept5listener = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==5)
{
contact.savedata_nr(edit_nr,tv1,tv2,tv3,tv4,tv5,context);
closeEdit();
}
}
};
OnClickListener cancel1listener = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText(contact.FirstName);
closeEdit();
}
};
OnClickListener cancel2listener = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText(contact.FirstName);
closeEdit();
}
};
OnClickListener cancel3listener = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText(contact.FirstName);
closeEdit();
}
};
OnClickListener cancel4listener = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText(contact.FirstName);
closeEdit();
}
};
OnClickListener cancel5listener = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText(contact.FirstName);
closeEdit();
}
};
OnClickListener b1lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0)
{
finish();
}
}
};
OnClickListener b2lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0)
{
contact.delete();
finish();
}
}
};
OnClickListener b3lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0)
{
}
}
};
OnClickListener b4lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0)
{
Uri call = Uri.parse("tel:"+contact.Phone1);
Intent intent = new Intent(Intent.ACTION_CALL, call);
startActivity(intent);
}
}
};
OnClickListener b5lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0)
{
}
}
};
OnClickListener b6lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0)
{
if(tv1.isEnabled())
{
tv1.setSelected(false);
tv1.setEnabled(false);
}
else
{
cancel1.setVisibility(Button.VISIBLE);
accept1.setVisibility(Button.VISIBLE);
b6.setVisibility(Button.INVISIBLE);
tv1.setEnabled(true);
tv1.setSelected(true);
tv1.setFocusableInTouchMode(true);
tv1.requestFocus();
tv1.setSelection(tv1.getText().length());
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
edit_nr= 1;
}
}
};
OnClickListener b7lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0)
{
if(tv2.isEnabled())
tv2.setEnabled(false);
else
{
cancel2.setVisibility(Button.VISIBLE);
accept2.setVisibility(Button.VISIBLE);
b7.setVisibility(Button.INVISIBLE);
tv2.setEnabled(true);
tv2.setSelected(true);
tv2.setFocusableInTouchMode(true);
tv2.requestFocus();
tv2.setSelection(tv2.getText().length());
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
edit_nr= 2;
}
}
};
OnClickListener b8lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr == 0)
{
if(tv3.isEnabled())
tv3.setEnabled(false);
else
{
cancel3.setVisibility(Button.VISIBLE);
accept3.setVisibility(Button.VISIBLE);
b8.setVisibility(Button.INVISIBLE);
tv3.setEnabled(true);
tv3.setEnabled(true);
tv3.setSelected(true);
tv3.setFocusableInTouchMode(true);
tv3.requestFocus();
tv3.setSelection(tv3.getText().length());
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
edit_nr=3;
}
}
};
OnClickListener b9lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr ==0 )
{
if(tv4.isEnabled())
tv4.setEnabled(false);
else
{
cancel4.setVisibility(Button.VISIBLE);
accept4.setVisibility(Button.VISIBLE);
b9.setVisibility(Button.INVISIBLE);
tv4.setEnabled(true);
tv4.setEnabled(true);
tv4.setSelected(true);
tv4.setFocusableInTouchMode(true);
tv4.requestFocus();
tv4.setSelection(tv4.getText().length());
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
edit_nr= 4;
}
}
};
OnClickListener b10lisner = new OnClickListener() {
#Override
public void onClick(View v) {
if(edit_nr==0)
{
if(tv5.isEnabled())
tv5.setEnabled(false);
else
{
cancel5.setVisibility(Button.VISIBLE);
accept5.setVisibility(Button.VISIBLE);
b10.setVisibility(Button.INVISIBLE);
tv5.setEnabled(true);
tv5.setEnabled(true);
tv5.setSelected(true);
tv5.setFocusableInTouchMode(true);
tv5.requestFocus();
tv5.setSelection(tv5.getText().length());
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null)
{
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
edit_nr= 5;
}
}
};
int edit_nr=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_szczegoly);
Log.d("dupa","dupa1");
context = this;
Intent intent = getIntent();
contactID = intent.getLongExtra("contactID", 0);
contact = new Contact(contactID, this);
tv1 = (EditText) findViewById(R.id.editText1);
tv2 = (EditText) findViewById(R.id.editText2);
tv3 = (EditText) findViewById(R.id.editText3);
tv4 = (EditText) findViewById(R.id.editText4);
tv5 = (EditText) findViewById(R.id.editText5);
i = (ImageView) findViewById(R.id.imageView1);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
b5 = (Button) findViewById(R.id.button5);
b6 = (Button) findViewById(R.id.button6);
b7 = (Button) findViewById(R.id.button7);
b8 = (Button) findViewById(R.id.button8);
b9 = (Button) findViewById(R.id.button9);
b10 = (Button) findViewById(R.id.button10);
tv1.setText(contact.FirstName);
tv2.setText(contact.LastName);
tv3.setText(contact.Phone1);
tv4.setText(contact.Phone2);
tv5.setText(contact.EmaiL);
accept1 = (Button) findViewById(R.id.accept1);
accept2 = (Button) findViewById(R.id.accept2);
accept3 = (Button) findViewById(R.id.accept3);
accept4 = (Button) findViewById(R.id.accept4);
accept5 = (Button) findViewById(R.id.accept5);
cancel1 =(Button) findViewById(R.id.cancel1);
cancel2 =(Button) findViewById(R.id.cancel2);
cancel3 =(Button) findViewById(R.id.cancel3);
cancel4 =(Button) findViewById(R.id.cancel4);
cancel5 =(Button) findViewById(R.id.cancel5);
}
public void closeEdit()
{
tv1.setSelected(false);
tv1.setEnabled(false);
tv2.setSelected(false);
tv2.setEnabled(false);
tv3.setSelected(false);
tv3.setEnabled(false);
tv4.setSelected(false);
tv4.setEnabled(false);
tv5.setSelected(false);
tv5.setEnabled(false);
cancel1.setVisibility(Button.INVISIBLE);
accept1.setVisibility(Button.INVISIBLE);
b6.setVisibility(Button.VISIBLE);
cancel2.setVisibility(Button.INVISIBLE);
accept2.setVisibility(Button.INVISIBLE);
b7.setVisibility(Button.VISIBLE);
cancel3.setVisibility(Button.INVISIBLE);
accept3.setVisibility(Button.INVISIBLE);
b8.setVisibility(Button.VISIBLE);
cancel4.setVisibility(Button.INVISIBLE);
accept4.setVisibility(Button.INVISIBLE);
b9.setVisibility(Button.VISIBLE);
cancel5.setVisibility(Button.INVISIBLE);
accept5.setVisibility(Button.INVISIBLE);
b10.setVisibility(Button.VISIBLE);
edit_nr=0;
}
public void onResume() {
super.onResume();
Log.d("dupa","dupa");
Point size = new Point();
Display display = getWindowManager().getDefaultDisplay();
display.getSize(size);
to = this;
w = size.x;
contactFoto = Bitmap.createScaledBitmap(contact.photo, w, (int) (w*contact.photo.getHeight()/contact.photo.getWidth()), true);
i.setImageBitmap(contactFoto);
accept1.setOnClickListener(accept1listener);
accept2.setOnClickListener(accept2listener);
accept3.setOnClickListener(accept3listener);
accept4.setOnClickListener(accept4listener);
accept5.setOnClickListener(accept5listener);
cancel1.setOnClickListener(cancel1listener);
cancel2.setOnClickListener(cancel2listener);
cancel3.setOnClickListener(cancel3listener);
cancel4.setOnClickListener(cancel4listener);
cancel5.setOnClickListener(cancel5listener);
b1.setOnClickListener(b1lisner);
b2.setOnClickListener(b2lisner);
b3.setOnClickListener(b3lisner);
b4.setOnClickListener(b4lisner);
b5.setOnClickListener(b5lisner);
b6.setOnClickListener(b6lisner);
b7.setOnClickListener(b7lisner);
b8.setOnClickListener(b8lisner);
b9.setOnClickListener(b9lisner);
b10.setOnClickListener(b10lisner);
}
}
The number of buttons by itself is not a likely cause of slowness. However, from the code it seems as if many actions from listeners (ie contact.savedata_nr) might be running on the main/UI thread which could cause slowness, depending on what happens when these methods are called. As mentioned in the comment, creating Bitmap might be better task to be carried out in the background as well.
To fix this, you should review your code and see what can be run in the background thread instead. Operations like saving can be done on the background thread, and then any updates to the GUI after these should be carried out on UI thread. If the background operation takes a long time, it's a good idea to up a progress indicator to show the user that something is happening and that the screen isn't just stuck.
You can read about Android threading here.
The basic example would be:
new Thread(new Runnable()
{
public void run()
{
//put background code here
contact.save(...)
//after background task is finished, update the UI
runOnUiThread(new Runnable()
{
#Override
public void run()
{
//put UI code here
textview.setText(...);
}
});
}
}).start();

Categories