Thanks for checking out my question!
I have a relativly ismple loop which will add a onClickListener to each ImageView I add to my Layout, however when trying to add a new Intent to it, it gives me one of the following errors:
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
Will result in the "Cannot resolve Constructor 'Intent ...." error.
So when I was looking for a solution, people suggested to change "this" to "MainActivity.this", but...
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(MainActivity.this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
resulted into: com.myName.appName.MainActivity is not an enclosing class
Here is the ImageActivity class:
public class ImageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
String URL = getIntent().getExtras().getString("URL");
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.getLayoutParams().height = (int) (imageView.getLayoutParams().width * (Float.valueOf(String.valueOf(1.41))));
Picasso.with(this).load(URL).into(imageView);
}
The weird thing is that I have done numerous new Intent's during my play time with creating apps, but I cant seem to solve this one. What am I missing here?
FULL CODE FROM HERE
public class DetailsActivity extends AppCompatActivity {
TextView TVWeChatIdValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
String dataString = getIntent().getExtras().getString("dataString");
String[] itemData = dataString.split(",");
String category = itemData[0];
Log.e("DetailsActivity", category);
String itemID = itemData[1];
Log.e("DetailsActivity", itemID);
String imageURLsString = itemData[2];
Log.e("DetailsActivity", imageURLsString);
String description = itemData[3];
Log.e("DetailsActivity", description);
String price = itemData[4];
Log.e("DetailsActivity", price);
String itemCode = category + itemID;
TextView textView;
textView = (TextView) findViewById(R.id.Title);
textView.setText(getResources().getString(R.string.app_name));
textView = (TextView) findViewById(R.id.ItemReferralValue);
textView.setText(itemCode);
textView = (TextView) findViewById(R.id.ItemPriceValue);
textView.setText(price);
TVWeChatIdValue = (TextView) findViewById(R.id.WeChatIDValue);
new DatabaseTask(this, "details", "GETWECHATID").execute();
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ItemDetailsContent);
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
ImageView imageView = (ImageView) findViewById(R.id.ItemDetailsDescription);
String imageURL = ".../images/" + description;
Picasso.with(this).load(imageURL).into(imageView);
}
public void SetWeChatId(String mValue) {
TVWeChatIdValue.setText(mValue);
}
public int getPx(int dimensionDp) {
float density = getResources().getDisplayMetrics().density;
return (int) (dimensionDp * density + 0.5f);
}
}
WORKING CODE
public class MainActivity extends AppCompatActivity {
TextView TVWeChatIdValue;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView;
textView = (TextView) findViewById(R.id.Title);
textView.setText(getResources().getString(R.string.app_name));
textView = (TextView) findViewById(R.id.SubTitle);
textView.setText(getResources().getString(R.string.slogan));
textView = (TextView) findViewById(R.id.MoreForWomen);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("women");
}
});
textView = (TextView) findViewById(R.id.MoreForMen);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("men");
}
});
textView = (TextView) findViewById(R.id.MoreForKids);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("kids");
}
});
}
public void GetData() {
TVWeChatIdValue = (TextView) findViewById(R.id.WeChatIDValue);
new DatabaseTask(this, "main", "GETWECHATID").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForWomenContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "WOMEN", "GETNEWESTITEMS").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForMenContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "MEN", "GETNEWESTITEMS").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForKidsContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "KIDS", "GETNEWESTITEMS").execute();
}
public void SetWeChatId(String mValue) {
TVWeChatIdValue.setText(mValue);
}
public void ProcessNewItems(LinearLayout mLinearLayout, final String mCategory, final HashMap<Integer, Item> mItems){
for (int i = 0; i < mItems.size(); i++) {
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(96),getPx(128)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
String imageURL = ".../images/" + mItems.get(i).getImageURLs()[0];
Picasso.with(this).load(imageURL).into(image);
mLinearLayout.addView(image);
final int index = i;
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowItemDetails(mCategory, mItems.get(index));
}
});
}
}
void ShowItemDetails(String mCategory, Item mItem){
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra("dataString", mItem.GetDataString());
Log.e("CatalogActivity", mItem.GetDataString());
startActivity(intent);
}
void OpenCatalog(String mCategory){
//show catalog
Intent intent = new Intent(this, CatalogActivity.class);
intent.putExtra("category", mCategory);
startActivity(intent);
}
public int getPx(int dimensionDp) {
float density = getResources().getDisplayMetrics().density;
return (int) (dimensionDp * density + 0.5f);
}
#Override
public void onResume() {
super.onResume();
GetData();
}
}
You need to use the name of the Activity subclass which contains the code that creates the OnClickListener. In many examples, this is MainActivity. However, this doesn't seem to be the case in your code. Since you are in a class named DetailsActivity then use that name:
Intent intent = new Intent(DetailsActivity.this, ImageActivity.class);
From what I can see of your code here, I strongly suggest that you learn about ListView and RecyclerView. They are a bit complex, but once you understand them, they do much of the work for you similar to what you are trying to do here. For one thing, they are more efficient than your own code because they only create as many views as are visible.
Let's look more closely at your other example:
public class MainActivity extends AppCompatActivity {
// ...
void ShowItemDetails(String mCategory, Item mItem){
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra("dataString", mItem.GetDataString());
startActivity(intent);
}
}
Notice that the ShowItemDetails() is inside the MainActivity class. So this refers to an instance of that class which can be used wherever a Context is needed. (For more details about this you need to read about inheritance and polymorphism.)
On the other hand, your original code creates an Intent in a method which is inside an anonymous subclass of OnClickListener which cannot be used as a Context. However the anonymous inner class is in a method inside DetailsActivity which inherits from Context. In order to access an instance of this outer class, you have to use DetailsActivity.this.
For more details you should learn about the special this reference and inner classes.
You have this block
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(MainActivity.this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
Change MainActivity.this to whatever Activity subclass that is setting the OnClickListener. That would be DetailsActivity.this in your case. Basically the enclosing activity just means the name of the class file (which is also the name of the Activity class) in which the Activity is being defined, this Activity encapsulates the call to .setOnClickListener() to which you are passing an anonymous inner class, which is being enclosed inside your DetailsActivity, hence the name enclosing activity. Hope that makes sense
Related
I have no idea how to make my added view permanent with its own class saved for futeer access.
Right now when I run the code there will be an empty view since there are no values coming from the intents, once I click on the button and fill out the information, the empty box gets replaced with a view that has the title I had giving, but when I click to add again it just replaces the old one, how to ensure that it doesn't replace but gets added on?
//main_activiy
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sports_screen);
// Creating the list that is on screen
FloatingActionButton addClass = findViewById(R.id.Add_class_button);
//sending out variable
Intent intent = new Intent (this, Creating_Class_main.class);
Activity ma = this;
//names
Intent MB = getIntent();
String Classinp = MB.getStringExtra("strC");
String tchinp = MB.getStringExtra("strT");
//adding team
team sportsteam = new team(ma, Classinp,tchinp);
sportsteam.addtext();
// Input
addClass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
}
}
//Second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_class);
EditText ClassName = findViewById(R.id.CLinput);
EditText teacher = findViewById(R.id.tchinput);
Button end = findViewById(R.id.end);
Intent intent = new Intent (this, MainActivity.class);
end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent.putExtra("strC", ClassName.getText().toString());
intent.putExtra("strT", teacher.getText().toString());
startActivity(intent);
}
});
}
}
//my class
public class team {
// Defining Activity class to use
private Activity activity;
// Defining text box
LinearLayout lay;
View Tbox;
// Members Defining
String teamname;
String teacher;
ArrayList<Players> members = new ArrayList<Players>();
public team(Activity activity, String teamname, String teacher) {
// To be able to use activity
this.activity = activity;
// Normal things to define
this.teamname = teamname;
this.teacher = teacher;
// initialize the lay and Tbox variables
lay = activity.findViewById(R.id.Scontainer);
Tbox = activity.getLayoutInflater().inflate(R.layout.text_box_output, null);
}
public void addtext() {
// add text to the layout and view
TextView title = Tbox.findViewById(R.id.daTeam);
title.setText(teamname);
lay.addView(Tbox);
}
}
I am new to Android development. I have an app in which the user creates multiple names (as if they were players of a game). These "players" appear as a matrix is used in the same activity. (Being possible here to exclude any player).
I want to display all of these players (MainActivity) in another activity (Main2Activity), showing only the first player added and, clicking a button, switch to the second player.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
TextView textAdd;
EditText etAdd;
ArrayList<Model> models = new ArrayList<Model>();
MyAdapter myAdapter;
int position;
Button prox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prox = findViewById(R.id.prox);
prox.setOnClickListener(new View.OnClickListener() {
//next screen
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String nome = etAdd.getText().toString();
intent.putExtra("value", nome);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerView);
textAdd = findViewById(R.id.text_adicionar);
etAdd = findViewById(R.id.et_Adicionar);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
myAdapter = new MyAdapter(getApplicationContext(),
models, new MyAdapter.Onclick() {
#Override
public void onEvent(Model model, int pos) {
position = pos;
etAdd.setText(model.getId());
}
});
recyclerView.setAdapter(myAdapter);
textAdd.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.text_adicionar: {
insertItem(String.valueOf(etAdd.getText()));
}
break;
}
}
private void insertItem(String name) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
Model model = gson.fromJson(String.valueOf(jsonObject), Model.class);
models.add(model);
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.play: {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
break;
}
}
}
I'm not sure if I fully understand your question, but are you just looking for a way to pass data from one Activity to another?
If so, use .putExtra() with your Intent for starting the next Activity.
In the onCreate method for your second Activity, use .getExtras() to retrieve the data.
In 1st Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("DataName", data);
startActivity(intent);
In the 2nd Activity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String[] dataArray = getIntent().getExtras().get("DataName"));
}
EDIT:
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
I've got 2 activities (well actually 4 but only 2 matter for now), the main activity and the font changing activity. The main activity sends text that the user has typed in to the font changing activity using an intent and startActivityForResult. Within the font changing activity the user can change the font of the text, as expected. What I'm trying to do is after the user has changed the font, send the text and the new font back to the main activity. But I'm not sure how to do this. I'm thinking of using some kind of bundle but I am stuck. If anyone could help me that would be greatly appreciated.
Here's my (relevant) Main Activity code:
public class MainActivity extends AppCompatActivity
{
RelativeLayout move_group;
ImageView view;
String backgroundImageName;
SeekBar seekSize;
TextView user_text;
Button button;
SeekBar tiltChange;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_text = (TextView) findViewById(R.id.user_text);
static final int REQUEST_FONT = 4;
public void FontChange(View view)
{
Intent fontIntent = new Intent(this, Main4Activity.class);
fontIntent.putExtra("Text", temp);
startActivityForResult(fontIntent, REQUEST_FONT);
}
//There's supposed to be an accompanying onActivityResult method as well
//but i haven't figured that part out yet
}
Here's my (relevant) Font Activity code:
public class Main4Activity extends AppCompatActivity
{
TextView user_font_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
user_font_text = (TextView) findViewById(R.id.user_font_text);
}
public void boldText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_bold);
user_font_text.setTypeface(custom_font);
}
public void italicText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_italic);
user_font_text.setTypeface(custom_font);
}
public void regularText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_regular);
user_font_text.setTypeface(custom_font);
}
public void thinText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_thin);
user_font_text.setTypeface(custom_font);
}
public void OK(View view)
{
//The intent and/or bundle would go here but I don't know what to do
}
}
public void FontChange(View view)
{
temp = user_text.getText().toString();
Intent fontIntent = new Intent(this, Main4Activity.class);
fontIntent.putExtra("Text", temp);
startActivityForResult(fontIntent, REQUEST_FONT);
}
this will fetch your string from textview to fontActivity.
Now in your FontActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
Intent intent = getIntent();
String text = intent.getStringExtra("temp");
user_font_text = (TextView) findViewById(R.id.user_font_text);
user_font_text.setText(text);
}
public void OK(View view)
{
Intent returnIntent = new Intent();
returnIntent.putExtra("result",
user_font_text.getText().toString());
returnIntent.putExtra("font",
ypur_font_type);
setResult(Activity.RESULT_OK, returnIntent);
}
Remaining part of setting font style can be done using SpannableStringBuilder. here you can check SpannableStringBuilder . Hope this helps.
so a quick question. In my app, the users go through multiple activities that provides them with radio-buttons to choose from.. at the final activity, based on there options, the will be shown which character they are etc... Now the problem is I don't know how to write a code in order to do that. Here is what I have
First activity
public class Quiz1 extends Activity {
Button btn;
RadioGroup rg1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz1);
btn = (Button) findViewById(R.id.nextBtn1);
rg1= (RadioGroup) findViewById(R.id.rg1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (rg1.getCheckedRadioButtonId() == -1) {
Toast.makeText(getApplicationContext(), "Please select an answer",
Toast.LENGTH_SHORT).show();
} else{
Intent intent = new Intent(getApplicationContext(), Quiz2.class);
Bundle bundle = getIntent().getExtras();
int id = rg1.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(id);
bundle.putString("rg1", radioButton.getText().toString());
intent.putExtras(bundle);
startActivity(intent);
}
}
});
}
}
Second activity
Button btn;
RadioGroup rg2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz2);
btn = (Button) findViewById(R.id.nextBtn2);
rg2= (RadioGroup) findViewById(R.id.rg2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (rg2.getCheckedRadioButtonId() == -1) {
Toast.makeText(getApplicationContext(), "Please select an answer",
Toast.LENGTH_SHORT).show();
} else{
Intent intent = new Intent(getApplicationContext(), Quiz3.class);
Bundle bundle = getIntent().getExtras();
int id = rg2.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(id);
bundle.putString("rg2", radioButton.getText().toString());
intent.putExtras(bundle);
startActivity(intent);
}
}
});
}
}
This continues for about 7 activities
Final activity (where the result and the character are shown)
public class Final1 extends Activity {
Button btnRestart;
Button btnShare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final1);
Bundle bundle = getIntent().getExtras();
TextView textView = (TextView)findViewById(R.id.txt);
textView.setText(bundle.getCharSequence("rg"));
TextView textView1 = (TextView)findViewById(R.id.txt1);
textView1.setText(bundle.getCharSequence("rg1"));
TextView textView2 = (TextView)findViewById(R.id.txt2);
textView2.setText(bundle.getCharSequence("rg2"));
TextView textView3 = (TextView)findViewById(R.id.txt3);
textView3.setText(bundle.getCharSequence("rg3"));
TextView textView4 = (TextView)findViewById(R.id.txt4);
textView4.setText(bundle.getCharSequence("rg4"));
TextView textView5 = (TextView)findViewById(R.id.txt5);
textView5.setText(bundle.getCharSequence("rg5"));
TextView textView6 = (TextView)findViewById(R.id.txt6);
textView6.setText(bundle.getCharSequence("rg6"));
btnRestart = (Button)findViewById(R.id.restartBtn);
btnRestart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(v.getContext(), Quiz.class);
startActivityForResult(in, 0);
}
});
btnShare = (Button)findViewById(R.id.btnShare);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "check out this app";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
}
}
Now, in the final activity, I want to have a code where if for example:
if in activity1(Quiz1) options 1 OR 2 are chosen ( as in the radio-buttons selected),
Quiz2: options 2 or 4
Quiz3: options 1 or 4
Quiz2: options 2 or 3
and so on...
then change a textview to something specific like "your character is x"
I have already carried all the information to the final class, I just don't know how to approach this problem, even-though it sounds simple.
Any help would be appreciated, thank you <3
EDIT:
TextView textviewResult = (TextView) findViewById(R.id.textViewResult);
if(bundle.getString("rg").equals("A")||(bundle.getString("rg").equals("B")&& bundle.getString("rg1").equals("B")&& bundle.getString("rg2").equals("Long range weapons")
&& bundle.getString("rg3").equals("C") || bundle.getString("rg3").equals("D") && bundle.getString("rg4").equals("A")||bundle.getString("rg4").equals("B")
|| bundle.getString("rg4").equals("CC") && bundle.getString("rg5").equals("A") || bundle.getString("rg5").equals("E")
&& bundle.getString("rg6").equals("Yes"))) {
textviewResult.setText("x");
}else{
textviewResult.setText("not x");
}
The problem with this is, even if I choose another option for rg (so not the "A" or "B" options), but then for the rest I choose the ones in the If statement, it still ends up saying x(but it should be saying Not x)
You can use the String equals() method inside your if statement. It returns true if both Strings are equal.
E.g.:
if(bundle.getString("rg").equals("YourRadioButtonText")){
...
}
Your code could look something like this:
`public class Final1 extends Activity {
Button btnRestart;
Button btnShare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final1);
Bundle bundle = getIntent().getExtras();
TextView textView = (TextView)findViewById(R.id.txt);
textView.setText(bundle.getCharSequence("rg"));
TextView textView1 = (TextView)findViewById(R.id.txt1);
textView1.setText(bundle.getCharSequence("rg1"));
TextView textView2 = (TextView)findViewById(R.id.txt2);
textView2.setText(bundle.getCharSequence("rg2"));
TextView textView3 = (TextView)findViewById(R.id.txt3);
textView3.setText(bundle.getCharSequence("rg3"));
TextView textView4 = (TextView)findViewById(R.id.txt4);
textView4.setText(bundle.getCharSequence("rg4"));
TextView textView5 = (TextView)findViewById(R.id.txt5);
textView5.setText(bundle.getCharSequence("rg5"));
TextView textView6 = (TextView)findViewById(R.id.txt6);
textView6.setText(bundle.getCharSequence("rg6"));
// NEW
TextView textviewResult = (TextView) findViewById(R.id.resultTV);
if(bundle.getString("rg").equals("C")){
textviewResult.setText("It is C");
}
else if(bundle.getString("rg1").equals("A") || bundle.getString("rg2").equals("B")){
textviewResult.setText("It is A or B");
}
else if(bundle.getString("rg1").equals("C") && bundle.getString("rg2").equals("D")){
textviewResult.setText("It is C and D");
}
else if(!bundle.getString("rg1").equals("A")){
textviewResult.setText("It is not A");
}
else {
textviewResult.setText("Mhhh");
}
// END
btnRestart = (Button)findViewById(R.id.restartBtn);
btnRestart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(v.getContext(), Quiz.class);
startActivityForResult(in, 0);
}
});
btnShare = (Button)findViewById(R.id.btnShare);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "check out this app";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
}
}`
I can't believe I have so much trouble with this. I have this variable in my game activity:
public static int numberOfPointsA;
and in another activity
public static int numberOfPointsB;
Now I need these values to pass to another activity, where I should total these values and set result to textView. Since these are public static variables I tried:
public static int totalScore = ClassA.numberOfPointsA + ClassB.numberOfPointsB;
textView.setText("" + totalScore);
But that's not working. So I tried with intent:
In game classA:
Intent intent = new Intent(this, Menu.class);
intent.putExtra("foobar", numberOfPointsA);
startActivity(intent);
and in menu class:
Intent intent = getIntent();
int numberOfPointsA = intent.getIntExtra("foobar", 0);
But that's not working either. If I place in the scope of activity, as soon as activity starts it crashes. If I place it in onCreate method, I can's use my int variable anymore, I don't need it in onCreate method, I need it elsewhere.
So how to set my variable in game class, pass to menu class, save it there and then make it wait until I finish my game class B and do the same with that variable, and then total those two variables and set it successfuly to the textView?
Menu activity:
public class Izbor extends Activity implements OnClickListener{
private int asocijacijeUkupno = 0;
private int thUkupno = 0;
int ukupanBrojPoena = asocijacijeUkupno + thUkupno;
Button toploHladno, asocijacije, cigle, spojnice, nazad, poeniTH, poeniAso, poeniCigle, poeniSpojnice, poeniUkupno;
TextView naslov;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asocijacijeUkupno = getIntent().getIntExtra("RUNNING_TOTAL", 0);
thUkupno = getIntent().getIntExtra("RUNNING_TOTAL2", 0);
setContentView(R.layout.izbor);
addListenerOnButton();
}
private void addListenerOnButton() {
naslov = (TextView) findViewById(R.id.tvIzborNaslov);
toploHladno = (Button) findViewById(R.id.bIzbor1);
asocijacije = (Button) findViewById(R.id.bIzbor2);
cigle = (Button) findViewById(R.id.bIzbor3);
spojnice = (Button) findViewById(R.id.bIzbor4);
nazad = (Button) findViewById(R.id.bIzborNazad);
poeniTH = (Button) findViewById(R.id.bPoeniTH);
poeniAso = (Button) findViewById(R.id.bPoeniAso);
poeniCigle = (Button) findViewById(R.id.bPoeniCigle);
poeniSpojnice = (Button) findViewById(R.id.bPoeniSpojnice);
poeniUkupno = (Button) findViewById(R.id.bPoeniUkupno);
toploHladno.setOnClickListener(this);
asocijacije.setOnClickListener(this);
cigle.setOnClickListener(this);
spojnice.setOnClickListener(this);
nazad.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if(asocijacijeUkupno != 0){
poeniAso.setText("" + asocijacijeUkupno);
}else{
poeniAso.setText("");
}
if(thUkupno != 0){
poeniTH.setText("" + thUkupno);
}else{
poeniTH.setText("");
}
if(ukupanBrojPoena != 0){
poeniUkupno.setText("" + ukupanBrojPoena);
}else{
poeniUkupno.setText("");
}
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bIzbor1:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.TOPLOHLADNO"));
break;
case R.id.bIzbor2:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.ASOCIJACIJE"));
break;
case R.id.bIzbor3:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzbor4:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzborNazad:
if(music == true){
buttonBack.start();
}
finish();
break;
}
}
}
The following is a very basic example, using two activities to pass an int around.
First Activity, which you start from:
public class FirstActivity extends Activity {
private int mTotal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... onCreate code, layout stuff etc....
}
// this is tied to a View onClick call
public void moveToSecondAct(View view) {
Intent intent = new Intent();
intent.putExtra("RUNNING_TOTAL",mTotal);
intent.setClass(this, SecondActivity.class);
//... any other options like ...
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// start the second Activity
startActivity(intent);
}
}
And the second Activity example is something like:
public class SecondActivity extends Activity {
private int mTotal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTotal = getIntent().getIntExtra("RUNNING_TOTAL", 0);
//.... onCreate code, layout stuff etc....
Log.i("Running total is:"+ mTotal);
// update the total on the TextView
TextView tv = (TextView) findViewById(R.id.poeniUkupno);
tv.setText("Total: "+ mTotal);
}
}
Edit: Some changes to try help make things clearer
I didn't completely get what you have been trying to say but what I got was you want to create a variable in FirstActivity send its value to SecondActivity and then pass their sum to ResultActivity if its so then here you go
//First Activity
public class FirstActivity extends Activity{
int firstValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firstValue = 10;
}
public sendValueToSecondActivity(View view){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("firstValue", firstValue);
startActivity(intent);
}
}
//Second Activity
public class SecondActivity extends Activity{
int sumOfFirstAndSecond;
int secondValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
secondValue = 20;
}
public sendValueToSecondActivity(View view){
sumOfFirstAndSecond = getIntent().getIntExtra("firstValue") + secondValue;
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra("sumOfFirstAndSecond", sumOfFirstAndSecond);
startActivity(intent);
}
}
//Result Activity
public class ResultActivity extends Activity{
TextView textView;
int result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
secondValue = 20;
textView = (TextView) findViewById(R.id.textView);
}
public setResultToTextView(View view){
result = getIntent().getIntExtra("sumOfFirstAndSecond");
textView.setText(""+result);
}
}