I am trying to have what the user types in the textEdits in the StartScreen Activity to show up in my MainActivity.
First I created my 2 intents for the 2 users.
String playerOneContent = playerOneEditText.getText().toString();
String playerTwoContent = playerTwoEditText.getText().toString();
Intent intent = new Intent(StartScreen.this, GameView.class);
intent.putExtra("NAME", playerOneContent);
intent.putExtra("NAME2", playerTwoContent);
startActivity(intent);
Then in my GameView I have the following code:
public class GameView extends View {
Paint paint = new Paint();
Context context;
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
paint.setColor(Color.YELLOW);
canvas.drawPaint(paint);
paint.setColor(Color.RED);
paint.setTextSize(20);
canvas.drawText("NAME",50, 50, paint);
}
}
How would I get the intents from the StartScreen and use it in the GameView?
This is the code I had in my Main Activity originally:
TextView playerOneTextView = (TextView)findViewById(R.id.playerOneTextView);
TextView playerTwoTextView = (TextView)
findViewById(R.id.playerTwoTextView);
playerOneTextView.setText(getIntent().getStringExtra("NAME"));
playerTwoTextView.setText(getIntent().getStringExtra("NAME2"));
Unfortunately, intents don't work in Android without extending the Activity class.
Therefore, what you can do is create an object of the MainActivity class in your GameView class and get the value of the variables.
So something like this in MainActivity.java:
public String playerOneContent;
public String playerTwoContent;
#Override
public void onCreate...... //blah blah blah
public void functionWhereYouSetValueofStrings(){
playerOneContent = playerOneEditText.getText().toString();
playerTwoContent = playerTwoEditText.getText().toString();
}
Now, in the GameView.java class do the following to get the values:
MainActivity ma = new MainActivity();
playerOneTextView.setText(ma.playerOneContent);
playerTwoTextView.setText(ma.playerTwoContent);
It's using the Object to refer to the public fields that you have in MainActivity.java. I believe that this should answer your question, and help you.
If not, then just make a comment with the problem below.
Related
I'm having some trouble with an issue in my Android Studio application that is to do with pressing the back button. Basically the user inputs into a text view and another method (not included as it works fine but I can post if requested) searches an API for the relevant data and displays it in a recycler view. Then the user makes a selection from the recycler view and the method below parses a JSON file and adds relevant data from it to an array in a separate class "Director". Once this happens the next activity "GraphActivity" starts and draws a number of nodes on a canvas for each director in the array.
The issue I am having is that when I make an input into the text view and then press the back button to close the soft keyboard on my Android device (it covers up the recycler view) and go through the steps I just mentioned, when the GraphActivity activity starts it does not work (no nodes are drawn). However, if I then press the back button to go back to the first activity and then make the same selection from the recycler view again, it works.
From what I can tell, the issue seems to be with the data being added to the "Director" array but I cannot figure out what is causing it, Logcat shows that the first time the GraphActivity activity starts the "Director" array is empty and therefore, no nodes are drawn but when I press back and then make the same selection again the array has the correct data and the nodes are drawn.
I would really appreciate some help with this as I am very new to Android Studio and have been searching around for hours to try and find a solution.
public class MainActivity extends AppCompatActivity implements MainAdapter.OnCompanyClickedListener {
private RecyclerView recyclerView;
private TextView userInput;
private Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rView);
RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
}
//Parse JSON File
public void searchCompanyDirectors(final String companyNumber){
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
HttpClient httpClient = new HttpClient();
try{
final String response = httpClient.run("myURL");
runOnUiThread(new Runnable(){
#Override
public void run(){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("items");
for (int i = 0; i < array.length();i++){
JSONObject o = array.getJSONObject(i);
String appointment = o.getString("links");
String parsedAppointment = parseApp(appointment);
Director director = new Director(o.getString("name"),parsedAppointment);
Director.directorList.add(director);
}
}catch (JSONException e){
e.printStackTrace();
}
}
});
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
thread.start();
}
#Override
public void onCompanyClicked(int position) {
Toast.makeText(this,Company.companyList.get(position).getTitle(),Toast.LENGTH_LONG).show();
chosenCompanyNumber = Company.companyList.get(position).getCompanyNumber();
chosenCompany = Company.companyList.get(position).getTitle();
searchCompanyDirectors(chosenCompanyNumber);
Intent intent = new Intent(this,GraphActivity.class);
startActivity(intent);
}
}
The GraphActivity class:
public class GraphActivity extends AppCompatActivity {
DrawGraph drawGraph;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawGraph = new DrawGraph(this);
setContentView(drawGraph);
The DrawGraph class:
public class DrawGraph extends View {
private Paint p1;
private Paint p2;
private Paint p3;
private Paint paint;
private Path path;
private Point point1;
private int radius = 300;
double x;
double y;
double angle;
int mWidth = this.getResources().getDisplayMetrics().widthPixels;
int mHeight = this.getResources().getDisplayMetrics().heightPixels;
List<Director> directorList = Director.getDirectorList();
private String chosenCompany = MainActivity.getChosenCompany();
private static List<Float> ordinates = new ArrayList<>();
public DrawGraph(Context context) {
super(context);
p1 = new Paint(Paint.ANTI_ALIAS_FLAG);
p1.setStrokeWidth(10);
p2 = new Paint(Paint.ANTI_ALIAS_FLAG);
p2.setStrokeWidth(10);
p3 = new Paint(Paint.ANTI_ALIAS_FLAG);
p3.setStrokeWidth(5);
path = new Path();
paint = new Paint();
point1 = new Point(mWidth/2, mHeight/2);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Colors
p1.setStyle(Paint.Style.FILL);
p1.setColor(Color.RED);
p2.setStyle(Paint.Style.FILL);
p2.setColor(Color.GREEN);
p3.setStyle(Paint.Style.STROKE);
p3.setColor(Color.CYAN);
paint.setColor(Color.BLACK);
paint.setTextSize(18f);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.CENTER);
Rect bounds = new Rect();
paint.getTextBounds(chosenCompany, 0, chosenCompany.length(),bounds);
//Draw company and directors
for (int i = 1; i <= directorList.size(); i++)
{
//Divide the company node
angle = i * (360/directorList.size());
x = point1.x + radius * cos(angle);
y = point1.y + radius * sin(angle);
//Draw directors
canvas.drawCircle((float)x,(float)y - (bounds.height() / 2), bounds.width() + 5,p2);
canvas.drawText(directorList.get(i-1).getName(),(float)x,(float)y,paint);
}
Okay, I've found an issue in DrawGraph class noted here;
List<Director> directorList = Director.getDirectorList();
private String chosenCompany = MainActivity.getChosenCompany();
You should not directly access the data objects of one activity from another. The previous activity could be destroyed etc as per Android OS and its lifecycle. You must think of it like out of sight, out of memory; which can cause the current activity to not be able to access the data in the previous one.
You'd need to properly send the parsed data from your JSON file, the variables List directorList and the String chosenCompany from your MainActivity to GraphActivity.
You can send data from one activity to another by adding it to the intent with which you call the next activity. The Intent class has features to help you send a small amount of information via itself; called putExtra() and getExtra(). More about them here.
You will need to add those variable datasets through intent.putExtra and fetch them back in your other activity onCreate by using getExtras.
Activity A >> Intent call to Activity B + Data >> Activity B
Hope this helps.
I tried a lot of things but I can't get it to work... I try to pass this String Variable (when i click Item in RecyclerView) to my MainActivity.
What works bad is calling the function (OnRecyclerViewItemClick) and changing the variable(GetUrlFromItem). My version of Android Studio is 2.3.3
I really need do this:
My RecyclerView:
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView titulo;
Button playbtn01;
List<Fuente> ListaObjeto;
public viewHolder(View itemView,List<Fuente> datos) {
super(itemView);
ListaObjeto = datos;
titulo = (TextView) itemView.findViewById(R.id.texto);
playbtn01 = (Button) itemView.findViewById(R.id.playbtn00);
playbtn01.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Fuente objeto = ListaObjeto.get(position);
if (view.getId() == playbtn01.getId()) {
MainActivity mainActivity = new MainActivity:
mainActivity.OnRecyclerViewItemClick(); /// initiate Void in Main
mainActivity.GetUrlFromItem = objeto.GetUrl; //Change Variable of Main
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
public String GetUrlFromItem;
public void OnRecyclerViewItemClick() {
if (GetUrlFromItem == "..."){
doSomething...
}
}
}
There are two big problems that I see.
The first is how you get a MainActivity instance to work with. In your question, you have this line of code:
MainActivity mainActivity = new MainActivity:
Calling new is going to do exactly what it sounds like: create a new instance of the MainActivity class. You do not want a new instance! You want your alive and running instance.
There are a handful of ways to get ahold of your alive and running MainActivity, but probably the simplest one for now is going to be casting your ViewHolder's itemView's Context. So instead of the above, write something like this:
MainActivity mainActivity = (MainActivity) itemView.getContext();
The second big problem is in the next two lines:
mainActivity.OnRecyclerViewItemClick();
mainActivity.GetUrlFromItem = objeto.GetUrl;
The problem here is the order of these two statements. Because you invoke mainActivity.OnRecyclerViewItemClick() before setting the value of mainActivity.GetUrlFromItem, the value will not be updated when OnRecyclerViewItemClick() is executed.
Simply swap the order of these two lines.
I set the background color of my app with this code:
RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(Color.RED);
How could I have this carry over to the next activities that come after this one, without using XML because it is not always the color RED. This depends on a selection by the user. But once the user has selected RED I want this color to carry over to the next activities. Is there a way to go about this without doing something like this for all the actives.
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("Color", "RED");
startActivity(intent);
And then on the next activity use that Extra to set the color. Is there a way that I can just set it for all the following activities until the user changes it?
Thanks for the help in advance.
i think you need to get #Code for that color and use
To send value
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("Color", "#Code");
startActivity(intent);
In next activity..
RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(Color.parseColor(intent.getExtra("Color")));
colors used in android are of int format not String
setBackgroundColor() takes a color in numeric form (e.g., 0xFFFF0000 for red)
So you can do this way:
Suppose from class A sending a int variable to class B
int bgColor=Color.RED; <---Change It with whatever you want(but should be numeric)
Intent bgIntent = new Intent(Background.this, MainScreen.class);
bgIntent.putExtra("background", bgColor);
startActivity(bgIntent);
and on class B
Intent bgIntent = getIntent();
bgGlobal = bgIntent.getExtras().getInt("background",-1);
if(bgGlobal != -1)
{
DetailsLayout.setBackgroundResource(Color.parseColor(bgGlobal));
}
else
{
DetailsLayout.setBackgroundResource(R.color.a1);
}
for more info please refer this
Put the setting of background color in a singleton class, say
public class ColorHolder {
public static ColorHolder instance=null;
private int color;
public static ColorHolder getInstance(){
if(instance==null){
instance=new ColorHolder();
}
}
public int getColor(){
return color;
}
public void setColor(int c){
color=c;
}
}
Then create a subclass of Activity, say
public class ColoredActivity extends Activity{
protected void onCreate(Bundle s){
super.onCreate(s);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(ColorHolder().getInstance().getColor());
}
}
Then all the Activities which want to apply this setting should extend this "ColoredActivity"
Please help!
I have a problem with creating a BitmapDrawable in a static context.
I am creating an android app for a student contest and since the MainActivity class starts
to look "dirty" (having lots of code in it) I decided to make MainActivityLayout class that extends the MainActivity. Basicly I moved some methods (the ones for setting layouts) from MainActivity to MainActivityLayout class. The problem is with resize() method where I use BitmapDrawable constructor wich is "bugging me slowly" because needs a reference to resources in order to resize properly the bitmap.
The MainActivity class :
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLayoutOne();
MainActivityLayouts.setLayoutOne();
getLayoutTwo();
MainActivityLayouts.setLayoutTwo();
}
private void getLayoutOne(){
//here I get the layouts id using findViewById() method
}
private void getLayoutTwo(){
//here I get the layout 2 id using findViewById() method
}
protected static Drawable resize(Drawable image,int xSize,int ySize) {
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, xSize, ySize, false);
return new BitmapDrawable(getResources(),bitmapResized);
}
}
The MainActivityLayout class:
public class MainActivityLayouts extends MainActivity{
public MainActivityLayouts(){
// ...
}
protected final static void setLayoutOne(){
Drawable drawableOne = ImageViewOne.getDrawable();
//here is the problem...cannot make a static refference...
//getResources() from resize method from MainActivity to be more specific
drawableOne = resize(drawableOne,100,100);
ImageViewOne.setImageDrawable(drawableOne);
}
protected final static void setLayoutTwo(){
Drawable drawableTwo = ImageViewTwo.getDrawable();
//here is the problem...cannot make a static refference...
//getResources() from resize method from MainActivity to be more specific
drawableTwo = resize(drawableTwo,200,200);
ImageViewTwo.setImageDrawable(drawableTwo);
}
Is there any solution to my problem? Resizing in another mode or can I avoid creating a BitmapDrawable and still obtain the same effect?
Any critic is highly appreciated :).
I'm a novice programmer and I'm trying to learn Android coding using Eclipse.
This is my first time using StackOverflow.
Just for tutorial purposes, I want to make a simple Animal Encyclopedia.
So in my Home class, there are some buttons: "Dog", "Cat", "Bird", etc. When I click the button, it will bring me to the same layout but of course with different content.
So I created a class named AnimalData that holds the
ArrayList<Integer> to store R.drawable.xxx and ArrayList<String>
to store the text that I will put below the picture (like "Bulldog"
or "Husky")
Then I created a class named ChangeContent to set all those drawable
and text to the XML
But whenever I click the button, it results in Stopped Unexpectedly Error
Below are the shortened Home class, The "crash-maker" isn't here. I have checked the whole code line per line using Thread.sleep(2000), so if my app crashes before 2 second, the error is before the sleep() code and vice versa.
public class Home extends Activity implements OnClickListener{
Button dog, cat, bird;
AnimalData ad;
ChangeContent cc;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
//set the findViewById for all the buttons
//set onClickListener() to all the buttons
}
public void onClick(View v) {
switch (v.getId()){
case R.id.bDog:
drawable.add(R.drawable.xxx);
drawable.add(R.drawable.yyy);
title.add("Bulldog");
title.add("Husky");
break;
case R.id.Cat:
//same
break;
case R.id.bBird:
//same
break;
}
ad.setDrawable(drawable);
ad.setTitle(title);
Intent i = new Intent("animal.ChangeContent"); //from Manifest
startActivity(i);
}
}
The AnimalData is just a typical getter setter, so I will just skip the code for that
The error is right after ChangeContent started because even when I put the sleep() on the first line of constructor, it doesn't have any effect.
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
Sorry for the long question, I tried to make it as short as possible
Can you guys help me figure the error out?
Thanks before
You are trying to get arraylist from intent, whereas you are not putting putStringArrayList and putIntegerArrayList methods.
putIntegerArrayListExtra(String name, ArrayList<Integer> value)
putStringArrayListExtra(String name, ArrayList<String> value)
so Change calling activity to following:
Intent i = new Intent(Home.this, ChangeContent.class); //from Manifest
i.putIntegerArrayListExtra("drawables", drawable);
i.putStringArrayListExtra("titles", titles);
startActivity(i);
and get data from intent in onCreate method by following methods:
getIntegerArrayListExtra, and getStringArrayListExtra
you also can do following by making contentChanged method to static, by this you wont need to do much changes in your application code, just do following:
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private static ArrayList<Integer> drawable;
private static ArrayList<String> title;
public static ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
See the answer by RajaReddy P here:
https://stackoverflow.com/a/9937854
In the send class use:
Intent intent = new Intent(PhotoActivity.this,PhotoActivity1.class );
intent.putIntegerArrayListExtra("VALUES", image);
startActivity(cameraIntent);
.. and in the receiver class use:
Intent i = getIntent();
ArrayList<Integer> img = i.getIntegerArrayListExtra("VALUES");
Your approach is wrong -
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
ChangeContent is a Activity class so, you don't pass parameter like this.
Passsing class should be serializable and use it -
startActivity(new Intent(this, ChangeContent.class)
.putExtra("key", ad);
And in your ChangeContent class extract the class from Intent
So, change your code design and go ahead.
Best of luck.