I'm having trouble with making my randomly generated image, which is interpreted as a button, become clickable. Each leads to a different activity.
The random images work perfect actually, the only problem it's not clickable.
Here's my Main.java:
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final List<String> images = new ArrayList<String>();
for (int i=1; i<=13; i++) {
images.add("img"+i);
}
final Button imgView = (Button)findViewById(R.id.top1);
String imgName = null;
int id = 0;
Collections.shuffle(images, new Random());
imgName = images.remove(0);
imageRandomizer(imgName, id, imgView);
}
public void imageRandomizer(String imgName, int id, final Button imgView) {
id = getResources().getIdentifier(imgName,
"drawable",
getPackageName());
imgView.setBackgroundResource(id);
}
}
On my layout, I specified the id top1 as a Button. So the above code will look up to my drawable images, which have the names img1.jpg, img2.jpg, img3.jpg , until img13.jpg.
Making an ImageButton clickable to one activity without being dependent on the shown random image is easy, I can do it without problem.
But what I wanna make is something like, when img1.jpg is generated, it becomes clickable and leads to Activity1.java, for img2.jpg the intent goes to Activity2.java, etc.
EDIT
#Roflcoptr
Here's my OnClickListener:
private OnClickListener top_listener = new OnClickListener() {
public void onClick(View v) {
switch((Integer) v.getTag()) {
case 1:
Intent aid = new Intent(Main.this, ProjektAID.class);
startActivity(aid);
case 2:
Intent adh = new Intent(Main.this, ProjektADH.class);
startActivity(adh);
case 3:
Intent bos = new Intent(Main.this, ProjektBOS.class);
startActivity(bos);
case 4:
Intent brot = new Intent(Main.this, ProjektBROT.class);
startActivity(brot);
case 5:
Intent care = new Intent(Main.this, ProjektCARE.class);
startActivity(care);
case 6:
Intent caritas = new Intent(Main.this, ProjektCARITAS.class);
startActivity(caritas);
case 7:
Intent doc = new Intent(Main.this, ProjektDOC.class);
startActivity(doc);
case 8:
Intent drk = new Intent(Main.this, ProjektDRK.class);
startActivity(drk);
case 9:
Intent give = new Intent(Main.this, ProjektGIVE.class);
startActivity(give);
case 10:
Intent hive = new Intent(Main.this, ProjektHIV.class);
startActivity(hive);
case 11:
Intent jo = new Intent(Main.this, ProjektJOHANNITER.class);
startActivity(jo);
case 12:
Intent kind = new Intent(Main.this, ProjektKINDERHERZ.class);
startActivity(kind);
case 13:
Intent kult = new Intent(Main.this, ProjektKULTURGUT.class);
startActivity(kult);
}
}
};
and here's the randomizer method:
public void imageRandomizer(String imgName, int id, final Button imgView) {
id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
imgView.setTag(new Integer(1)); //example for image 1
if (imgName.equals("img1")) {
imgView.setTag(new Integer(1)); //example for image 1
} else if (imgName.equals("img2")) {
imgView.setTag(new Integer(2));
} else if (imgName.equals("img3")) {
imgView.setTag(new Integer(3));
} else if (imgName.equals("img4")) {
imgView.setTag(new Integer(4));
} else if (imgName.equals("img5")) {
imgView.setTag(new Integer(5));
} else if (imgName.equals("img6")) {
imgView.setTag(new Integer(6));
} else if (imgName.equals("img7")) {
imgView.setTag(new Integer(7));
} else if (imgName.equals("img8")) {
imgView.setTag(new Integer(8));
} else if (imgName.equals("img9")) {
imgView.setTag(new Integer(9));
} else if (imgName.equals("img10")) {
imgView.setTag(new Integer(10));
} else if (imgName.equals("img11")) {
imgView.setTag(new Integer(11));
} else if (imgName.equals("img12")) {
imgView.setTag(new Integer(12));
}
else if (imgName.equals("img13")) {
imgView.setTag(new Integer(13));
}
}
I would use a tag to identify the button. So in your imateRandomizer add a unique ID for each possible Image. I don't know how you can identify the images uniquely, but I'll show the example here for the name:
public void imageRandomizer(String imgName, int id, final Button imgView)
{
id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
if (imgName.equals("Name of the Image for your first activity") {
imgView.setTag(new Integer(1)); //example for image 1
} else if (imgName.equals("Name of the Image for your second activity") {
imgView.setTag(new Integer(2));
}
}
And then In your ClickListener you can check which tag the button has:
imgView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch((Integer) v.getTag()) {
case 1: //start Activity 1;
break;
case 2: //start Activity 2;
break;
}
}
});
Related
I cannot get the four multiple choice buttons and the question textView to display text. What happens is there is an intent transferred over with a selected category "who" or "what". That category is compared with the "who" and "what" if statements. If it is one of them then it is supposed to post the question and run through the ten question. I am using a switch case inside the if statement to help distinguish what button was clicked and move on. When I run the emulator it gets to the screen with four multiple choice buttons but nothing is display on the text or text view.
public class QuestionActivity extends AppCompatActivity {
List<QuestionsTable> whoQuesList;
List<QuestionsTable> whatQuesList;
int score=0;
int qid=0;
QuestionsTable currentWhatQ;
QuestionsTable currentWhoQ;
Button btnA, btnB, btnC, btnD;
Button butSkip;
TextView txtQuestion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
butSkip = (Button) findViewById(R.id.btnSkip);
MySQLiteHelper db = new MySQLiteHelper(this);
whoQuesList = db.getAllWhos();
whatQuesList = db.getAllWhos();
currentWhatQ = whatQuesList.get(qid);
currentWhoQ = whoQuesList.get(qid);
}
public void onClickQuestion(View txtViewQuestion) {
Bundle d = getIntent().getExtras();
int c = d.getInt("category");
String category = Integer.toString(c);
if ("Who".equals(category)) {
txtQuestion = (TextView) findViewById(R.id.txtViewQuestion);
btnA = (Button) findViewById(R.id.btnOptionA);
btnB = (Button) findViewById(R.id.btnOptionB);
btnC = (Button) findViewById(R.id.btnOptionC);
btnD = (Button) findViewById(R.id.btnOptionD);
setQuestionView();
switch (txtViewQuestion.getId()) {
case btnOptionA:
if (currentWhoQ.getAnswer().equals(btnA.getText())) {
score++;
}
if (qid < 10) {
currentWhoQ = whoQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
case btnOptionB:
if (currentWhoQ.getAnswer().equals(btnB.getText())) {
score++;
}
if (qid < 10) {
currentWhoQ = whoQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
case btnOptionC:
if (currentWhoQ.getAnswer().equals(btnC.getText())) {
score++;
}
if (qid < 10) {
currentWhoQ = whoQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
case R.id.btnOptionD:
if (currentWhoQ.getAnswer().equals(btnD.getText())) {
score++;
}
if (qid < 10) {
currentWhoQ = whoQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
}
}
if ("What".equals(category)) {
MySQLiteHelper db = new MySQLiteHelper(this);
whoQuesList = db.getAllWhos();
whatQuesList = db.getAllWhos();
currentWhatQ = whatQuesList.get(qid);
currentWhoQ = whoQuesList.get(qid);
txtQuestion = (TextView) findViewById(R.id.txtViewQuestion);
btnA = (Button) findViewById(R.id.btnOptionA);
btnB = (Button) findViewById(R.id.btnOptionB);
btnC = (Button) findViewById(R.id.btnOptionC);
btnD = (Button) findViewById(R.id.btnOptionD);
setWhatQuestionView();
switch (txtViewQuestion.getId()) {
case btnOptionA:
if (currentWhatQ.getAnswer().equals(btnA.getText())) {
score++;
}
if (qid < 10) {
currentWhatQ = whatQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
case btnOptionB:
if (currentWhatQ.getAnswer().equals(btnB.getText())) {
score++;
}
if (qid < 10) {
currentWhatQ = whatQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
case btnOptionC:
if (currentWhatQ.getAnswer().equals(btnC.getText())) {
score++;
}
if (qid < 10) {
currentWhatQ = whatQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
case R.id.btnOptionD:
if (currentWhatQ.getAnswer().equals(btnD.getText())) {
score++;
}
if (qid < 10) {
currentWhatQ = whatQuesList.get(qid);
setQuestionView();
} else {
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 Intent
startActivity(intent);
}
break;
}
}
}
public void setQuestionView() {
txtQuestion.setText(currentWhoQ.getQuestion());
btnA.setText(currentWhoQ.getMultipleChoiceA());
btnB.setText(currentWhoQ.getMultipleChoiceB());
btnC.setText(currentWhoQ.getMultipleChoiceC());
btnD.setText(currentWhoQ.getMultipleChoiceD());
qid++;
}
public void setWhatQuestionView() {
txtQuestion.setText(currentWhatQ.getQuestion());
btnA.setText(currentWhatQ.getMultipleChoiceA());
btnB.setText(currentWhatQ.getMultipleChoiceB());
btnC.setText(currentWhatQ.getMultipleChoiceC());
btnD.setText(currentWhatQ.getMultipleChoiceD());
qid++;
}
Not Sure, what type of Data your txtViewQuestion is...
The Switch Statement Works perfectly with primitive Data types...
If you try to call the Name of the Button Variable, this will Not Work because a program only works with memory adress, so Java will Not be able to give you the name of your object (if its a Button)
To solve this, you could Pass a Parameter to the Methods (for example int)
0 for the first button
1 for the second button
2 for the third...
And then you could "Switch" this Parameter
Bundle d = getIntent().getExtras();
int c = d.getInt("category");
String category = Integer.toString(c);
if ("Who".equals(category)) {
What is the value of c? How could it ever equal "Who" or "What"?
And like others have said, use the full ID of the buttons in the switch statements.
case R.id.btnOptionA:
instead of
case btnOptionA:
What is btnOptionA, btnOptionB and btnOptionC? txtViewQuestion.getId() return an Integer, in case tag you should use R.id.btnOptionA, R.id.btnOptionB, R.id.btnOptionC...
I'm trying to pass captured image and valuefrom C to B, finally to listView A. When the list in Activity A is clicked, it will display the passed image on imageView and values on editText B . But the problem now is the image displayed on Activity B is not from row I have clicked on listview A.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,int position, long id)
{
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM", "");
name = temp[1].trim();
Log.e("TAG", result + "");
if (name.equals("Project"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // image receive from C
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); //display image
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
Activity C
ImageView b;
ok.setOnClickListener(new View.OnClickListener()
{ // return image to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Add image into database
When ok button in Activity A is clicked, I want save all the image todatabase.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
byte[] data=getBitmapAsByteArray(getActivity(),Global.img);// this is a function
SB.insertStaffBenefit(data);
}
}
}
public static byte[] getBitmapAsByteArray(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
Toast.makeText(context, outputStream.size()/1024+"KB", Toast.LENGTH_LONG).show();
return outputStream.toByteArray();
}
1: ListView in A. Values were get fom C and B.
2: Activity B. Assume the list is clicked and intent to B. Noted that the value and image are from Activity C and B.
3: New value and images added and return to A
4: Two list in Activity A now
5: When first list clicked, image changed
You may add bitmap array list (in your Activity A):
ArrayList<Bitmap> m_listBitmapItems = new ArrayList<Bitmap>();
in onItemClick of your listV:
Global.img = m_listBitmapItems.get(position);
in onActivityResult():
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
}
else
{
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}
My app presents many images so I move from one image to the flowing one through a button (i10) and to go backward I used an other button (i8).
I think this method is a bit old fashion and I want to SWIPE between images, but I have really no clue, i read many about swiping but with no success.
here is my old fashion code:
num = 1;
imagename = getIntent().getExtras().getString("somekey");
resId = getApplicationContext().getResources().getIdentifier(
imagename + num, "drawable", getPackageName());
image1.setImageResource(resId);
num++;
i10.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
resId = getApplicationContext().getResources()
.getIdentifier(imagename + num, "drawable",
getPackageName());
} catch (NotFoundException e) {
e.printStackTrace();
}
if (resId > 0) {
image1.setImageResource(resId);
num++;
overridePendingTransition(R.anim.pushin, R.anim.pushout);
} else {
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
overridePendingTransition(R.anim.pushinhorizontal,
R.anim.pushouthorizontal);
}
}
});
i8.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
num = num - 2;
try {
resId = getApplicationContext().getResources()
.getIdentifier(imagename + num, "drawable",
getPackageName());
} catch (NotFoundException e) {
e.printStackTrace();
}
if (resId > 0) {
image1.setImageResource(resId);
num++;
overridePendingTransition(R.anim.pushin, R.anim.pushout);
} else {
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
overridePendingTransition(R.anim.pushinhorizontal,
R.anim.pushouthorizontal);
}
}
});
The best approach would be to use ViewPager
You can create a pager adapter and let the viewpager handles swipe operations.
Sample
I want to pass the values from one page to another page my code is:
public class main extends Activity implements OnClickListener {
private static final String TAG = "AskMeShowMe2";
private String choice = null;
private String fname = null;
private Menu myMenu = null;
final static int START =0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG,"Main - onCreate() ...");
setContentView(R.layout.activity_main);
View promptButton = findViewById(R.id.submit_button);
promptButton.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.greetingsRadioGroup);
int checkedRadioButton = radioGroup.getCheckedRadioButtonId();
switch (checkedRadioButton) {
case R.id.mrButton :
choice = "Mr.";
break;
case R.id.mrsButton :
choice = "Mrs.";
break;
case R.id.msButton:
choice = "Ms.";
break;
case R.id.drButton:
choice = "Dr.";
break;
}
switch(v.getId()){
case R.id.submit_button:
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
startActivity(j);
fname=String.valueOf(R.id.firstname);
Intent t = new Intent(this, Info.class);
j.putExtra("fname", fname);
startActivity(t);
break;
}
}
and it other Info.Class :
public class Info extends Activity {
private static final String TAG = "Info";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Intent myIntent = getIntent();
Bundle b = myIntent.getExtras();
String choice = b.getString("choice");
String fname = b.getString("fname");
Log.i(TAG,"selection: " + choice);
TextView textView = (TextView) findViewById(R.id.showmeText);
textView.append(": " + choice);
TextView textView1 = (TextView) findViewById(R.id.fname);
textView1.append(": " + fname);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return true;
}
}
when i run this program then my Info.class page doesn't show when i click the submit button,Can you please help me how to fix it?
Change Switch block to following:
switch(v.getId()){
case R.id.submit_button:
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
fname=String.valueOf(R.id.firstname);
j.putExtra("fname", fname);
startActivity(j);
break;
}
As you are starting Activity Info two times, Putting extras to only one intent, which is being started earlier.
use
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
fname=String.valueOf(R.id.firstname);
j.putExtra("fname", fname);
startActivity(j);
instead of
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
startActivity(j);
fname=String.valueOf(R.id.firstname);
Intent t = new Intent(this, Info.class);
j.putExtra("fname", fname);
startActivity(t);
becuase currently you are calling startActivity two times first for intent j and second time for intent t so remove one and put both choice and fname in single intent and call startActivity only once.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating random number in a range with Java
How can I generate random number in specific range in Android?
Here is my scenario
From the Mainactivity ; On click of a Button i want to generate a random number from 1 to 4
Based on the output, i want to write an if-else that will call 4 different activities
So on click, if 4 is generated, then call activity 4
Next time 1 can be generated and should call activity 1
and so on ....
Can someone please help me with this code?
myBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random r = new Random();
int index = r.nextInt(4)+1;
Intent intent;
if (index == 4) {
intent = new Intent(Activity.this, Activity4.class);
}
else if (index == 3) {
intent = new Intent(Activity.this, Activity3.class);
}
else if (index == 2) {
intent = new Intent(Activity.this, Activity2.class);
}
else
intent = new Intent(Activity.this, Activity1.class);
startActivity(intent);
}
});
public void test1(){
Random r = new Random();
int index = r.nextInt(4)+1;
Intent intent = null;
switch(index){
case 1: intent = new Intent(this, Activity1.class);
break;
case 2: intent = new Intent(this, Activity2.class);
break;
case 3: intent = new Intent(this, Activity3.class);
break;
case 4: intent = new Intent(this, Activity4.class);
break;
default:
Log.e("ERROR", "");
return;
}
if(intent != null){
this.startActivity(intent);
}
}