Return a string from runnable - android

I'm trying to create an Android Application, but I've a problem with the return of the global variable "tmp2" (String): I've to do a check of tmp2 and if is null for breaking the while cycle. The methods getInvisibleText and getVisibleText are used to split text in pages. How can I do?
public void setText (){
int i = 0;
tmp = stringResponse;
//Log.i("TMP", " 1 " + tmp);
final TextView tv = new TextView (this);
final PageTurnLayout flipper = (PageTurnLayout) findViewById(R.id.flipper);
while (i != 15){
tv.setTextSize(20);
tv.setPadding(7, 5, 5, 0);
tv.requestLayout();
tv.post(new Runnable() {
#Override
public void run() {
tv.setText(tmp);
tmp = getInvisibleText(tv);
tmp2 = getVisibleText(tv);
tv.setText(tmp2);
}
});
Log.i("ifNull", " "+ tmp2);
flipper.addView(tv);
i++;
}
}

Related

Android: String array

I have a game activity about different alphabet are randomly available user would select some of them that are making a correct word.
i made the string array of word which is answer
but i want to knew how to display this answer word alphabets and adding some randomly other alphabet as a confusion?
like taking the answer for example [World] and divid it's alphabet like that [W , L, D , O] AND make them randomly displayed and the player choose from them ?
TextView guessItTimer;
CountDownTimer timer;
Random r;
String currentWord;
private int presCounter = 0;
private int maxPresCounter = 4;
private String[] keys = {"R", "I", "B", "D", "X"};
String dictionary[] = {
"remember",
"hungry",
"crying",
"sour",
"sleep",
"awesome",
"Seven",
"color",
"began",
"appear",
"weight",
"language"
};
TextView textScreen, textQuestion, textTitle;
Animation smallbigforth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guess_it);
guessItTimer = findViewById(R.id.guessItTimer);
smallbigforth = AnimationUtils.loadAnimation(this, R.anim.smallbigforth);
keys = shuffleArray(keys);
for (String key : keys) {
addView(( findViewById(R.id.layoutParent)), key, findViewById(R.id.et_guess));
}
maxPresCounter = 4;
resetTimer();
}
//CountdownTimer
void resetTimer() {
timer = new CountDownTimer(30150, 1000) {
#Override
public void onTick(long l) {
guessItTimer.setText(String.valueOf(l / 1000));
}
#Override
public void onFinish() {
Toast.makeText(GuessItActivity.this, "Time is over", Toast.LENGTH_SHORT).show();
startActivity(new Intent(GuessItActivity.this, BossFinalActivity.class));
finish();
}
}.start();
}
private String[] shuffleArray(String[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
String a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
private void addView(LinearLayout viewParent, final String text, final EditText editText) {
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
linearLayoutParams.rightMargin = 30;
final TextView textView = new TextView(this);
textView.setLayoutParams(linearLayoutParams);
textView.setBackground(this.getResources().getDrawable(R.drawable.bgpink));
textView.setTextColor(this.getResources().getColor(R.color.colorPurple));
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setClickable(true);
textView.setFocusable(true);
textView.setTextSize(32);
textQuestion = findViewById(R.id.textQuestionBoss);
textScreen = findViewById(R.id.gametitle);
textTitle = findViewById(R.id.Ammo);
textView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if(presCounter < maxPresCounter) {
if (presCounter == 0)
editText.setText("");
editText.setText(editText.getText().toString() + text);
textView.startAnimation(smallbigforth);
textView.animate().alpha(0).setDuration(300);
presCounter++;
if (presCounter == maxPresCounter)
doValidate();
}
}
});
viewParent.addView(textView);
}
private void doValidate() {
presCounter = 0;
EditText editText = findViewById(R.id.et_guess);
LinearLayout linearLayout = findViewById(R.id.layoutParent);
currentWord = dictionary[r.nextInt(dictionary.length)];
if(editText.getText().toString().equals(currentWord)) {
//Toast.makeText(GuessItActivity.this, "Correct", Toast.LENGTH_SHORT).show();
Intent a = new Intent(GuessItActivity.this,BossFinalActivity.class);
startActivity(a);
editText.setText("");
} else {
Toast.makeText(GuessItActivity.this, "Wrong", Toast.LENGTH_SHORT).show();
editText.setText("");
}
keys = shuffleArray(keys);
linearLayout.removeAllViews();
for (String key : keys) {
addView(linearLayout, key, editText);
}
}
public void onBackPressed() {
timer.cancel();
this.finish();
super.onBackPressed();
}
You can achieve it like this
String a2z = "abcdefghijklmnopqrstuvwxyz";
String answer = "World";
// lets assume you need 16 char to select from
ArrayList<Character> chars = new ArrayList<Character>();
for (int i = 0; i < answer.length(); i++) {
chars.add(answer.charAt(i));
}
int dif = 16 - chars.size();
Random rand = new Random();
for (int i = 0; i < dif; i++) {
int ranIndex = rand.nextInt(a2z.length());
chars.add(a2z.charAt(ranIndex));
}
Collections.sort(chars);
System.out.println("nameArray2" + chars.toString());

How to fetch edittext and text values created dynamically?

Am trying to create edittext and textview widgets dynamically into program. it works fine. now i want to access the textvalue with its corresponding edittext value. how to do it?
Here is what i have tried.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callreport);
dcname = ProductdetailsEnd.doctor;
resultArr1 = ProductdetailsEnd.resultArr;
callreportbtn = (Button) findViewById(R.id.callreportbtn);
arraysize = resultArr1.length;
TableLayout tb = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < arraysize; i++) {
res = resultArr1[i];
TableRow tr = new TableRow(this);
TableRow.LayoutParams pl = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT);
tr.setLayoutParams(pl);
tr.setWeightSum(1.0f);
product = new TextView(this);
product.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f));
product.setId(i);
qty = new EditText(this);
qty.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f));
qty.setId(i);
qty.setWidth(50);
product.setText(res);
tr.addView(product);
tr.addView(qty);
tb.addView(tr, i);
Log.d("Call Report name : ", "" + dcname);
Log.d("Call Report prod :", "" + res);
}
Log.d("res length : ", "" + arraysize);
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
String qty1 = qty.getText().toString();
Log.d("products &&: ", "" + product1 + ":" + qty1);
}
callreportbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_LONG).show();
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
String qty1 = qty.getText().toString();
Log.d("products &&: ", "" + product1 + ":" + qty1);
}
}
});
}
after entering the value, when i say submit it should display the textview value along with edittext value.
For more convenience i have added a snap of my output.
first image to enter the value
second image is output in logcat.
There are many ways to do what you want.
Place your views inside a List object, and read the list when you submit.
Implement TextWatcher interface and record your String values as they change.
Assign an Id to your views, and later retrieve your views by Id.
Third option required you to carefully assign id's, because I think they must be unique. Second option, I think, is best one in many cases, since you may also want to provide some feedback to user.
EDIT:
TextWatcher is interface that receives callbacks from TextView. Simply call addTextChangedListener method and provide a TextWatcher implementation.
aTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Finally i got the answer. referred this post - Creation of EditText Dynamically and get their text from each of EditText
Created an array of the EditText and accessed it in the button onclick method.
this is my code and its working.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callreport);
dcname = ProductdetailsEnd.doctor;
resultArr1 = ProductdetailsEnd.resultArr;
callreportbtn = (Button) findViewById(R.id.callreportbtn);
quantity = new ArrayList<EditText>();
arraysize = resultArr1.length;
TableLayout tb = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < arraysize; i++) {
res = resultArr1[i];
TableRow tr = new TableRow(this);
TableRow.LayoutParams pl = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT);
tr.setLayoutParams(pl);
tr.setWeightSum(1.0f);
product = new TextView(this);
product.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f));
product.setId(i);
qty = new EditText(this);
qty.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f));
//qty.setId(i);
qty.setWidth(50);
product.setText(res);
tr.addView(product);
tr.addView(qty);
tb.addView(tr, i);
quantity.add(qty);
Log.d("Call Report name : ", "" + dcname);
Log.d("Call Report prod :", "" + res);
}
Log.d("res length : ", "" + arraysize);
Log.d("qty length : ", "" + qty.length());
String[] items1 = new String[quantity.size()];
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
items1[i] = quantity.get(i).getText().toString();
Log.d("qty id ", "" +qty.toString());
Log.d("products &&: ", "" + product1 + ":" + items1);
}
callreportbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_LONG).show();
String[] items = new String[quantity.size()];
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
items[i] = quantity.get(i).getText().toString();
Log.d("products &&: ", "" + product1 + ":" + items[i]);
}
}
});
}

My code throws ArrayIndexOutOfBoundException but i think it's ok

here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.

working with canvas : The specified child already has a parent. You must call removeView() on the child's parent first

I visit so many solutions regarding this issue but can't catch it clearly .When ever I run the project first time it works perfectly but when I run it second time then it fire this error in logCat
The specified child already has a parent. You must call removeView() on the child's parent first
where is the error in that code segment ?where should I change in code. any suggestion is acceptable .Thanks in advance ..
Main.java
public class MainActivity extends Activity {
List<PieDetailsItem> piedata = new ArrayList<PieDetailsItem>(0);
EditText edt3;
Button btnChart;
public String s15;
public String[] strArray;
public ImageView mImageView ;
public LinearLayout finalLayout ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
finalLayout = (LinearLayout) findViewById(R.id.pie_container);
mImageView = new ImageView(this);
edt3 = (EditText) this.findViewById(R.id.editText1);
btnChart = (Button) findViewById(R.id.button1);
btnChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*if(mImageView != null) {
finalLayout.removeView(mImageView);
}
else {*/
s15 = edt3.getText().toString();
/*System.out.println("value 1 is --->"+s10);
System.out.println("value 2 is --->"+s12);*/
System.out.println("value 3 is --->"+s15);
String domain = s15;
strArray = domain.split("\\,");
for (String str : strArray) {
System.out.println(str);
}
// }
openChart();
}
});
}
private void openChart(){
Integer[] items = new Integer[strArray.length];
//double[] distribution = new double[strArray.length];
for (int i = 0; i < items.length; i++) {
items[i] = Integer.parseInt(strArray[i]);
System.out.println("xxxxxx"+items[i]);
}
PieDetailsItem item;
int maxCount = 0;
int itemCount = 0;
// int items[] = { 20, 40, 10, 15, 5 };
int colors[] = { -6777216, -16776961, -16711681, -12303292, -7829368 };
// String itemslabel[] = { " vauesr ur 100", " vauesr ur 200",
// " vauesr ur 300", " vauesr ur 400", " vauesr ur 500" };
for (int i = 0; i < items.length; i++) {
itemCount = items[i];
item = new PieDetailsItem();
item.count = itemCount;
// item.label = itemslabel[i];
item.color = colors[i];
piedata.add(item);
maxCount = maxCount + itemCount;
}
int size = 200;
int BgColor = 0xffa11b1;
Bitmap mBaggroundImage = Bitmap.createBitmap(size, size,
Bitmap.Config.ARGB_8888);
View_PieChart piechart = new View_PieChart(this);
piechart.setLayoutParams(new LayoutParams(size, size));
piechart.setGeometry(size, size, 2, 2, 2, 2, 2130837504);
piechart.setSkinparams(BgColor);
piechart.setData(piedata, maxCount);
piechart.invalidate();
piechart.draw(new Canvas(mBaggroundImage));
piechart = null;
//ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mImageView.setBackgroundColor(BgColor);
mImageView.setImageBitmap(mBaggroundImage);
//LinearLayout finalLayout = (LinearLayout) findViewById(R.id.pie_container);
finalLayout.addView(mImageView);
}
}
You're adding mImageView to the layout multiple times. A view can only be part of 1 ViewGroup. You need to either add it only once, or create a second ImageView if you really want 2 of them in the layout.

Multiple clickspans in a textview

I have a function to build clickable tags for a textview. It goes as follows:
private CharSequence tagsBuilder(String text, String token) {
SpannableStringBuilder builtTags = new SpannableStringBuilder();
int start = 0, end = 0;
for(int i = 0; i < 5; i++) {
start = 0;
end = text.indexOf(token, 0);
try {
if(start < end) {
SpannableStringBuilder ssb = new SpannableStringBuilder(text.substring(start, end));
ssb.setSpan(new ClickableSpan() {
#Override
public void onClick(View v)
{
Log.i("DEBUGTAG", "Span clicked - " + ((TextView) v).getText());
}
}, start, end, 0);
builtTags.append(ssb);
builtTags.append(" ");
text = text.substring(end + 1);
}
} catch (IndexOutOfBoundsException e) {
break;
}
}
return builtTags;
}
I can see the textview with 5 individually clickable tags. But the problem is, the Log that prints for any tag that is clicked is whole text of the textview.
Am I doing something wrong here? How do I get the text of individual tags that were clicked.
Your log line is the following:
Log.i("DEBUGTAG", "Span clicked - " + ((TextView) v).getText());
That logs the contents of the TextView. So... you get the text of the TextView. If you want to get token in there, you'll have to copy that in.
Here's something you can try:
private CharSequence tagsBuilder(String text, final String token) {
SpannableStringBuilder builtTags = new SpannableStringBuilder();
int start = 0, end = 0;
for(int i = 0; i < 5; i++) {
start = 0;
end = text.indexOf(token, 0);
try {
if(start < end) {
SpannableStringBuilder ssb = new SpannableStringBuilder(text.substring(start, end));
ssb.setSpan(new ClickableSpan() {
private String mText = token;
#Override
public void onClick(View v)
{
Log.i("DEBUGTAG", "Span clicked - " + mText);
}
}, start, end, 0);
builtTags.append(ssb);
builtTags.append(" ");
text = text.substring(end + 1);
}
} catch (IndexOutOfBoundsException e) {
break;
}
}
return builtTags;
}

Categories

Resources