I am having trouble in displaying the values in text view. It displays only the last value in text view. I want to iterate each and every value in new line.
Here is my code.
PreviewCatNameTxt = new TextView[obdatin.catCount];
PreviewNameTxt = new TextView[10];
PreviewQtyTxt = new TextView[10];
PreviewAmtTxt = new TextView[10];
System.out.println("setview3");
for(int i=0;i<obdatin.catCount;i++){
System.out.println("num oof prca"+obdatin.catList[i].getNumCategory());
if(obdatin.catList[i].isTotQtyNonZero(0)){
PreviewCatNameTxt[i] = (TextView) findViewById(R.id.textViewh);
PreviewCatNameTxt[i].setText(obdatin.catList[i].getCategoryName(0));
System.out.println("prca"+obdatin.catList[i].getCategoryName(0));
}
int cnt =obdatin.catList[i].proList.getNumProduct();
System.out.println("setview3");
for(int j = 0; j<cnt; j++) {
if(obdatin.catList[i].proList.isQtyNonZero(j)){
PreviewNameTxt[j] = (TextView)findViewById(R.id.textView1);
PreviewNameTxt[j].setText(obdatin.catList[i].proList.getProductName(j));
PreviewQtyTxt[j] = (TextView)findViewById(R.id.textView2);
PreviewQtyTxt[j].setText(obdatin.catList[i].proList.getProductQty(j));
PreviewAmtTxt[j] = (TextView)findViewById(R.id.textView3);
String amt = obdatin.catList[i].proList.getProductAmt(j);
PreviewAmtTxt[j].setText(amt);
System.out.println("prcaN"+obdatin.catList[i].proList.getProductName(j));
System.out.println("prcaQ"+obdatin.catList[i].proList.getProductQty(j));
System.out.println("prcaA"+obdatin.catList[i].proList.getProductAmt(j));
}
}
Edited Code as per your requirement
PreviewCatNameTxt = (TextView) findViewById(R.id.textViewh);
for(int i=0;i<obdatin.catCount;i++){
System.out.println("num oof prca"+obdatin.catList[i].getNumCategory());
if(obdatin.catList[i].isTotQtyNonZero(0)){
PreviewCatNameTxt.append(" "+obdatin.catList[i].getCategoryName(0));
System.out.println("prca"+obdatin.catList[i].getCategoryName(0));
}
int cnt =obdatin.catList[i].proList.getNumProduct();
System.out.println("setview3");
for(int j = 0; j<cnt; j++) {
if(obdatin.catList[i].proList.isQtyNonZero(j)){
PreviewCatNameTxt.append("\n"+obdatin.catList[i].proList.getProductName(j));
PreviewCatNameTxt.append("\n"obdatin.catList[i].proList.getProductQty(j));
String amt = obdatin.catList[i].proList.getProductAmt(j);
PreviewCatNameTxt.append("\n"+amt+"\n\n");
System.out.println("prcaN"+obdatin.catList[i].proList.getProductName(j));
System.out.println("prcaQ"+obdatin.catList[i].proList.getProductQty(j));
System.out.println("prcaA"+obdatin.catList[i].proList.getProductAmt(j));
}
Please remove TextView array and all those things. Please reply your feedback.
I am not entirely sure what you are trying to do.Why do you use System.out.println?
If I got it right you want a larger text to be put in TextView separated by newlines after each loop of the for. One way to do it is to have a String which you fill with every iteration, also adding a newline after each iteration and after the for setting the text.
So, you could have something like this:
String catList="";
for(int i=0;i<obdatin.catCount;i++){
if(obdatin.catList[i].isTotQtyNonZero(0)){
catList = catList + obdatin.catList[i].getCategoryName(0) + "\n";
}
int cnt =obdatin.catList[i].proList.getNumProduct();
PreviewCatNameTxt[i] = (TextView) findViewById(R.id.textViewh);
PreviewCatNameTxt[i].setText(catList);
Also, if you want to log something you should od to use LogCat. You can read about Reading and Writing in LogCat here and here.
Good luck!
PreviewNameTxt[j] = (TextView)findViewById(R.id.textView1);
PreviewQtyTxt[j] = (TextView)findViewById(R.id.textView2);
PreviewAmtTxt[j] = (TextView)findViewById(R.id.textView3);
String cat="",obtaincat="",amt="";
for(int j = 0; j<cnt; j++) {
if(obdatin.catList[i].proList.isQtyNonZero(j)){
cat = cat + obdatin.catList[i].getCategoryName(j) + "\n";
obtaincat=btaincat+obdatin.catList[i].proList.getProductQty(j)+"\n";
amt =amt+ obdatin.catList[i].proList.getProductAmt(j)+"\n";
}
}
PreviewNameTxt[j].setText(cat);
PreviewQtyTxt[j].setText(obtaincat);
PreviewAmtTxt[j].setText(amt);
Change to Logcat :
Log.w("","prcaN"+obdatin.catList[i].proList.getProductName(j));
Log.w("","prcaQ"+obdatin.catList[i].proList.getProductQty(j));
Log.w("","prcaA"+obdatin.catList[i].proList.getProductAmt(j));
Related
hi
why load text from String array and set text to textview is very slow in big string array?
please help to me.
//get khotbe text from database and copy to khotbe activity
private void setkhotbetextarabicfarsi() {
this.sqliteDB = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("aliname").getPath(), (SQLiteDatabase.CursorFactory) null);
Itemid = this.getIntent().getIntExtra("selectedFromListid", 1);
Cursor cursorLines = this.sqliteDB.rawQuery("SELECT * FROM khotbe where IDFehrest=" + this.Itemid , (String[]) null);
allrecs = cursorLines.getCount();
matn = new String[allrecs];
if (this.allrecs != 0) {
cursorLines.moveToFirst();
for (int i = 0; i < this.allrecs; ++i) {
String TextArabicOfKhotbe = cursorLines.getString(cursorLines.getColumnIndex("TextArabicOfKhotbe"));
int IDkhotbe = cursorLines.getInt(cursorLines.getColumnIndex("IDkhotbe"));
this.matn[i] = TextArabicOfKhotbe;
cursorLines.moveToNext();
}
}
and main code:
for(int var1 = 0; var1 < this.allrecs; ++var1) {
tvArabic = new JustifiedTextView(this);
tvArabic.setText(matn[var1]);
you are creating the textviews in loop that might making it slow.. try populating the array values using an adapter..
Also check the number of rows you are accessing from the DB. if they are huge in number, they would require more time to be fetched.
Use limit in that case.
I have setup an edittext box and set the maxlength to 10. When I copy the edittext to a string myTitles. I need the myTiles to be 10 chars long and not dependent on what is entered in the edittext box.
myTitles[0] = TitlesEdit.getText().toString();
The edittext was filled with ABCD so I need to add 6 spaces or placeholders after the ABCD. I have seen other post with str_pad and substr without success
myTitles[0] = str_pad(strTest, 0, 10);
myTitles[0] = substr(strTest,0, 10);
Try something like
public static String newString(String str) {
for (int i = str.length(); i <= 10; i++)
str += "*";
return str;
}
This will return a String with * replaced for the empty ones.
So, for eg, if your String is abcde, then on calling newString() as below
myTitles[0] = newString("abcde");
will return abcde***** as the output.
String s = new String("abcde");
for(int i=s.length();i<10;i++){
s = s.concat("-");
}
Then output your string s.
Thank you Lal, I use " " to fill and it worked fine. here is my new code.
String strTest = TitlesEdit.getText().toString();
for (int i = strTest.length(); i <= 10; i++) {
strTest += " ";
}
Log.d("TAG", "String" + strTest);
myTitles[intLinenumber] = strTest;
I fetch my data from my web server using JSON string (see below)
{"identification":[{"question":"Who created the C programming language?","answers":"Dennis Ritchie","subject":"1","points":"1","question-id":"1"},{"question":"What company created Visual Basic?","answers":"Microsoft","subject":"1","points":"1","question-id":"2"}],"multiplechoice":[{"question":"Which of the following programming languages are not Object Oriented?","answers":"C","choices":["Java","Visual Basic"],"subject":"1","points":"1","question-id":"3"},{"question":"The person who is responsible for the creation of Facebook?","answers":"Mark Zuckerberg","choices":["Steve Jobs","Bill Gates","Larry Page"],"subject":"1","points":"1","question-id":"4"}]}
Using that data I created a dynamic components for e.g. some question have 3 choices hence 3 radio buttons some have 5 choices which is 5 radio buttons etc.
Now the main problem is I really don't have any idea on how to get the reference of the components that I created programmatically, I know how use findViewById when using XML but this time there are no XML file used except for the parent layouts.
I'm planning on retrieving and parsing all the value of the components that I created back into JSON string. (which I have an idea on how to do and not the main problem of this question)
The code below is the one who is responsible for dynamically creating components:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jObject = new JSONObject(jsonObj.toString().trim());
Iterator<?> keys = jObject.keys();
Log.d("TEST: ", "WORKING> " + "ENABLED");
JSONArray temp_json_arr = null;
JSONObject temp_json_obj = null;
String temp_string = "";
int question_number = 1;
LinearLayout ll = (LinearLayout)findViewById(R.id.test_layout);
while( keys.hasNext() ){
String key = (String)keys.next();
Log.d("TEST: ", "KEYS> " + key);
// Getting JSON Array node
temp_json_arr = jsonObj.getJSONArray(key);
// looping through All Questions
for (int i = 0; i < temp_json_arr.length(); i++) {
Log.d("TEST: ", "EXECUTE> before if condition");
JSONObject q = temp_json_arr.getJSONObject(i);
if( key.equals("identification") ) {
Log.d("TEST: ", "EXECUTE> START");
int element_ctr = 0;
TextView[] question_textview = new TextView[10];
TextView[] label_textview = new TextView[10];
EditText[] answer_edittext = new EditText[10];
TextView[] seperator_textview = new TextView[10];
//question node
question_textview[element_ctr] = new TextView(getApplicationContext());
question_textview[element_ctr].setText(question_number+". "+q.getString("question"));
question_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
//question_textview[element_ctr].
ll.addView(question_textview[element_ctr]);
//label node
label_textview[element_ctr] = new TextView(getApplicationContext());
label_textview[element_ctr].setText("Answer:");
label_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(label_textview[element_ctr]);
//answer node
answer_edittext[element_ctr] = new EditText(getApplicationContext());
answer_edittext[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(answer_edittext[element_ctr]);
if(i!=temp_json_arr.length()-1) {
//seperator
seperator_textview[element_ctr] = new TextView(getApplicationContext());
seperator_textview[element_ctr].setText("--------------------------------------------------");
ll.addView(seperator_textview[element_ctr]);
Log.d("TEST: ", "EXECUTE> END");
}
}
if( key.equals("multiplechoice") ) {
Log.d("TEST: ", "EXECUTE> START");
int element_ctr = 0;
TextView[] question_textview = new TextView[10];
TextView[] label_textview = new TextView[10];
RadioButton[] answer_radiobutton = new RadioButton[10];
TextView[] seperator_textview = new TextView[10];
//question node
question_textview[element_ctr] = new TextView(getApplicationContext());
question_textview[element_ctr].setText(question_number+". "+q.getString("question"));
question_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(question_textview[element_ctr]);
//label node
label_textview[element_ctr] = new TextView(getApplicationContext());
label_textview[element_ctr].setText("Answer:");
label_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(label_textview[element_ctr]);
//choices node
JSONArray temp_json_arr2 = null;
temp_json_arr2 = q.getJSONArray("choices");
temp_string = q.getString("answers");
temp_json_arr2.put(temp_string);
Random rnd = new Random();
for (int k = temp_json_arr2.length() - 1; k >= 0; k--)
{
int j = rnd.nextInt(k + 1);
// Simple swap
Object object = temp_json_arr2.get(j);
temp_json_arr2.put(j, temp_json_arr2.get(k));
temp_json_arr2.put(k, object);
}
Log.d("TEST: ", "TRAP> START");
int group_ctr = 0;
RadioButton[] choices_radiobutton = new RadioButton[10];
RadioGroup[] choices_radiogroup = new RadioGroup[10]; //create the RadioGroup
choices_radiogroup[group_ctr] = new RadioGroup(getApplicationContext());
choices_radiogroup[group_ctr].setOrientation(RadioGroup.VERTICAL);
Log.d("TEST: ", "TRAP> END");
for (int t = 0; t < temp_json_arr2.length(); t++) {
choices_radiobutton[t] = new RadioButton(getApplicationContext());
choices_radiobutton[t].setText(temp_json_arr2.getString(t));
choices_radiobutton[t].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
choices_radiogroup[group_ctr].addView(choices_radiobutton[t]); //the RadioButtons are added to the radioGroup instead of the layout
}
ll.addView(choices_radiogroup[group_ctr]);//you add the whole RadioGroup to the layout
group_ctr++;
if(i!=temp_json_arr.length()-1) {
//seperator
seperator_textview[element_ctr] = new TextView(getApplicationContext());
seperator_textview[element_ctr].setText("--------------------------------------------------");
ll.addView(seperator_textview[element_ctr]);
Log.d("TEST: ", "EXECUTE> END");
}
}
if( key.equals("truefalse") ) {
//Log.d("TEST: ", "hi iam true or false");
}
question_number++;
}//end for
}//end while
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm sorry for codes, I just started creating android app and I'm still trying to get a hang with basic stuffs before jumping into complicated code structures, I just want to solve the problem I'm having right now before proceeding with other things.
One simple solution would be to set ID for the Views/components when you create them in the code.
Use this method.
someView.setId(int);
The int must be positive. (Any number)
Once you set the ID, you can refer it in the code elsewhere.
Example
TextView1.setId(10);
TextView tv = (TextView)findViewById(10);
Though it may seems complicated at the start may help you improve on further requirement.
It is better to create a DataStructure (custom class) to de-serialize this json to Object (refer GSON library) then bind it to the UI. And then if UI is updated assign the updated values to Object and send back to server (refer Retrofit library for easy REST operations)
i want to show json in html tag below mycode im getting json and show in two diffrent textview but i want to show in single lines and show all getJSONObject(i).getString("name")); name in bold color and all getJSONObject(i).getString( "sub_ingredients")); in simple text do not want to use two textview i want toshow insingle text view what wil ido? i want to show as html tag
"dish_ingredient":
[
{"name":"Salt","sub_ingredients":""},
{"name":"Sesame Seeds","sub_ingredients":""},
{"name":"Calcium Sulfate","sub_ingredients":""},
{"name":"Brown Sugar","sub_ingredients":""},
{"name":"Salt","sub_ingredients":""},
{"name":"Hamburger Bun","sub_ingredients":""},
{"name":"Cheese-cultured pasteurized milk","sub_ingredients":""},
{"name":"Hamburger Bun","sub_ingredients":"Wheat, Niacin, Eggs"}]}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
row4 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row4.findViewById(R.id.name)).setText(school5
.getJSONObject(i).getString("name"));
((TextView) row4.findViewById(R.id.subingredients))
.setText(school5.getJSONObject(i).getString( "sub_ingredients"));
table3.addView(row4);
}
If I understand correctly you want to display the JSON as formatted above in one TextView but with certain highlighting. Check out this post. If you want to keep the JSON in its original format I would just get the initial JSONArray, call toString(), and then replace the words "name" and "sub-ingredient" with text fomatted the way you want.
If I misunderstood and you want to extract the values for each JSONObject you just need to loop through the JSONArray
//format these to look like whatever you want
SpanableString nameTitle = "Name: "
SpanableString subIngredientTitle = " Sub-ingredient: ";
String concatProduct = "";
int arraySize = jsonArray.length();
for(int i = 0; i < arraySize; i++){
JSONObject thing = jsonArray.getJSONObject(i);
String name = thing.getString("name");
String subIngredient = thing.getString("sub-ingredient");
if(i == 0){
concatProduct = nameTitle + name + subIngredientTitle + subIngredient;
} else {
concatProduct += " " + nameTitle + name + subIngredientTitle + subIngredient;
}
}
textView.setText(concatProduct);
Something like this would let you process the JSONArray and build one string that you could set to one TextView. The formatting is up to you.
ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.