I'm having a tremendous amount of difficulty dealing with static members while trying to make an Android app.
Here's what the app has to do:
There are two tabs, My Classes and Class List, each of which are separate intents. The point of the app is that when you click the "add" button next to a class in the Class List, it should dynamically update the list under My Classes. However, I can't do this because my data structure that holds the classes is dynamic, but the Class List intent is static, so I keep getting the "Cannot reference non-static member from static context" error.
Is there any way to use dynamic intents, and if so, how?
EDIT:
Here's where the intents are declared:
public class TabLayout extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
Intent intent = new Intent(this, MyClasses.class);
tabHost.addTab(tabHost.newTabSpec("My Classes")
.setIndicator("My Classes", res.getDrawable(R.drawable.ic_tab_main))
.setContent(intent));
Intent intent2 = new Intent(this, ClassList.class);
tabHost.addTab(tabHost
.newTabSpec("Class List")
.setIndicator("Class List", res.getDrawable(R.drawable.ic_tab_main))
.setContent(intent2));
Intent intent3 = new Intent(this, SyncList.class);
tabHost.addTab(tabHost
.newTabSpec("Sync List")
.setIndicator("Sync List", res.getDrawable(R.drawable.ic_tab_main))
.setContent(intent3));
tabHost.setCurrentTab(0);
// Set tabs Colors
tabHost.setBackgroundColor(Color.BLACK);
tabHost.getTabWidget().setBackgroundColor(Color.BLACK);
}
}
Here's the MyClassList file:
public class MyClassList extends MyClasses {
int numClasses;
MyClasses myclasses = new MyClasses();
final static TableRow tableRowArray[] = new TableRow[4];
TextView classNameArray[] = new TextView[4];
TextView teacherNameArray[] = new TextView[4];
Button dropButtonArray[] = new Button[4];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create containers
ScrollView classListScrollView = new ScrollView(this);
TableLayout classListTableLayout = new TableLayout(this);
// Add class entries
for (int i = 0; i < 4; i++)
{
tableRowArray[i] = new TableRow(this);
tableRowArray[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
classNameArray[i] = new TextView(this);
classNameArray[i].setText("");
classNameArray[i].setPadding(10, 20, 10, 20);
classNameArray[i].setTextSize(20);
tableRowArray[i].addView(classNameArray[i]);
teacherNameArray[i] = new TextView(this);
teacherNameArray[i].setText("");
teacherNameArray[i].setPadding(10, 20, 10, 20);
teacherNameArray[i].setTextSize(16);
tableRowArray[i].addView(teacherNameArray[i]);
dropButtonArray[i] = new Button(this);
dropButtonArray[i].setText("Drop");
tableRowArray[i].addView(dropButtonArray[i]);
classListTableLayout.addView(tableRowArray[i], new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tableRowArray[i].setVisibility(View.GONE);
}
classListScrollView.addView(classListTableLayout);
this.setContentView(classListScrollView);
dropButtonArray[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
myclasses.dropClass(0);
}
});
dropButtonArray[1].setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
myclasses.dropClass(1);
}
});
dropButtonArray[2].setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
myclasses.dropClass(2);
}
});
dropButtonArray[3].setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
myclasses.dropClass(3);
}
});
}
public void updateMyClasses(ClassObject myclasses[])
{
for (int i = 0; i < 4; i++)
{
if (myclasses[i].isNull)
{
classNameArray[i].setText(myclasses[i].getClassName());
teacherNameArray[i].setText(myclasses[i].getTeacherName());
tableRowArray[i].setVisibility(View.VISIBLE);
}
else
{
tableRowArray[i].setVisibility(View.GONE);
}
}
}
public MyClasses getMyClasses()
{
return myclasses;
}
}
Here's the MyClasses file:
public class MyClasses extends Activity {
static int numClasses;
static ClassObject MyClassArray[];
public MyClasses()
{
MyClassArray = new ClassObject[4];
for (int i = 0; i < 4; i++)
{
MyClassArray[i] = new ClassObject();
}
numClasses = 0;
}
public int getNumClasses()
{
return numClasses;
}
public void dropClass(int c)
{
for (int i = c; i < 3; i++)
{
MyClassArray[i] = MyClassArray[i+1];
}
//MyClassList.updateMyClasses(MyClassArray);
}
public void addClass(ClassObject c)
{
if (numClasses >= 4)
return;
MyClassArray[numClasses] = c;
//MyClassList.updateMyClasses(MyClassArray);
}
public boolean hasClass(ClassObject c)
{
for (int i = 0; i < 4; i++)
{
if (MyClassArray[i].getClassName() == c.getClassName())
return true;
}
return false;
}
}
And here's the line that gives the error:
addButtonArray[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
MyClasses.addClass(ClassListArray[0]);
}
});
This line is your problem:
MyClasses.addClass(ClassListArray[0]);
You are trying to call the instance method addClass without giving the reference to a MyClasses instance. How you fix this depends on where the code is. Is it embedded in the MyClasses class?
Related
I'm creating an alarm clock application, and I'd like the homepage to have multiple Alarm objects shown, like the default Android clock application. To do this, I've been trying a ListView to create a button for each Alarm in an ArrayList of Alarms.
Debugging the crashes this caused, I've found that it can't implement Serializable or Parcelable due to the Context object within it, and thus I have no way to pass it from one activity to another. The ListView works fine when I create the alarms from the MainActivity itself, but when I use the CreateAlarmActivity that takes input from the user, the ListView won't pass through and it crashes.
I haven't found this precise problem on StackOverflow. This problem is close (Implementing Parcelable Class That Requires Context) but involves a database, which seems overkill for my needs.
If a ListView is even the best way to go about this, how should I pass the ListView between activities? If there's a better way, what would be a better implementation?
I apologise for the large amount of code. I'm not sure exactly what may prove relevant, so I've erred on the side of too much information rather than too little.
Code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ListView alarmListView;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
int[] testArray = {0, 0, 0, 0, 0, 0, 0};
Alarm testAlarm = new Alarm("testAlarm", 6, 1, true, testArray, 10);
Alarm testAlarm2 = new Alarm("testAlarm2", 6, 1, true, testArray, 10);
AlarmAdapter alarmAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmListView = (ListView) findViewById(R.id.alarmListView);
alarmList.add(testAlarm);
alarmList.add(testAlarm2);
alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList);
alarmListView.setAdapter(alarmAdapter);
alarmAdapter.notifyDataSetChanged();
}
// Create alarm when user presses FAB on activity_main.xml.
public void createNewAlarm(View view) {
Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
createAlarmIntent.putExtra("alarmList", alarmList);
createAlarmIntent.putExtra("alarmAdapter", alarmAdapter);
startActivity(createAlarmIntent);
}
public void testAlarmActivated(View view){
Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
startActivity(activateAlarmIntent);
}
}
AlarmAdapter.java:
public class AlarmAdapter extends BaseAdapter implements Parcelable {
private Context alarmContext;
private ArrayList<Alarm> alarmList;
public AlarmAdapter(Context context, ArrayList arrayList) {
super();
alarmContext = context;
alarmList = arrayList;
}
public int getCount() {
return alarmList.size();
}
// getView method is called for each item of ListView
public View getView(int position, View view, ViewGroup parent) {
// inflate the layout for each item of listView
LayoutInflater inflater = (LayoutInflater) alarmContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.alarm_row, parent, false);
// get the reference of textView and button
TextView alarmName = (TextView) view.findViewById(R.id.title);
// Button alarmButton = (Button) view.findViewById(R.id.alarmButton);
// Set the title and button name
Alarm tempAlarm = alarmList.get(position);
alarmName.setText(tempAlarm.name);
// btnAction.setText("Action " + position);
// Click listener of button
/*btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Logic goes here
}
});*/
return view;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
protected AlarmAdapter(Parcel in) {
alarmContext = (Context) in.readValue(Context.class.getClassLoader());
if (in.readByte() == 0x01) {
alarmList = new ArrayList<Alarm>();
in.readList(alarmList, Alarm.class.getClassLoader());
} else {
alarmList = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(alarmContext);
if (alarmList == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(alarmList);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<AlarmAdapter> CREATOR = new Parcelable.Creator<AlarmAdapter>() {
#Override
public AlarmAdapter createFromParcel(Parcel in) {
return new AlarmAdapter(in);
}
#Override
public AlarmAdapter[] newArray(int size) {
return new AlarmAdapter[size];
}
};
}
Alarm.java:
public class Alarm implements Serializable {
String name;
int hour;
int minute;
boolean isPm;
int[] daysActive;
int snoozeTimer;
public Alarm(String startName, int startHour, int startMinute,
Boolean startIsPm, int[] startDaysActive, int startSnoozeTimer){
name = startName;
hour = startHour;
minute = startMinute;
isPm = startIsPm;
daysActive = startDaysActive;
snoozeTimer = startSnoozeTimer;
}
}
CreateAlarmActivity.java:
public class CreateAlarmActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
alarmAdapter = (AlarmAdapter)getIntent().getParcelableExtra("alarmAdapter)");
}
int alarmHour = 6;
int alarmMinute = 0;
boolean isPm = false;
int snoozeTimer = 10;
int [] daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
AlarmAdapter alarmAdapter;
// Add one to the hour of the alarm.
public void changeHour(View view) {
Button btn = findViewById(R.id.buttonHours);
if (alarmHour == 12){
alarmHour = 0;
}
else {
alarmHour++;
}
btn.setText(Integer.toString(alarmHour));
}
// Add one to the minute of the alarm.
public void changeMinute(View view) {
Button btn = findViewById(R.id.buttonMinutes);
if (alarmMinute == 59) {
alarmMinute = 0;
}
else {
alarmMinute++;
}
if (alarmMinute < 10) {
// Ensure minute 1 becomes 01, e.g, 6:01 am.
btn.setText("0" + Integer.toString(alarmMinute));
}
else {
btn.setText(Integer.toString(alarmMinute));
}
}
public void changeAmPm(View view) {
Button btn = findViewById(R.id.buttonAmPm);
if (isPm == true) {
isPm = false;
btn.setText("am");
}
else {
isPm = true;
btn.setText("pm");
}
}
public void changeSnoozeTimer(View view) {
Button btn = findViewById(R.id.buttonSnoozeTimer);
if (snoozeTimer == 15){
snoozeTimer = 1;
}
else {
snoozeTimer++;
}
btn.setText(Integer.toString(snoozeTimer));
}
public void finishAlarm(View view){
EditText alarmName = findViewById(R.id.alarmName);
String name = alarmName.getText().toString();
Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
alarmList.add(alarm);
alarmAdapter.notifyDataSetChanged();
Intent finishAlarmIntent = new Intent(this, MainActivity.class);
finishAlarmIntent.putExtra("alarmList", alarmList);
startActivity(finishAlarmIntent);
}
public void cancelAlarm(View view){
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
startActivity(cancelAlarmIntent);
}
public void changeSunday(View view) {
Button btn = findViewById(R.id.buttonSunday);
if (daysActive[0] == 0){
daysActive[0] = 1;
// Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
// Credit goes to EddieB for the below line.
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[1] = 0;
// Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
// Credit goes to Ivo for the below line.
btn.getBackground().clearColorFilter();
}
}
public void changeMonday(View view) {
Button btn = findViewById(R.id.buttonMonday);
if (daysActive[1] == 0){
daysActive[1] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[1] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeTuesday(View view) {
Button btn = findViewById(R.id.buttonTuesday);
if (daysActive[2] == 0){
daysActive[2] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[2] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeWednesday(View view) {
Button btn = findViewById(R.id.buttonWednesday);
if (daysActive[3] == 0){
daysActive[3] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[3] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeThursday(View view) {
Button btn = findViewById(R.id.buttonThursday);
if (daysActive[4] == 0){
daysActive[4] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[4] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeFriday(View view) {
Button btn = findViewById(R.id.buttonFriday);
if (daysActive[5] == 0){
daysActive[5] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[5] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeSaturday(View view) {
Button btn = findViewById(R.id.buttonSaturday);
if (daysActive[6] == 0){
daysActive[6] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[6] = 0;
btn.getBackground().clearColorFilter();
}
}
}
Here i have declared the product class variables and assigned it.
product.java
public class Product {
String[] name= new String[100];
int price;
int image;
boolean box;
Product(String[] _describe, int _price, int _image, boolean _box) {
name = _describe;
price = _price;
image = _image;
box = _box;
}
}
This is my product class. What should i change in the above coding??
public class MainActivity extends Activity {
String[] data =new String[] {"no:1","no:2","no:3","no:4","no:5","no:6"};
String[] columnTags = new String[] {"ProcessName", "IpItem", "IpColor", "OpItem","OpColor", "PlanQty", "DcQty", "RecQty", "RtQty"};
ArrayList products = new ArrayList();
ListAdapter1 boxAdapter;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillData();
boxAdapter = new ListAdapter1(this, products);
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
}
void fillData() {
for (int i = 0; i <= 20; i++) {
products.add(new Product(columnTags, i * 100,i * 553
, false));
}
}
public void showResult(View v) {
String result = "Selected Product are :";
int totalAmount=0;
for (Product p : boxAdapter.getBox()) {
if (p.box){
result += "\n" + p.name;
totalAmount+=p.image;
}
}
String total="Total="+totalAmount;
// Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
Bundle bundle=new Bundle();
bundle.putString("res",result);
bundle.putString("tot",total);
Intent intent = new Intent(MainActivity.this,MainActivity2Activity.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
The first parameter of your add() requires a String[] and you are passing it a String.
Just change ,
products.add(columnTags[i],i*100,i*553,false)
to
products.add(columnTags,i*100,i*553,false)
Also do the following,
for(...)
{
String temp = columnTags[i];
products.add(temp,i*100,i*553,false)
}
EDIT
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillData();
ArrayAdapter boxAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, new ArrayList<String>(Arrays.asList(products.name)));
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
}
void fillData() {
String temp;
for (int i = 0; i <columnTags.length; i++) {
temp = columnTags[i];
products.add(new Product(temp, i * 100,i * 553, false));
}
}
So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.
I am populating a Scrollview using items retrieved from a SQLite database, and am dynamically generating an OnClickListener for each row using the code below. I want the code in the OnClickListener to return control to the Activity which called it (MealActivity) using an Intent, passing back the id of the item which was clicked on.
I've attempted this using the 2nd code segment below, but I'm getting a compile error: "The method startActivity(Intent, int) is undefined for the type OnClickListenerSelectPresetItem".
How can I invoke the original Activity from my OnClickListener?
public class SelectPresetItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_preset_item);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
readRecords();
}
public void readRecords() {
LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<preset_item> preset_item = new TableControllerPresetItem(this).read();
if (preset_item.size() > 0) {
for (preset_item obj : preset_item) {
long id = obj.id;
String PresetDesc = obj.preset_desc;
int PresetMinutes = obj.preset_minutes;
String textViewContents = PresetDesc + " - "
+ PresetMinutes + " minutes";
TextView textViewItem = new TextView(this);
textViewItem.setPadding(0, 10, 0, 10);
textViewItem.setText(textViewContents);
textViewItem.setTag(Long.toString(id));
textViewItem.setOnClickListener(new OnClickListenerSelectPresetItem());
linearLayoutRecords.addView(textViewItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}listener
The method startActivity(Intent, int) is undefined for the type OnClickListenerSelectPresetItem
public class SelectPresetItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_preset_item);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
readRecords();
}
public void readRecords() {
LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<preset_item> preset_item = new TableControllerPresetItem(this).read();
if (preset_item.size() > 0) {
for (preset_item obj : preset_item) {
long id = obj.id;
String PresetDesc = obj.preset_desc;
int PresetMinutes = obj.preset_minutes;
String textViewContents = PresetDesc + " - "
+ PresetMinutes + " minutes";
TextView textViewItem = new TextView(this);
textViewItem.setPadding(0, 10, 0, 10);
textViewItem.setText(textViewContents);
textViewItem.setTag(Long.toString(id));
textViewItem.setOnClickListener(new OnClickListenerSelectPresetItem());
linearLayoutRecords.addView(textViewItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
This is the OnCLickListener code:
public class OnClickListenerSelectPresetItem implements OnClickListener {
public final static String EXTRA_MEAL_ID = "com.ian.mealtimer.MEAL_ID";
#Override
public void onClick(View view) {
Long selectedMealId = Long.valueOf(view.getTag().toString());
Intent myIntent = new Intent(view.getContext(),
MealActivity.class);
long mealId = -1;
myIntent.putExtra(EXTRA_MEAL_ID, selectedMealId);
startActivity(myIntent, 0);
}
}
You should use:
startActivity (Intent intent)
there is a different method which has an integer parameter:
startActivityForResult (Intent intent, int requestCode)
Also a context can start an activity, so you have to get the context. Easily you can get it from your view:
#Override
public void onClick(View view) {
Long selectedMealId = Long.valueOf(view.getTag().toString());
Intent myIntent = new Intent(view.getContext(),
MealActivity.class);
long mealId = -1;
myIntent.putExtra(EXTRA_MEAL_ID, selectedMealId);
view.getContext().startActivity(myIntent);
}
You can read more about starting activities here.
startActivity is a method of the class Context. The OnClickListener cannot know on which context it should be called. Pass the Context as Parameter to the constructor of the OnClickListener and save it inside:
In class OnClickListenerSelectPresetItem:
private Context context;
public OnClickListenerSelectPresetItem(Context context){
this.context=context;
}
Then call startActivity on this context
this.context.startActivity(myIntent, 0);
And construct them by passing the activity
textViewItem.setOnClickListener(new OnClickListenerSelectPresetItem(this));
How about you pass the activity to the constructor of the OnClickListenerSelectPresetItem
and then use it like the following :
public class OnClickListenerSelectPresetItem implements OnClickListener {
public final static String EXTRA_MEAL_ID = "com.ian.mealtimer.MEAL_ID";
private SelectPresetItemActivity selectPresetItemActivity;
public OnClickListenerSelectPresetItem(SelectPresetItemActivity selectPresetItemActivity){
this.selectPresetItemActivity = selectPresetItemActivity;
}
#Override
public void onClick(View view) {
Long selectedMealId = Long.valueOf(view.getTag().toString());
Intent myIntent = new Intent(view.getContext(),
MealActivity.class);
long mealId = -1;
myIntent.putExtra(EXTRA_MEAL_ID, selectedMealId);
selectPresetItemActivity.startActivity(myIntent, 0);
}
}
I'm newbie in java. So the program should take the user entered text and if there is "a" it gonna play a-sound, if there is "b" it gonna play b-sound.And it must play this sounds one by one even if there are multiple "a" or "b". Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bStart = (Button) findViewById(R.id.bStart);
final EditText etStart = (EditText) findViewById(R.id.etStart);
final EditText etFinish = (EditText) findViewById(R.id.etFinish);
final char[] arr = etStart.getText().toString().toCharArray();
final MediaPlayer as = MediaPlayer.create(R2d2Activity.this, R.raw.as);
final MediaPlayer bs = MediaPlayer.create(R2d2Activity.this, R.raw.bs);
final SoundPool sp;
final int a;
final int b;
final int t;
sp = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
a = sp.load(this, R.raw.as, 1);
b = sp.load(this, R.raw.bs, 1);
final String value = etStart.getText().toString();
final Thread timer = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1300);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
}
});
bStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int n = 0;
String value;
String first;
value = etStart.getText().toString();
// TODO Auto-generated method stub
//actual code
for (int i=0; i<value.length(); i++){
first = etStart.getText().toString().substring(i, i+1);
if(first.contentEquals("a")){
as.start();
as.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer arg0) {
//when finished
}
});
}else{
}
if(first.contentEquals("b")){
bs.start();
}else{
}
}
}
});
The problem is that it starts playing audio files all at one time. I tried to add some OnCompletionListener, but I don't know what to do with it. Help me please.
What you can do is
//define a variable to be used as index.
int audioindex = 0;
//Extract the files id into an array
int[] audioFileIds=new int[]{R.raw.as,R.raw.bs};
Then in your MediaPlayer onCompletionListener put something like following.
then in your OnCompletionListener.
mp.setOnCompletionListener(new OnCompletionListener(){
// #Override
public void onCompletion(MediaPlayer player) {
// File has ended, play the next one.
FunctionPlayFile(audioFileIds[audioindex]);
audioindex+=1; //increment the index to get the next audiofile
}
});