My code seems to run but it does not display the result any result on text view am guessing is because of the way I set my code. The code is below Somebody please help me. Thanks
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
Button button = (Button) findViewById(R.id.but);
input = (EditText) findViewById(R.id.editTextj);
display = (TextView) findViewById(R.id.textView8);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CCActivity3 fs = new CCActivity3();
fs.fileReader();
}// button
});// button end
}
public void fileReader() {
try {
InputStream is=this.getResources().openRawResource(R.raw.file);
BufferedReader bc = new BufferedReader(new InputStreamReader(is));
String cLine;
String inputText = "";
List<String> test2 = new ArrayList<String>();
// read file line by line
while ((cLine = bc.readLine()) != null) {
inputText = inputText + cLine + "\n";
}
s = input.getText().toString();
test = CCActivity3.getPermutation(s);//Permutation method
test2.retainAll(test);//intersection
String fg = "";
for (String s2 : test2) {
fg += s2 + "\n";
}
display.setText(fg);
bc.close();
} catch (Exception e) {// catch any errors if necessary
display.setText(e.getMessage());
}
}
If you check the resource line am very sure am not getting that right and also the formating of the code I believe they just scattered . Hint the file.txt on the res/raw path has more than 100,000 strings/words, could this be the cause.Thanks Again
Regarding your code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CCActivity3 fs = new CCActivity3();
fs.fileReader();
}// button
});// button end
Is CCActivity3 derived from an Activity?
If so, then you shouldn't construct it this way.
You can't instantiate your own Activity class. Only the Android framework can do that.
What seems to be happening here is that inside fileReader(), you are calling getResources() on an Activity whose Context has not yet been properly initialized by onCreate().
In any case, one thing you can do is call fileReader() method directly without instantiating CCActivity3, like so:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fileReader();
}// button
});// button end
test = CCActivity3.getPermutation(s);//Permutation method
test2.retainAll(test);//intersection
Above codes can get the right return?
Related
I am trying desperately to read a file from Android Studio asset folder. The file is "ok.txt" and contains the string: yo chicken mcgriddle fiddle fiddle.
Per this video: https://youtu.be/1CHDASXojNQ and stackoverflow browsing, this is the solution I came up with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
tv_text = (TextView) findViewById(R.id.nameView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv_text.setText(LoadData("ok.txt"));
}
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
});
}
}
I am inclined to believe that the code works, but, it does not return the String. In the app, it returns a blank message in the place of the textview's "hello world" placeholder after clicking the button. I thought it was due to the limitation of the textview so I modified the constraint size, but the blank persists. Anybody know what's up?
I am new working with this customized Dialog in android. I may not be able to clarify my problem properly by writing, So it humble request to understand what i want from given code.
In MainActivity i have Button to delete an element of an ArrayList and setting the info from the ArrayList to a Layout.
Code from CustomDialog:
public class PermissionToDelete extends Dialog implements View.OnClickListener {
public Button btnYes, btnNo;
public TextView txtPermToDelete;
public PermissionToDelete(Context context){
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.permission_delete);
initialize();
}
public void initialize(){
btnYes = findViewById(R.id.btnYes);
btnNo = findViewById(R.id.btnNo);
txtPermToDelete = findViewById(R.id.txtPermToDelete);
btnYes.setOnClickListener(this);
btnNo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnNo){
dismiss();
}
else if(v.getId() == R.id.btnYes){
MainActivity.deleteOrErase = "delete";
dismiss();
}
}
}
There is a static String variable in MainActivity named deleteOrErase.
From dialog it returns the string delete if Button Yes is clicked.
Code from MainActivity:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String text = tv.getText().toString();
PermissionToDelete permissionToDelete = new PermissionToDelete(MainActivity.this);
permissionToDelete.show();
if(deleteOrErase.equals("delete")){
String index = "";
for(int i = 1; text.charAt(i) != ')'; i++){
index += text.charAt(i);
}
tasksList.remove(Integer.parseInt(index) - 1);
File rootFile = new File(rootFolder);
if(rootFile.exists()){
String[]entries = rootFile.list();
for(String s: entries){
File currentFile = new File(rootFile.getPath(),s);
currentFile.delete();
}
rootFile.delete();
}
dailyTasksLayout.removeAllViews();
makePrimaryFileAndFolder();
saveDataToFile();
setTaskList();
deleteOrErase = "";
}
But the problem is before button from dialog is clicked, if(deleteOrErase.equals("delete")) is encountered when the value of deleteOrErase is still null.
Therefore data isn't deleted at the first click.
Its need second click to delete, because now the value of deleteOrErase is "delete".
How can i delete it from first click?
Or is there any other way???
thanks dear honorable members! <3
(I don't know either i could clarify my problem or not.
Even i can't understand from mty writings :P )
I am trying to create a repeating text app. So I use a for loop for repeating the text and display this text in a textview.
When I press a button then I want it to generate the text as many times as the loop runs.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterText = findViewById(R.id.editText);
repeatText = findViewById(R.id.repeatTime);
genTxt = findViewById(R.id.genText);
genrate = findViewById(R.id.generate);
reset = findViewById(R.id.reset);
copy = findViewById(R.id.copyButton);
share = findViewById(R.id.shareButton);
genrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Storing text in Gen Text Area
String txt = enterText.getText().toString().trim();
//Storing Repeat value
String repeats = repeatText.getText().toString().trim();
int repealVal = Integer.parseInt(repeats);
for(int i=1;i<=repealVal;i++){
genTxt.setText(txt);
Log.d("tets","loop "+i+txt);
}
}
});
}
public void reset(View view){
enterText.setText("");
repeatText.setText("");
genTxt.setText("");
}
When I run it I only get the text one time in my textview.
Try changing your onClick method to the following:
genrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Storing text in Gen Text Area
String txt = enterText.getText().toString().trim();
//Storing Repeat value
String repeats = repeatText.getText().toString().trim();
int repealVal = Integer.parseInt(repeats);
for(int i=1;i<=repealVal;i++){
genTxt.setText(genTxt.getText() + txt);
Log.d("tets","loop "+i+txt);
}
}
});
Note that inside the loop you are only switching the text, not adding to the text.
To even further optimize solution, you should consider using .append() instead of .setText()
Here you are setting text to same TextView again and again.
If you want to dynamically generate multiple TextViews you can try below solution.
Give an id to your root layout in xml where you want to add text. Here I am using LinearLayout. Add it in your code as below:
LinearLayout linearLayout = findViewById(R.id.ll) //ll is the id of LinearLayout
Then add this in your onclick
TextView txtView;
for(int i = 1; i <= repealVal; i++) {
txtView = new TextView(MainActivity.this);
txtView.setText(txt);
linearLayout.addView(txtView);
}
when clicking on the button it does nothing ,,,after testing I concluded the problem is with the equal method statment ,,,the whole issue is when comparing string array to string any solutions?
EditText coderead = (EditText)findViewById(R.id.editText1);
Button go = (Button)findViewById(R.id.button1);
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
final double pointx[] ={23.666666,65.22222};
final double pointy[] ={31.55555,29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
for (int i=0; i<code.length; i++) {
if(code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
}
else{Toast.makeText(getBaseContext(), "code not found", 5000);}
}
}
});
Your mn variable should be read after your button has been clicked.
Button go = (Button) findViewById(R.id.button1);
final String code[] = {"m1", "n2"};
final double pointx[] = {23.666666, 65.22222};
final double pointy[] = {31.55555, 29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
// mn should be read after the button click!
EditText coderead = (EditText) findViewById(R.id.editText1);
final String mn = coderead.getText().toString();
for (int i = 0; i < code.length; i++) {
if (code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
} else {
Toast.makeText(getBaseContext(), "code not found", 5000);
}
}
}
});
So if I understand your code correctly you are trying to respond to a button click and take the text that has been input and do something based on that?
You are setting the value of mn at the time you are creating the button, rather than when the button is pressed. At that time the text will be empty (or null). You should move the code to get the value of the entered text to within the onClickListener.
Should your "code not found" message happen outside the for loop?
What do you mean by nothing happens? Do you get a Toast message or not? Did you make sure that no error is being generated? If you are not getting the Toast Message and you have no errors, then make sure the intent is correct. I would recommend you debug the code from the line of Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
Then, report what is happening back here.
Something I don't get. With these two lines:
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
Why don't you just compute the (final) index to code right then and there, vs waiting until onClick?
To all you that have helped me with my other questions thank you. I almost have it, but 2 final problems are preventing it from working the way i want.
These 2 classes are supposed to do as follows. 1st class gets the names of the people that want to play the game. Uses the same EditText and when they input their name they click submit. When all the names are submitted they click the done/play button which sends them and their data (how many players and names) to the next class. On class 1 i believe the error lies in the submit button. I'm trying to add all the names to an array list and I dont believe it is doing it correctly. When I run the app it takes in the names just fine from the users standpoint. But on the following screen it should display their name: (it says null so it is not getting the names correctly) and a task to do (which it does correctly).
The last thing it needs to do is on class 2 it needs to allow those buttons (failed, champ, and not bad) to only need to be clicked once (then it sets a score to the name of the person who's turn it was) and then it needs to start the next person and task. (It does neither atm). I would really appreciate help getting this blasted thing to work. Thanks to all who take the time to reply. And sorry if ur sick of seeing my help requests.
Class 1
public class Class1 extends Activity
{
int players=0, i=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
//names = new String[players];
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
//for( i=i; i < players; i++)
//{
players++;
names.add(input.getText().toString());
//names[i] = input.getText().toString();
input.setText("");
//}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names;
String[] tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks = new String[10];
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
names = new String[players];
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
return;
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
return;
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
return;
}
});
}
counter++;
}
}
}
As a side note. The things that you see within those sections that have // comments next to them I have there because i was testing out between those and the ones that arent commented out and neither worked. If you have any input on fixing any of this i appreciate it.
I see two problems with your code that might explain why you get a null for your players list in your second Activity:
In Game, String[] names = bundle.getStringArray("arrayKey"); should be
ArrayList<String> names = bundle.getStringArrayList("arrayKey");`
In Class1, you're putting the ArrayList into the Bundle(bundle.putStringArrayList("arrayKey", names);) which is pointless since bundle goes no where. You should be putting it into the Intent instead:
done.putStringListExtra("arrayKey", names);
Note that your code is all the more confusing because you have both a String [] named names and an ArrayList named names in different scopes. Decide on one (I'd recommend the List) and get rid of the other.
Also, in Game, this is unncessary:
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
You already have the bundle just before this, so you could as well do:
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
players = bundle.getInt("players", 1);
The basic concept is that from the calling activity, you put information into an Intent using the various putExtra() and putExtraXXX() methods. In the called activity, you get the information you had put into the Intent by either
getting a Bundle *from * the Intent via getExtras() and then getting everything put in using the various get() methods on the Bundle (not the Intent).
directly invoking the getExtraXXX() methods on the Intent.
For the second part, as your code currently stands, it simply going to loop over all the players immediately (5 times in all, I don't understand the purpose of counter).
What you should instead be doing is performing all of your processing (calculating the score for the current player, incrementing the value of the player index, setting the next task etc) only when one of the 3 buttons is pressed. If it's going to be a long-lived task, you could disable the buttons until finished in order to enforce the requirement of allowing only one button to be pressed per player. Re-enable the buttons when the next player is ready.
I don't have the energy to churn out everything you need but at a starting point, turn this:
public void onCreate(Bundle savedInstanceState)
{
//...other code here
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
return;
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
return;
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
return;
}
});
}
counter++;
}
//...other code here
}
into
public void onCreate(Bundle savedInstanceState)
{
//...other code here
int i = 0;
TextView name1 = (TextView) findViewById(R.id.pname);
TextView task = (TextView) findViewById(R.id.task);
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
//do what must be done for the current player, calculate score, etc
prepareNextPlayer(++i, names, name1, task);
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
//do what must be done for the current player, calculate score, etc
prepareNextPlayer(++i, names, name1, task);
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
//do what must be done for the current player, calculate score, etc
prepareNextPlayer(++i, names, name1, task);
}
});
//...other code here
}
private void prepareNextPlayer(int i, ArrayList<String> names, String [] tasks, TextView nameField, TextView taskField)
{
if(i >= names.size())
{
//all players have been processed, what happens now?
return;
}
int rindex = generator.nextInt(10);
nameField.setText( names.get(i)+":");
task.setText( tasks[rindex]);
}