What I am trying to accomplish is to take an array, sort it, pull the first 5 results and display them in a small window. It was recommended to me to try to accomplish this using the previously mentioned methods as shown in the below code. I am still quite new to Android and this is my first attempt at utilizing StringBuffer and AlertDialog.
My error is that I have either done something wrong initializing the lastScoreMessage variable or I am passing it around incorrectly. All I know is that even though I am specifically calling it in my onClick switch case, it is giving me an error saying it is never used (in the lastFive method) and Cannot resolve symbol lastScoreMessage in the onClick switch statement where I am attempting to use it.
Any help here is greatly appreciated.
public class EditTextButtons extends AppCompatActivity implements View.OnClickListener {
DBHandler db;
Calendar c = Calendar.getInstance ( );
Date d = c.getTime ( );
EditText etName;
Button btnAdd;
Button btnLastFive;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.snake_layout_r);
db = new DBHandler (this);
etName = (EditText) findViewById (R.id.etName);
btnAdd = (Button) findViewById (R.id.btnAdd);
btnLastFive = (Button) findViewById (R.id.btnLastFive);
// set listeners
btnAdd.setOnClickListener (this);
btnLastFive.setOnClickListener (this);
}
@Override
public void onClick(View v) {
switch (v.getId ( )) {
case R.id.btnAdd:
insertIntoDB ( );
Intent i = new Intent (getApplicationContext ( ), Snake.class);
startActivity (i);
break;
case R.id.btnLastFive:
lastFive ();
showMessage ("Last 5 Scores", lastScoreMessage);
break;
default:
break;
}
}
protected void insertIntoDB() {
ContentValues cv = new ContentValues ( );
cv.put (db.USERNAME, etName.getText ( ).toString ( ));
}
protected void lastFive() {
int listsize = 5;
List<User> userlist = new ArrayList<User> ( );
userlist = db.convertDatabaseToList ( );
Collections.sort (userlist, User.Comparators._id);
StringBuffer buffer = new StringBuffer();
String lastScoreMessage;
for (int i = 0; i < listsize; i++) {
User temp = userlist.get(i);
String username = temp.getName();
int score = temp.getScore();
buffer.append(username + ": " + score + "\n");
}
lastScoreMessage = buffer.toString();
}
protected void showMessage(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
simply create lastScoreMessage in the class instead of method. the problem is the scope of variable is only upto method. first create variable in class. and then store value in method like you did.