My app in Android Studio is OK but when I run it, it tells me your app has closed. The application is a card game.
My code:
## Heading ##
public class MainActivity extends Activity {
*Button btn_retry;*
*int lastImageView = 0;
int beforLastImageView = 0;
int lastCard=0;
int beforLastCard=0;
int imageNumber=0;
int beforImageNumber=0;
int numberOfCards = 6;
int numberOfImages = 30;*
final ImageView[] Imageview = new ImageView[numberOfCards];
int[] Imageview_Id = {R.id.img1, R.id.img2, R.id.img3,
R.id.img4, R.id.img5, R.id.img6};
final int[] images = {R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i4, R.drawable.i5,
R.drawable.i6, R.drawable.i7, R.drawable.i8, R.drawable.i9, R.drawable.i10,
R.drawable.i11, R.drawable.i12, R.drawable.i13, R.drawable.i14, R.drawable.i15,
R.drawable.i16, R.drawable.i17, R.drawable.i18, R.drawable.i19, R.drawable.i20,
R.drawable.i21, R.drawable.i22, R.drawable.i23, R.drawable.i24, R.drawable.i25,
R.drawable.i26, R.drawable.i27, R.drawable.i28, R.drawable.i29, R.drawable.i30,
R.drawable.i31, R.drawable.i32, R.drawable.i33, R.drawable.i34, R.drawable.i35,
R.drawable.i36, R.drawable.i37, R.drawable.i38, R.drawable.i39, R.drawable.i40};
final List<Integer> cardlist = new ArrayList<Integer>();
#Override
**protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickOnButton1();**
final List<Integer> imagelist = new ArrayList<Integer>();
for (int i = 0; i < numberOfCards; i++) {
imagelist.add(i);
}
Collections.shuffle(imagelist);
for (int i = 0; i < numberOfCards; i++) {
Imageview[i] = (ImageView) findViewById(Imageview_Id[i]);
}
final List<Integer> cardlist = new ArrayList<Integer>();
for (int i = 0; i< numberOfCards / 2; i++) {
cardlist.add(imagelist.get(i));
}
for (int i=numberOfCards/2;i<numberOfCards;i++){
cardlist.add(imagelist.get(i-numberOfCards/2));
}
Collections.shuffle(cardlist);
for (int i=0 ; i<numberOfCards;i++){
Imageview[i].setOnClickListener(onClickImage);
}
};
protected View.OnClickListener onClickImage= new
View.OnClickListener() {
**#Override
public void onClick(final View v) {**
switch (v.getId()){
case(R.id.img1):
imageNumber = 1;
case(R.id.img2):
imageNumber = 2;
case(R.id.img3):
imageNumber = 3;
case(R.id.img4):
imageNumber = 4;
case(R.id.img5):
imageNumber = 5;
case(R.id.img6):
imageNumber = 6;
}
android.os.Handler handler =new android.os.Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
String imageName="i"+cardlist.get(imageNumber);
int res = getResources().getIdentifier(imageName, "drawable", "com.example.arash.card");
Imageview[imageNumber].setImageResource(res);
lastImageView=(v.getId());
lastCard=cardlist.get(imageNumber);
}
},1000);
if (lastImageView != beforLastImageView) {
if (lastCard == beforLastCard) {
Imageview[imageNumber].setVisibility(View.INVISIBLE);
Imageview[imageNumber].setEnabled(false);
Imageview[beforImageNumber].setVisibility(View.INVISIBLE);
Imageview[beforImageNumber].setEnabled(false);
beforLastCard = 0;
beforLastImageView = 0;
lastCard = 0;
lastImageView = 0;
} else {
beforLastImageView = lastImageView;
beforLastCard = lastCard;
}
}
beforImageNumber=imageNumber;
}
};
**public void clickOnButton1() {**
final Context context = this;
btn_retry = (Button) findViewById(R.id.button);
btn_retry.setOnClickListener(new View.OnClickListener() {
***#Override***
public void onClick(View arg0) {
Intent intent = new Intent(context, MainActivity.class);
finish();
*startActivity(intent);*
}
});
}
Related
I want to make view by adding child list on android using cardview in recycleview.
i have made class to store these item and make arraylist on each parent of object if the object have child item, so i can differentiate if the list has child or not.
But i have difficulties to render the same layout to make the child list below the parent list. I am pragmatically make the layout one by one but it will be difficult to make that. So i want to render the same layout to my adapter when i want to make a child list whenever the object/class has arraylist of child list in that object.
this is my adapter right now
public class NotificationListAdapter extends BaseListAdapter<NotificationData, NotificationListAdapter.CustomViewHolder> {
private List<NotificationData> notificationData;
private ArrayList<Integer> indexForHide;
public NotificationListAdapter(Context context) {
super(context);
}
#Override
public void addAll(List<NotificationData> items) {
super.addAll(items);
this.notificationData = items;
}
void setChildNotif(){
ArrayList<NotificationData> childDataItems;
List<NotificationData> notificationDataChild = new ArrayList<NotificationData>();
notificationDataChild.addAll(notificationData);
indexForHide = new ArrayList<Integer>();
for (int i = 0; i < notificationData.size(); i++) {
childDataItems = new ArrayList<>();
if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}
for (int j = i; j < notificationDataChild.size(); j++){
if(i==j){
continue;
}else if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}else{
if(notificationDataChild.get(j).getRfqId()!=0){
if(notificationDataChild.get(j).getRfqId()==notificationData.get(i).getRfqId()){
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
if(!notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase("")) {
if (notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase(notificationData.get(i).getInvoiceNumber())) {
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
}
}
notificationData.get(i).setChildNotification(childDataItems);
Log.d("sizeNotif", i+" :"+notificationData.get(i).getChildNotification().size());
}
Log.d("sizeNotification", " :"+notificationData.size());
Log.d("sizeNotificationDummy", " :"+notificationData.size());
Log.d("isiHideAdapter", Arrays.toString(indexForHide.toArray()));
Log.d("isiHideAdapterSize", indexForHide.size()+"");
}
#Override
protected int getItemResourceLayout(int viewType) {
return R.layout.item_notification_list;
}
int position;
#Override
public int getItemViewType(int position) {
this.position = position;
return position;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
setChildNotif();
return new CustomViewHolder(getView(parent, viewType), onItemClickListener);
}
public class CustomViewHolder extends BaseViewHolder<NotificationData> {
private TextView tvNotifTitle, tvNotifBody, tvNotifStatus, tvNotifTime, tvSignUnread, tvHeaderTitle;
private CardView formContent;
private LinearLayout linearLayout_childItems;
private ImageView expandList;
public CustomViewHolder(View itemView, OnItemClickListener onItemClickListener) {
super(itemView, onItemClickListener);
tvNotifTitle = itemView.findViewById(R.id.tvNotifTitle);
tvNotifBody = itemView.findViewById(R.id.tvNotifBody);
// tvNotifStatus = itemView.findViewById(R.id.tvNotifStatus);
tvNotifTime = itemView.findViewById(R.id.tvNotificationTime);
formContent = itemView.findViewById(R.id.formContent);
tvSignUnread = itemView.findViewById(R.id.tvSignUnread);
tvHeaderTitle = itemView.findViewById(R.id.tvHeaderNotifList);
linearLayout_childItems = itemView.findViewById(R.id.ll_child_items);
expandList = itemView.findViewById(R.id.arrow_expand_notif_list);
//SET CHILD
int intMaxNoOfChild = 0;
for (int index = 0; index < notificationData.size(); index++) {
int intMaxSizeTemp = notificationData.get(index).getChildNotification().size();
if (intMaxSizeTemp > intMaxNoOfChild) intMaxNoOfChild = intMaxSizeTemp;
}
linearLayout_childItems.removeAllViews();
for (int indexView = 0; indexView < intMaxNoOfChild; indexView++) {
TextView textView = new TextView(context);
textView.setId(indexView);
textView.setPadding(20, 20, 0, 20);
textView.setGravity(Gravity.LEFT);
textView.setTextSize(14);
textView.setTextColor(ContextCompat.getColor(context, R.color.colorText));
textView.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_sub_notif_text));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 16;
textView.setOnClickListener(this);
linearLayout_childItems.addView(textView, layoutParams);
}
}
#Override
public void bind(NotificationData item) {
String title = splitString(item.getTitle());
tvNotifTitle.setText(title);
tvNotifBody.setText(item.getContent());
String txtTime = item.getCreatedAtDisplay().replaceAll("WIB", "");
tvNotifTime.setText(txtTime);
if (position == 0) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).topMargin = dpToPx(12);
}
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(12);
if (position == getItemCount() - 1) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(80);
}
if(item.getIsRead()==1){
formContent.setCardBackgroundColor(context.getResources().getColor(R.color.gray1));
formContent.setCardElevation(5);
formContent.setRadius(15);
tvSignUnread.setVisibility(View.GONE);
}else if(item.getIsRead()==0){
}
//setHeader
Calendar calendar;
SimpleDateFormat dateFormat;
calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
String date, yesterdayDate, dateDisplayData, dateData;
date = dateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE, -1);
yesterdayDate = dateFormat.format(calendar.getTime());
String[] arrDateDisplayData = item.getCreatedAtDisplay().split(",", 5);
dateDisplayData = arrDateDisplayData[0];
String[] arrDateData = item.getCreatedAt().split(" ", 5);
dateData = arrDateData[0];
Log.d("datenow", date);
Log.d("dateyesterday", yesterdayDate);
Log.d("dateDisplayData", dateDisplayData);
Log.d("dateData", dateData);
if(dateData.equalsIgnoreCase(date)){
tvHeaderTitle.setText("Hari ini");
}else if(dateData.equalsIgnoreCase(yesterdayDate)){
tvHeaderTitle.setText("Kemarin");
}else{
tvHeaderTitle.setText(dateDisplayData);
// tvHeaderTitle.setVisibility(View.GONE);
}
if (getAdapterPosition() > 0) {
String[] timePrev = notificationData.get(getAdapterPosition() - 1).getCreatedAt().split(" ");
if (dateData.equalsIgnoreCase(timePrev[0])) {
tvHeaderTitle.setVisibility(View.GONE);
}
}
if(indexForHide.contains(getAdapterPosition())){
formContent.setVisibility(View.GONE);
}
//SET CHILD
NotificationData dummyParentDataItem = notificationData.get(position);
int noOfChildTextViews = linearLayout_childItems.getChildCount();
for (int index = 0; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
currentTextView.setVisibility(View.VISIBLE);
}
int noOfChild = 0;
if(dummyParentDataItem.getChildNotification()==null){
noOfChild = 0;
}else{
noOfChild = dummyParentDataItem.getChildNotification().size();
}
if (noOfChild < noOfChildTextViews) {
for (int index = noOfChild; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
// currentTextView.setVisibility(View.GONE);
}
}
for (int textViewIndex = 0; textViewIndex < noOfChild; textViewIndex++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(textViewIndex);
currentTextView.setText(dummyParentDataItem.getChildNotification().get(textViewIndex).getTitle());
/*currentTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "" + ((TextView) view).getText().toString(), Toast.LENGTH_SHORT).show();
}
});*/
}
if (noOfChild > 0) {
expandList.setVisibility(View.VISIBLE);
expandList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (linearLayout_childItems.getVisibility() == View.VISIBLE) {
linearLayout_childItems.setVisibility(View.GONE);
// Toast.makeText(context, "expand", Toast.LENGTH_SHORT).show();
expandList.setImageResource(R.drawable.ic_arrow_up_blue);
}
else {
linearLayout_childItems.setVisibility(View.VISIBLE);
expandList.setImageResource(R.drawable.ic_arrow_down_blue);
}
}
});
}else {
linearLayout_childItems.setVisibility(View.GONE);
}
}
public int dpToPx(int dp) {
Resources r = context.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp, r.getDisplayMetrics()
);
return px;
}
public String splitString(String tempString){
StringBuilder finalString = new StringBuilder(tempString);
int i = 0;
while ((i = finalString.indexOf(" ", i + 20)) != -1) {
finalString.replace(i, i + 1, "\n");
}
return finalString.toString();
}
}
}
please help me to render my layout whenever i want to make a child list under my parent list so i can simplify my code above and not making the child layout programatically
Can not trigger on Click listener
I tried
setClickable(true);
but still not working
minimum sdk is 15
the code doesn't have xml file, i need to fix it programmatically
the complete code:
public class MainActivity extends AppCompatActivity {
private static char CHAR = 'a';
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
int rowNo = ROWS;
int colNo = (screenWidth().widthPixels * ROWS /screenWidth().heightPixels) ;
for (int i = 0; i < 5; i++) {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
for (int j = 0; j < 5; j++) {
String txt = String.valueOf(CHAR);
Cell cell = new Cell(this, txt, 50, 50);
cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("value is " + txt);
}
});
row.addView(cell);
CHAR += 1;
}
layout.addView(row);
}
setContentView(layout);
}
private class Cell extends LinearLayout{
public Cell(Context context, final String value, int width, int height) {
super(context);
LinearLayout.LayoutParams cellParams = new LinearLayout.LayoutParams(width, height);
setLayoutParams(cellParams);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(getGradientDrawable());
}else{
setBackgroundDrawable(getGradientDrawable());
}
}
private GradientDrawable getGradientDrawable() {
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setColor(Color.TRANSPARENT);
shape.setStroke(2, Color.BLACK);
return shape;
}
}
}
so, why and how to fix it.
at clicking the associated text will be printed
Try onClickListener inside your loop
Cell cell = new Cell(this, txt, 50, 50);
cell.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("value is " + value);
}
});
I have a global variable inext set to a random value correctly before a call to setWordsQuestion(). As soon as I enter setWordsQuestion() the value is 0. Do you know how I can debug this?
and reset to 0:
Here is the java file:
public class ExercisesWords_fragment extends Fragment {
static Context context;
String login;
String fileMenuCard = null;
InputStreamReader isr;
InputStream fIn;
BufferedReader input_card = null;
int level, lang;
int ihelp;
String fileLogin;
RadioGroup rg;
RadioButton rb1, rb2, rb3, rb4;
EditText edt;
TextView txt, question;
Button validation, next, help;
int MAXWORDS = 42;
String[] words_questions = new String[MAXWORDS];
String[] words_cb1 = new String[MAXWORDS];
String[] words_cb2 = new String[MAXWORDS];
String[] words_cb3 = new String[MAXWORDS];
String[] words_cb4 = new String[MAXWORDS];
String[] words_response = new String[MAXWORDS];
int[] words_level = new int[MAXWORDS];
int MAXTEMP = 5;
int[] tmp;
int inext_question, inext;
public ExercisesWords_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.exercises_words_fragment, container, false);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
}
#Override
public void onPause() {
closeFileWords();
super.onPause();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
context = getActivity().getApplicationContext();
fileMenuCard = "words";
login = getArguments().getString("login");
lang = getArguments().getInt("lang");
level = getArguments().getInt("level");
fileLogin = login + "_words.txt";
initViewFind();
initExerciseWords();
nextWordsQuestion();
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
edt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
validateResponse();
}
return false;
}
});
validation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateResponse();
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nextWordsQuestion();
}
});
help.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ihelp = 1;
hideKeyboard();
helpWords();
ihelp = 0;
}
});
}
private void drawBTN() {
if(lang == 0) {
validation.setText(R.string.pro_validation);
validation.setVisibility(View.VISIBLE);
next.setText(R.string.next);
next.setVisibility(View.VISIBLE);
help.setText(R.string.help);
help.setVisibility(View.VISIBLE);
}
else {
validation.setText(R.string.pro_validation_fr);
validation.setVisibility(View.VISIBLE);
next.setText(R.string.next_fr);
next.setVisibility(View.VISIBLE);
help.setText(R.string.help_fr);
help.setVisibility(View.VISIBLE);
}
}
private void nextWordsQuestion() {
int inext;
Random r;
r = new Random();
inext = r.nextInt(MAXWORDS);
if (inext_question < MAXTEMP) {
tmp[inext_question] = inext;
inext_question++;
setWordsQuestion();
return;
}
for (int i = 0; i < MAXTEMP; i++) {
if (inext == tmp[i]) {
r = new Random();
inext = r.nextInt(MAXWORDS);
i--;
}
}
System.arraycopy(tmp, 1, tmp, 0, MAXTEMP - 1);
tmp[MAXTEMP - 1] = inext;
setWordsQuestion();
}
private void setWordsQuestion(){
question.setText(words_questions[inext]);
question.setVisibility(View.VISIBLE);
edt.setText("");
rb1.setText(words_cb1[inext]);
rb2.setText(words_cb2[inext]);
rb3.setText(words_cb3[inext]);
rb4.setText(words_cb4[inext]);
rb1.setVisibility(View.INVISIBLE);
rb2.setVisibility(View.INVISIBLE);
rb3.setVisibility(View.INVISIBLE);
rb4.setVisibility(View.INVISIBLE);
rg.clearCheck();
hideKeyboard();
}
private void validateResponse(){
String response;
if(ihelp == 1){
int sel = rg.getCheckedRadioButtonId();
if(sel < 0) return;
RadioButton rb = (RadioButton) getActivity().findViewById(sel);
response = rb.getText().toString();
}
else {
response = edt.getText().toString();
}
TextView resp = (TextView) getActivity().findViewById(R.id.resp_words);
if(response.equals(words_response[inext])) {
next.setTextColor(Color.GREEN);
next.setVisibility(View.VISIBLE);
resp.setText(R.string.resp_card);
resp.setTextColor(Color.GREEN);
resp.setVisibility(View.VISIBLE);
}
else {
resp.setText(R.string.resp_card_no);
resp.setTextColor(Color.RED);
resp.setVisibility(View.VISIBLE);
}
}
private void helpWords(){
hideKeyboard();
rb1.setText(words_cb1[inext]);
rb1.setVisibility(View.VISIBLE);
rb2.setText(words_cb2[inext]);
rb2.setVisibility(View.VISIBLE);
rb3.setText(words_cb3[inext]);
rb3.setVisibility(View.VISIBLE);
rb4.setText(words_cb4[inext]);
rb4.setVisibility(View.VISIBLE);
}
private void hideKeyboard(){
EditText e = (EditText) getActivity().findViewById(R.id.words_answer);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(e.getWindowToken(), 0);
}
private void openWords(){
String l = null;
try {
if (lang == 0)
fIn = context.getResources().getAssets()
.open(fileMenuCard+".txt", Context.MODE_PRIVATE);
else
fIn = context.getResources().getAssets()
.open(fileMenuCard+"_fr.txt", Context.MODE_PRIVATE);
isr = new InputStreamReader(fIn);
input_card = new BufferedReader(isr);
} catch (Exception e) {
e.getMessage();
}
for(int i=0;i<MAXWORDS;i++){
try {
l = input_card.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (l != null) {
StringTokenizer tokens = new StringTokenizer(l, ";");
words_questions[i] = tokens.nextToken();
words_level[i] = Integer.valueOf(tokens.nextToken());
words_cb1[i] = tokens.nextToken();
words_cb2[i] = tokens.nextToken();
words_cb3[i] = tokens.nextToken();
words_cb4[i] = tokens.nextToken();
words_response[i] = tokens.nextToken();
}
}
}
private void closeFileWords(){
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
input_card.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initExerciseWords(){
tmp = new int[MAXTEMP];
for(int i=0;i<MAXTEMP;i++)
tmp[i] = -1;
inext_question = 0;
openWords();
}
private void initViewFind(){
edt = (EditText) getActivity().findViewById(R.id.words_answer);
txt = (TextView) getActivity().findViewById(R.id.title_words);
validation = (Button) getActivity().findViewById(R.id.validation_words);
next = (Button) getActivity().findViewById(R.id.next_words);
help = (Button) getActivity().findViewById(R.id.help_words);
question = (TextView) getActivity().findViewById(R.id.words_question);
rg = (RadioGroup) getActivity().findViewById(R.id.rg_words);
rb1 = (RadioButton) getActivity().findViewById(R.id.radio1_words);
rb2 = (RadioButton) getActivity().findViewById(R.id.radio2_words);
rb3 = (RadioButton) getActivity().findViewById(R.id.radio3_words);
rb4 = (RadioButton) getActivity().findViewById(R.id.radio4_words);
if(lang == 0)
txt.setText(R.string.words_fr);
else
txt.setText(R.string.words_title_fr);
}
}
You are setting a local variable that hides the instance member :
private void nextWordsQuestion() {
int inext; // remove this line
...
inext = r.nextInt(MAXWORDS);
...
setWordsQuestion();
...
}
Therefore setWordsQuestion, which uses the instance member, doesn't see the value you set in nextWordsQuestion.
When you assign a random value to inext, you are assigning it to a local variable, not the global one.
To fix, simply remove the local variable.
private void nextWordsQuestion() {
//int inext;
Random r;
r = new Random();
inext = r.nextInt(MAXWORDS);
if (inext_question < MAXTEMP) {
tmp[inext_question] = inext;
inext_question++;
setWordsQuestion();
return;
}
Hi there i've been constructing this code for a week but i still cant get it to work. It has no errors but when i run it on the AVD it terminates suddenly.
package com.tryout.sample;
import java.util.Random;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements View.OnClickListener{
Random number = new Random();
int Low = 1;
int High = 13;
int RandomNumber = number.nextInt(High-Low) + Low;
int current = 0;
int points=0;
final Integer[] cardid = { R.drawable.card1,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
};
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView score = (TextView) findViewById(R.id.textView2);
Button high = (Button) findViewById(R.id.button1);
Button low = (Button) findViewById(R.id.button2);
final ImageView pic = (ImageView) findViewById(R.id.imageView1);
low.setOnClickListener(new view.OnClickListener() {
public void onClick(View v) {
int resource = cardid[RandomNumber];
if(current < RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
high.setOnClickListener(new View.OnClickListener() {
public void higher(View v) {
int resource = cardid[RandomNumber];
if(current > RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
int resource = cardid[RandomNumber];
pic.setImageResource(resource);
current = RandomNumber;
}
}
I cant figure out where my problem is, kindly check out my code. THanks for any help
put this:
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
in you onCreate method after the call setContentView(R.layout.activity_main);.
How should R.id.imageView1 assigned if the content is not specified like in your case?
ImageView pic2;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic2 = (ImageView) findViewById(R.id.imageView1);
score = (TextView) findViewById(R.id.textView2);
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class minigame_cardpairing extends Activity implements View.OnClickListener {
private static final int TOTAL_CARD_NUM = 16;
private int[] cardId = {R.id.card01, R.id.card02, R.id.card03, R.id.card04, R.id.card05, R.id.card06, R.id.card07, R.id.card08,
R.id.card09, R.id.card10, R.id.card11, R.id.card12, R.id.card13, R.id.card14, R.id.card15, R.id.card16};
private Card[] cardArray = new Card[TOTAL_CARD_NUM];
private int CLICK_CNT = 0;
private Card first, second;
private int SUCCESS_CNT = 0;
private boolean INPLAY = false;
//----------- Activity widget -----------//
private Button start;
//-----------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.minigame_cardpairing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for(int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i] = new Card(i/2);
findViewById(cardId[i]).setOnClickListener(this);
cardArray[i].card = (ImageButton) findViewById(cardId[i]); // Card assignment
cardArray[i].onBack();
}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startGame();
//start.setBackgroundDrawable(background);
}
});
findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
} // end of onCreate
protected void startDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("The match-card game. Please remember to flip the cards two by two card hand is a pair Hit. Hit all pairs are completed.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Game Description");
alt2.show();
}
protected void clearDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("It fits all the cards in pairs. Congratulations.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Match-complete");
alt2.show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
startDialog();
}
public void onClick(View v) {
if (INPLAY) {
switch (CLICK_CNT) {
case 0:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
first = cardArray[i];
break;
}
}
if (first.isBack) {
first.onFront();
CLICK_CNT = 1;
}
break;
case 1:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
second = cardArray[i];
break;
}
}
if (second.isBack) {
second.onFront();
if (first.value == second.value) {
SUCCESS_CNT++;
Log.v("SUCCESS_CNT", "" + SUCCESS_CNT);
if (SUCCESS_CNT == TOTAL_CARD_NUM/2) {
clearDialog();
}
}
else {
Timer t = new Timer(0);
t.start();
}
CLICK_CNT = 0;
}
break;
}
}
}
void startGame() {
int[] random = new int[TOTAL_CARD_NUM];
int x;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (!cardArray[i].isBack)
cardArray[i].onBack();
}
boolean dup;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
while(true) {
dup = false;
x = (int) (Math.random() * TOTAL_CARD_NUM);
for (int j=0; j<i; j++) {
if (random[j] == x) {
dup = true;
break;
}
}
if (!dup) break;
}
random[i] = x;
}
start.setClickable(false);
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].card = (ImageButton) findViewById(cardId[random[i]]);
cardArray[i].onFront();
}
Log.v("timer", "start");
Timer t = new Timer(1);
//flag = false;
t.start();
/*
while(true) {
if (flag) break;
//Log.v("flag", "" + flag);
}
Log.v("timer", "end");
*/
SUCCESS_CNT = 0;
CLICK_CNT = 0;
INPLAY = true;
}
class Timer extends Thread {
int kind;
Timer (int kind) {
super();
this.kind = kind;
}
#Override
public void run() {
INPLAY = false;
// TODO Auto-generated method stub
try {
if (kind == 0) {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
}
else if (kind == 1) {
Thread.sleep(3000);
mHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INPLAY = true;
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
first.onBack();
second.onBack();
first.isBack = true;
second.isBack = true;
}
else if (msg.what == 1) {
//flag = true;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].onBack();
}
start.setClickable(true);
}
}
};
}
class Card { // start of Card class
private final static int backImageID = R.drawable.cardback;
private final static int[] frontImageID = {R.drawable.card1, R.drawable.card2,
R.drawable.card3, R.drawable.card4,
R.drawable.card5, R.drawable.card6,
R.drawable.card7, R.drawable.card8};
int value;
boolean isBack;
ImageButton card;
Card(int value) {
this.value = value;
}
public void onBack() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
}
public void flip() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
else {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
public void onFront() {
if (isBack) {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
} // end of Card class
I have a service:
import android.app.IntentService;
import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.Button;
public class CustTimer extends IntentService {
int length;
long timeLeft;
Button button;
long endTime;
public CustTimer() {
super("CustTimer");
}
public CustTimer(int length, Button button) {
super("CustTimer");
this.length = length;
this.button = button;
this.endTime = System.currentTimeMillis() + length;
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
new CountDownTimer(length, 1000) {
public void onTick(long millisUntilFinished) {
String min = String.valueOf(millisUntilFinished/60000 );
long re = millisUntilFinished%60000;
String secs = String.valueOf(re/1000);
button.setText(min + ":" + secs);
timeLeft = millisUntilFinished;
}
public void onFinish() {
//button.setText("done");
}
}.start();
}
}
and an activity which calls it, the onCreate method is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = new Intent(this, CustTimer.class);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout l2 = new LinearLayout(this);
l2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout l3 = new LinearLayout(this);
l3.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout l4 = new LinearLayout(this);
l4.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout l5 = new LinearLayout(this);
l5.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams hor = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1f);
LayoutParams ver = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f);
for (int i = 0; i < 16; i++){
buts[i] = new Button(this);
buts[i].setText(String.valueOf(i+1));
timerRun[i] = false;
}
for (int i = 0; i < 4; i++) {
l2.addView(buts[i], hor);
}
for (int i = 4; i < 8; i++) {
l3.addView(buts[i], hor);
}
for (int i = 8; i < 12; i++) {
l4.addView(buts[i], hor);
}
for (int i = 12; i < 16; i++) {
l5.addView(buts[i], hor);
}
for (int i = 0; i < 16; i++) {
final int j = i;
buts[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CustTimer t1 = new CustTimer(times[j], buts[j]);
timers[j] = t1;
startService(intent);
}
});
}
ll.addView(l2, ver);
ll.addView(l3, ver);
ll.addView(l4, ver);
ll.addView(l5, ver);
this.setContentView(ll);
}
My problem is that the startService() call doesn't return any errors however it wont run. just looking for some basic input on if i've missed anything important to do with services
edit:
manifest section is:
<service android:name="CustTimer"> </service>
There's an easier way to implement a simple timer:
private final Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
// TODO: update button text, manipulate views, etc.
mHandler.postDelayed(mRunnable, 1000);
}
};
private void start() {
mHandler.postDelayed(mRunnable, 1000);
}
private void stop() {
mHandler.removeCallbacks(mRunnable);
}