The following class is intended to display a set of strings contained in an xml file. Within the onCreate method, an array of strings is pulled from a resource file. These strings are a set of corny jokes that are added to an ArrayList of Joke objects (m_arrJokeList), constructed from the strings.
The addJoke method, called within the onCreate method, is intended to display these jokes in a scroll view as text. However, none of this seems to work on either my device or emulator, so something is definitely wrong with the code. I'd like to know how I can fix this as well on some tips on how to work with these views.
Here is the code, not fully implemented.
package edu.calpoly.android.lab2;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class SimpleJokeList extends Activity {
// Contains the list Jokes the Activity will present to the user
protected ArrayList<Joke> m_arrJokeList;
// LinearLayout used for maintaining a list of Views that each display Jokes
protected LinearLayout m_vwJokeLayout;
// EditText used for entering text for a new Joke to be added to m_arrJokeList.
protected EditText m_vwJokeEditText;
// Button used for creating and adding a new Joke to m_arrJokeList using the
// text entered in m_vwJokeEditText.
protected Button m_vwJokeButton;
// Background Color values used for alternating between light and dark rows
// of Jokes.
protected int m_nDarkColor;
protected int m_nLightColor;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
initLayout();
Resources localRsrc;
localRsrc = this.getResources();
ArrayList<Joke> jokeList = new ArrayList<Joke>();
String[] jokeStrings = localRsrc.getStringArray(R.array.jokeList);
int size = jokeStrings.length;
Joke tempJoke = new Joke();
for(int i=0;i < size;i++)
{
tempJoke.setJoke(jokeStrings[i]);
jokeList.add(tempJoke);
addJoke(tempJoke);
}
}
// Method used to encapsulate the code that initializes and sets the Layout
// for this Activity.
protected void initLayout() {
// TODO
//LinearLayout rootLayout;
m_arrJokeList = new ArrayList<Joke>();
m_vwJokeLayout = new LinearLayout(this); // why pass "this"
m_vwJokeLayout.setOrientation(LinearLayout.VERTICAL);
ScrollView extendedView = new ScrollView(this.getApplicationContext());
extendedView.addView(m_vwJokeLayout);
setContentView(extendedView);
}
// Method used to encapsulate the code that initializes and sets the Event
// Listeners which will respond to requests to "Add" a new Joke to the list.
protected void initAddJokeListeners() {
// TODO
}
// Method used for encapsulating the logic necessary to properly initialize
// a new joke, add it to m_arrJokeList, and display it on screen.
// #param strJoke
// A string containing the text of the Joke to add.
protected void addJoke(Joke jk) {
m_arrJokeList.add(jk);
TextView textJoke = new TextView(this);
textJoke.setText(jk.getJoke());
m_vwJokeLayout.addView(textJoke);
}
}
put
Joke tempJoke = new Joke();
in for loop
for(int i=0;i < size;i++)
{
Joke tempJoke = new Joke();
tempJoke.setJoke(jokeStrings[i]);
jokeList.add(tempJoke);
addJoke(tempJoke);
}
then try it. and let me know what happen.
Related
I wanted to create a simple app that shows words/sentences randomly from a list that I've created every time the user click on the button.
Android Studio doesn't show any error but nothing happens when I click on the button.
Appreciate your help. Thank you
Here's my code.
MainActivity.java
package com.example.arraytesting4;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.lang.String;
import java.lang.StringBuilder;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> SList;
TextView Sentence;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Sentence = (TextView) findViewById(R.id.Sentence);
}
public void buttonClicked(View v){
printJoke();
}
public void printJoke() {
StringBuilder SentenceStringBuilder = new StringBuilder();
for (String s : SList) {
SentenceStringBuilder.append(s + "\n");
}
Sentence.setText(SentenceStringBuilder.toString());
}
}
In SList.java
package com.example.arraytesting4;
import java.util.*;
import java.util.ArrayList;
public class SList extends MainActivity {
public void Sentence(){
ArrayList<String> SList = new ArrayList<String>();
SList.add("Apple");
SList.add("Banana");
SList.add("Ciku");
SList.add("Danny ate the others.");
}
}
Your hierarchy here doesn't have any sense. I don't know what you tried or thought but this is incorrect.
If you extends your MainActivity then your Slist is also an Activity, is your project even running?
There are different problems here :
You don't use Sentence() method anywhere
You are extending MainActivity to create a method of an ArrayList
An easy way should be create a method to initialise that ArrayList inside your MainActivity and then it should work.
Create a method to initialise the List and call this method inside onCreate()
private void initialiseArray(){
SList = new ArrayList<>();
SList.add("Apple");
SList.add("Banana");
SList.add("Ciku");
SList.add("Danny ate the others.");
}
Also remember to remove the Slist class.
Note: I don't know if you just want to show one sentence on the TextView or all the items in the ArrayList, in this case how you did it would show all the items.
you just need to write following code in your onCreate after importing button,
clickMe.onClickListener((View v) -> {
Sentence.setText(getRandomFromList(getSampleList()));
});
Now add below two methods to create List & get a random from List,
private ArrayList<String> getSampleList(){
ArrayList<String> list = new ArrayList();
list.add("Apple");
list.add("Banana");
list.add("Water Melon");
list.add("Fruit X");
list.add("Fruit Y");
return list;
}
private String getRandomFromList(ArrayList<String> list){
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
You haven't declare your button yet.
do something like this
Button *your button* = (Button) findViewById(R.id.*your button id*);
then, instead of creating buttonClicked function,
create button on click listener in your onCreate function.
something like this
*your button*.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
printJoke()
}
});
You have to add listener to your button.
So your buttons can know what they will do when someone click on them.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Sentence = (TextView) findViewById(R.id.Sentence);
Button myButton = (Button) findViewById(r.id.myButtonId);
myButton.setOnClickListener((View v) -> {
buttonClicked(); //or you can delete buttonClicked Method and call printJoke Method here
});
}
I have got a little problem which is for me impossible to solve. I've got lots of TableRows called Radek_X and they are set to be android:visibility="gone".
And I need that if you for the first time, click on button(there is only one button for that process) it will change Radek_1 to android:visibility="visible" if you click on the button for the second time it will change Radek_2 from gone to visible, while Radek_1 is still visible. And so on for all others TableRows. I'm really desperate. I will be very grateful for any help! Have a nice day!
Here is my java file
package jansoldat.formular100;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TableRow;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button buttonPridejStaniceni;
TableRow Radek_2, Radek_3, Radek_4,Radek_5,Radek_6;
#Override
private ArrayList<String> arrayList;
private ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPridejStaniceni = (Button) findViewById(R.id.buttonPridejStaniceni);
Radek_2 = (TableRow) findViewById(R.id.Radek_2);
Radek_3 = (TableRow) findViewById(R.id.Radek_3);
Radek_4 = (TableRow) findViewById(R.id.Radek_4);
Radek_5 = (TableRow) findViewById(R.id.Radek_5);
Radek_6 = (TableRow) findViewById(R.id.Radek_6);
}
public void PridejDalsiStaniceniClicked(View v)
{
Radek_2.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_4.setVisibility(View.VISIBLE);
Radek_5.setVisibility(View.VISIBLE);
Radek_6.setVisibility(View.VISIBLE);
}
}
`
It's actually easier than you think, change your onClick method, which I assume you're setting by xml to PridejDalsiStaniceniClicked to this:
int[] views = new int[]{R.id.Radek_2,R.id.Radek_3,R.id.Radek_4};//...
int counter = 0;
public void PridejDalsiStaniceniClicked(View v)
{
findViewById(views[counter]).setVisibility(View.VISIBLE);
if(counter<views.length){
counter++;
}
}
What happens inside is that we will fetch the view that matches the counter of times pressed while there are still views in the array. Some people don't realize that view ids are integers and can be stored in an array like in the example.
I'm new to android and have have an assignment to create an email application. So I have 2 layouts and 2 activities, one for reading the email and one for writing the email. I'm trying to retain the information sent in the fields in the email writing activity for when the email is being read. The problem is at the **bolded line below - "The method setText string is undefined for the type view", and I need to get all the text view to contain the information send from the other activity. I can post the other files if its needed, all help appreciated. I have tried other ways to assign the variable to text view but can't seem to get it to work.
DisplayMessageActivity.java
package com.example.project;
import com.example.project.R.layout;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Show the Up button in the action bar.
setupActionBar();
// Get the messages from the intent
Intent intent = getIntent();
String messageto2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String messagefrom2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE2);
String messagecc2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE3);
String messagebcc2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE4);
String messagesubject2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE5);
String messagebody2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE6);
**TextView msgto = (TextView)findViewById(R.id.to2).setText(messageto2);**
TextView msgfrom = (TextView)findViewById(R.id.from2);
TextView msgcc = (TextView)findViewById(R.id.cc2);
TextView msgbcc = (TextView)findViewById(R.id.bcc2);
TextView msgsubject = (TextView)findViewById(R.id.subject2);
TextView msgbody = (TextView)findViewById(R.id.body2);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
TIA
Try to change this:
(TextView)findViewById(R.id.to2).setText(messageto2);
to
((TextView)findViewById(R.id.to2)).setText(messageto2);
Methods are resolved according to the static type of the reference. findViewById() is declared with a return type of View and since the class View doesn't declare a method setText(), the compiler complains. Use this
TextView msgto = (TextView)findViewById(R.id.to2);
msgto.setText(messageto2);
try this..
((TextView)findViewById(R.id.to2)).setText(messageto2);
TextView msgto = (TextView)findViewById(R.id.to2).setText(messageto2);
Need to be changed to
TextView msgto = (TextView) findViewById(R.id.to2);
msgto.setText(messageto2);
That should help.
This is a simpler version of something I'm working on. When the add button is pressed, what is supposed to happen is, a LinearLayout is created and a CheckBox is also created with the text within the EditText box. The CheckBox is then placed into the newly created LinearLayout, and the newly created LinearLayout, placed in the already existing LinearLayout(named layout). I know it seems unnecessary to create a new LinearLayout but in the main program, its really important. My problem is, when I run the code, the app 'force closes' so I want to know what it is that I'm doing wrong or if there is a better approach I can take to achieve the result I need.
package co.cc.*******.toDo;
import co.cc.*******.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ToDoMainActivity extends Activity implements View.OnClickListener{
/** Called when the activity is first created. */
Button bAdd,bremove;
EditText et;
// CheckBox cbNew;
LinearLayout layout;//main layout
ArrayList<CheckBox> cbNew;//dynamic array of checkBoxes
ArrayList<LinearLayout> cbLayout;//dynamic array of LinearLayouts
int index = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
bAdd.setOnClickListener(this);
bremove.setOnClickListener(this);
}//end method onCreate
void initialize(){
bAdd = (Button)findViewById(R.id.bAdd);
bremove = (Button)findViewById(R.id.bremove);
et = (EditText)findViewById(R.id.et);
layout = (LinearLayout)findViewById(R.id.layout);
cbNew = new ArrayList<CheckBox>();
}//end method initialize
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.bAdd:
cbLayout.add(index, new LinearLayout(this));//create new layout to store cb
cbNew.add(index, new CheckBox(this));//create new checkbox
cbNew.get(index).setText(et.getText().toString()+ index);//set text to text in editText box
cbLayout.get(index).addView(cbNew.get(index));//add checkbox to newly created layout
layout.addView(cbLayout.get(index));//add newly created layout to already existing layout
index ++;
break;
}//end switch
//layout.removeView(cbNew.get(index));
}//end method onClick
}//end class ToDoMainActivity
I have huge problem. Have searching answer from many places but I do not find answer to question.
I have 2 classes in java. One is "main" and other is "menu"
On main, there is editText where person can type name and button ok.
When you press ok, I want to specific thing happen. That is where I need help. I am newcomer in Android.
I want that in other class, where will be main application and stuff, the entered name would be displayed. For example "Welcome " + name
I have tried many ways but I do not get it to work. So I want it to get one of 2 possible ways.
Set string in class 1 and then when it goes class 2, then it imports the string from class 1 to class 2 so I can use it.
I set string in class 2 and then in Class 1 I change the string in class 2, so the main 'data' string is actually in class 2, where I will continue using it if needed!
I have searched it from many places, used google and this database, but haven't found answer.
My codes are really nothing much, so no point pasting them here :).
Thanks for the help!
edit:// Ok, here are some codes then :)
package viimane.voimalus.incule;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ViimaneVoimalusActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button oknupp = (Button) findViewById(R.id.nimiOK);
oknupp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("viimane.voimalus.in" +cule.REALMENU"));
}
});
}
}
package viimane.voimalus.incule;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class RealMenu extends Activity {
EditText nimesisestus;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.peamenu);
}
}
You didn't show any code at all, so the answer won't be too detailed.
You can pass a String in the intent used to start the second activity, using putExtra method. In the second activity you may get the string by calling getStringExtra(). If you don't know much about starting activity and intents, there are many resources on the web, for example - this one.
To receive text input use EditText and to put text on the screen (that the user can't cange) use TextView.
Those are starting points. Next time I hope the question will be more focused.
Pass the string as parameter to the constructor of the menu class like this:
menu m = new menu(mystring);
then in the constructor save the atribute to your class
private String mystring;
menu(String mystring)
{
this.mystring = mystring;
}