Android Java create dynamic textviews - java

I am getting a json array through my api.
I want to display the data in my view, but I do not know how to generate for example textviews and put the data inside each views. (My wish would be to show the data in something like a html table, but at the moment I am fine to understand how to put the data in dynamic textviews
)
String id = jsonobject.getString("id");
String category = jsonobject.getString("category");
String content = jsonobject.getString("content");
Do hold the correct data.
Following method is in my Async task:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != "error") {
JSONArray jsonArray;
TextView textview = (TextView) findViewById(R.id.jokeContent);
try {
jsonArray = new JSONArray(result);
for(int i=0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String id = jsonobject.getString("id");
String category = jsonobject.getString("category");
String content = jsonobject.getString("content");
}
} catch (Exception e) {
Toasty.error(context, "Catch , test1!", Toast.LENGTH_SHORT, true).show();
}
} else {
Toasty.error(context, "Else , test2!", Toast.LENGTH_SHORT, true).show();
}
}

you can start by adding a table layout to your Layout, next create a row on your layout files something like this should work:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/row">
<TextView
android:id="#+id/ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="20"
android:text="TextView" />
<TextView
android:id="#+id/Category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="20"
android:text="TextView" />
<TextView
android:id="#+id/Content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="20"
android:text="TextView" />
</TableRow>
then you can add the rows and fill them with info like this on your activity by using an inflater
for(int i=0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String id = jsonobject.getString("id");
String category = jsonobject.getString("category");
String content = jsonobject.getString("content");
TableLayout tableLayout = (TableLayout)findViewById(R.id.table);
TableRow tablerow = (TableRow)getLayoutInflater().inflate(R.layout.row, tableLayout,false);
((TextView)tablerow.findViewById(R.id.ID)).setText(id);
((TextView)tablerow.findViewById(R.id.Category)).setText(category);
((TextView)tablerow.findViewById(R.id.Content)).setText(content);
tableLayout.addView(tablerow);
}
hope it helps

If I understood your question correctly you want to create a textView and update it after getting a response of your Asynk task.
The idea is..
Create Activity (e.x. Main Activity), create AsynkTask
Create layout and TextView inside
Find TextView in Activity and not in Asynk task. In your case
TextView textview = (TextView) findViewById(R.id.jokeContent);
Put data to some common resource from AsyncTask and get them in Activity.
E.x. (Kotlin) through interface
interface AsyncResponse {
fun finishProcess(result: String)
}
...
class AsyncExecuter constructor(val asyncResp: AsyncResponse)
...
override fun onPostExecute(result: String) { //AsynkTask
super.onPostExecute(result)
asyncResp.finishProcess(result) //asynkResp is interfase which is put to AsynkTask constructor
}
Activity implements my own AsynkResp interface and calls AsynkTask
override fun onResume() {
super.onResume()
AsyncExecuter(this).execute()
}
And implement method from interface in activity where update TextView
override fun finishProcess(output: String) {
textview?.text = output
}
The main idea is manipulation with UI should be done from Activity and not from parallel threads.

In this example, i have created a list for a prefixed array list. Instead of XML i use java to create dynamic views.
public class MainActivity extends AppCompatActivity { String[] wordlist = new String[] { "Shahi Paneer", "Shahi Thali","Shahi Parantha","Kadai Paneer","Mix Parantha", }; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); ListView list = new ListView(this); list.setBackgroundColor(Color.rgb(240,255,255) ); list.setAdapter(new MyAdapter(this, wordlist)); setContentView(list); } private class MyAdapter extends ArrayAdapter<String> { public MyAdapter(Context context, String[] strings) { super(context, -1, -1, strings); } #RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) #Override public View getView(int position, View convertView, ViewGroup parent) { Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/BLESD___ .ttf"); Typeface rupeeSymbol = Typeface.createFromAsset(getAssets(), "fonts/IndianRupee.ttf"); Typeface maze = Typeface.createFromAsset(getAssets(), "fonts/The Heart Maze Demo.ttf"); Typeface epicselfie = Typeface.createFromAsset(getAssets(), "fonts/My Epic Selfie Demo.ttf"); Typeface novaoval = Typeface.createFromAsset(getAssets(), "fonts/NovaOval.ttf"); LinearLayout listLayout = new LinearLayout(MainActivity.this); listLayout.setLayoutParams(new AbsListView.LayoutParams( AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT)); listLayout.setId(View.generateViewId()); listLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout layout1 = new LinearLayout(MainActivity.this); layout1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); layout1.setOrientation(LinearLayout.HORIZONTAL); listLayout.addView(layout1); ImageView imgView = new ImageView(MainActivity.this); imgView.setImageResource(R.drawable.thali); imgView.setPadding(20,20,20,10); imgView.setAdjustViewBounds(true); layout1.addView(imgView); LinearLayout layout2 = new LinearLayout(MainActivity.this); layout2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); layout2.setOrientation(LinearLayout.HORIZONTAL); listLayout.addView(layout2); TextView listText = new TextView(MainActivity.this); listText.setTextColor(Color.BLACK); listText.setPadding(30,0,0,0); listText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40); listText.setTypeface(maze,maze.BOLD); listText.setId(View.generateViewId()); layout2.addView(listText); LinearLayout cartlayout = new LinearLayout(MainActivity.this); cartlayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); cartlayout.setOrientation(LinearLayout.HORIZONTAL); cartlayout.setPadding(0,0,30,0); cartlayout.setGravity(Gravity.RIGHT); // layout3.setPadding(0,10,0,20); layout2.addView(cartlayout); ImageView addCartView = new ImageView(MainActivity.this); addCartView.setImageResource(R.drawable.add); // addCartView.setPadding(200,0,0,0); cartlayout.addView(addCartView); TextView NOFProd = new TextView(MainActivity.this); NOFProd.setId(View.generateViewId()); NOFProd.setTypeface(rupeeSymbol); NOFProd.setPadding(10,20,10,0); NOFProd.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25); // NOFProd.s NOFProd.setText("0"); cartlayout.addView(NOFProd); ImageView removeCartView = new ImageView(MainActivity.this); removeCartView.setImageResource(R.drawable.remove); // removeCartView.setPadding(20,5,20,0); cartlayout.addView(removeCartView); TextView descText = new TextView(MainActivity.this); descText.setTextColor(Color.DKGRAY); descText.setPadding(30,0,0,0); descText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); descText.setTypeface(epicselfie); descText.setText("Swadist Bhojan"); descText.setId(View.generateViewId()); listLayout.addView(descText); // price and others Textview LinearLayout layout3 = new LinearLayout(MainActivity.this); layout3.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); layout3.setOrientation(LinearLayout.HORIZONTAL); layout3.setPadding(0,10,0,20); listLayout.addView(layout3); TextView pricesymbol = new TextView(MainActivity.this); pricesymbol.setId(View.generateViewId()); pricesymbol.setTypeface(rupeeSymbol); pricesymbol.setPadding(30,10,0,0); pricesymbol.setText("`"); layout3.addView(pricesymbol); TextView priceText = new TextView(MainActivity.this); priceText.setId(View.generateViewId()); priceText.setTypeface(novaoval); priceText.setPadding(10,10,0,0); priceText.setText(": 200"); layout3.addView(priceText); TextView rating = new TextView(MainActivity.this); rating.setId(View.generateViewId()); rating.setPadding(50,0,0,0); rating.setTypeface(novaoval); rating.setText("Rating : 3.5"); layout3.addView(rating); TextView any = new TextView(MainActivity.this); any.setPadding(50,0,0,0); any.setTypeface(novaoval); any.setId(View.generateViewId()); any.setText("anything "); layout3.addView(any); listText.setText(super.getItem(position)); return listLayout; } } }

Related

Error "The specified child already has a parent" after LinearLayout.addView() and then Linearlayout.removeView()

I'm working on a project where I have a parent LinearLayout with id=linear_parent created on activity_main.xml. Inside this parent layout, n numbers of LinearLayouts are created programmatically base on user input at EditText (id=no_of_views_input).
And inside the each of these Linearlayouts, there are more child views (imageView, edit, button) created programmatically.
Suppose a user enters 4 no_of_views_input, the views heirarchy would be something like,
============
linear_parent
linearLayout //position 1
imageView
edit
button
linearLayout //position 2
imageView
edit
button
linearLayout //position 3
imageView
edit
button
linearLayout //position 4
imageView
edit
button
===========
After these layouts and views are created, I want to rearrange the LinearLayouts, base on user input from child id=edit.
Suppose the user enters 1 on edit at LinearLayout position 3 , what I want is, the current LinearLayout at position 3 must be added to position 1 along with its children, and finally remove the old Linearlayout which was at position 3. (would be currently at position 4 if indexes are shifted down).
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linear_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="vertical">
<!-- Views are added here programmatically -->
</LinearLayout>
<EditText
android:id="#+id/no_of_views_input"
android:layout_width="100dp"
android:layout_height="40dp"
android:hint="Number of view to add"/>
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
LinearLayout linear_parent;
Button add_button;
EditText no_of_views_input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linear_parent = findViewById(R.id.linear_parent);
add_button= findViewById(R.id.add_button);
no_of_views_input= findViewById(R.id.no_of_views_input);
no_of_views_input.setInputType(InputType.TYPE_CLASS_NUMBER);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!no_of_views_input.getText().toString().isEmpty()) {
String no_of_views_temp = no_of_views_input.getText().toString();
int no_of_views = Integer.parseInt(no_of_views_temp);
for (int i = 0; i < no_of_views; i++) {
LinearLayout linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams lp_ll = new LinearLayout.LayoutParams(600, 1500);
lp_ll.setMargins(0, 50, 0, 0);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setId(View.generateViewId()); // id = 1, 2, 3, 4, ...
int linearLayoutID = linearLayout.getId();
linearLayout.setLayoutParams(lp_ll);
ImageView imageView = new ImageView(MainActivity.this);
LinearLayout.LayoutParams lp_image = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 800);
imageView.setBackgroundColor(Color.Yellow);
imageView.setLayoutParams(lp_image);
EditText edit = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp_edit = new LinearLayout.LayoutParams(300, ViewGroup.LayoutParams.WRAP_CONTENT);
edit.setBackgroundColor(Color.WHITE);
edit.setInputType(InputType.TYPE_CLASS_NUMBER);
edit.setHint("move to index");
edit.setLayoutParams(lp_edit);
Button button = new Button(MainActivity.this);
LinearLayout.LayoutParams lp_button= new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setBackgroundColor(Color.BLUE);
button.setText("Move");
button.setLayoutParams(lp_button);
linear_parent.addView(linearLayout);
linearLayout.addView(imageView);
linearLayout.addView(edit);
linearLayout.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String indexTarget_temp = edit.getText().toString();
int indexTarget = Integer.parseInt(indexTarget_temp );
int childCount = linear_parent.getChildCount();
int currentLinearLayoutPos = linear_parent.indexOfChild(linearLayout);
try {
linear_parent.addView(linearLayout, indexTarget - 1); //adding current linearLayout to indexTarget
//error occurs this line
linear_parent.removeView(linear_parent.getChildAt(currentLinearLayoutPos + 1)); //removing linearLayout at old index
}
catch(IllegalStateException e) {
e.printStackTrace();
}
}
});
}
}else {
Toast.makeText(MainActivity.this, "Enter index no", Toast.LENGTH_SHORT).show();
}
}
});
}
}
The error I'm getting is
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Any help would be highly appreciated.
Try to remove the child from its parent before adding it as a subview:
try {
if (linearLayout.getParent() != null) {
// Remove child from parent
((ViewGroup) linearLayout.getParent()).removeView(linearLayout)
}
linear_parent.addView(linearLayout, indexTarget - 1);
}
catch(IllegalStateException e) {
e.printStackTrace();
}
However, consider switching to a RecyclerView.
It would simplify your code structure.

Cannot get the text from the edit text widget (android)

I have no clue what I am doing wrong but when I print the text from the edit text (using getText().toString()), in the logcat it is always an empty string. I am wondering if it has to do with that it is being done inside the onClickfunction for the continue button. I'm putting the whole onCreate function because the code inside the onClick function seems to match exactly what countless tutorials have shown.
#Override
protected void onCreate(Bundle savedInstanceState)
{
Button add_test = new Button(this);
Button delete_test = new Button(this);
Button[] barray = new Button[100];
int trans_grey = Color.parseColor("#40000000");
final String[] test_types = new String[] {"Choose...","Terms", "Multiple choice", "Custom"};
final ArrayAdapter<String> type_adapter = new ArrayAdapter<String>(this,R.layout.spinner_item,test_types);
// Preliminary operations and display opening layouts
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout scroll_layout = (LinearLayout)findViewById(R.id.scroll_layout);
LayoutParams scroll_params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
// Add the add a dynamic button
for (int index = 0; index <= 4; index++)
{
barray[index] = new Button(this);
barray[index].setBackgroundColor(trans_grey);
barray[index].setText("Array buttons");
barray[index].setTextColor(Color.parseColor("#CCffffff"));
scroll_layout.addView(barray[index], scroll_params);
}
add_test.setTextColor(Color.parseColor("#CCffffff"));
add_test.setBackgroundColor(trans_grey);
add_test.setText("Add a Test");
scroll_layout.addView(add_test, scroll_params);
add_test.setOnClickListener(new View.OnClickListener()
{#Override
public void onClick(View v)
{
AlertDialog.Builder add_test_builder = new AlertDialog.Builder(TestActivity.this);
final View add_test_view = getLayoutInflater().inflate(R.layout.add_test_menu, null);
Spinner type_spinner = (Spinner) add_test_view.findViewById(R.id.type);
add_test_builder.setView(add_test_view);
final Button continue_button = (Button) add_test_view.findViewById(R.id.continue_button);
AlertDialog dialog = add_test_builder.create();
dialog.show();
dialog.getWindow().setLayout(950,900);
type_spinner.setAdapter(type_adapter);
continue_button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
View add_test_view = getLayoutInflater().
inflate(R.layout.add_test_menu, null);
// The view of the test attribute dialog
EditText test_title = (EditText) add_test_view.
findViewById(R.id.testTitle);
// Test title widget to hold title of test
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title);
}
});
return;
}
});
// Add the delete a test button
delete_test.setTextColor(Color.parseColor("#CCffffff"));
delete_test.setBackgroundColor(trans_grey);
delete_test.setText("Delete a Test");
scroll_layout.addView(delete_test, scroll_params);
return;
}
}
Layout:
<EditText
android:id="#+id/testTitle"
android:maxLines="1"
android:lines="1"
android:inputType="textAutoCorrect"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#00000000"
android:hint="Test Title"/>
Don't inflate the view yiu are assigning to dialog multiple times as you are creating multiple instances of it you are writing to one view but trying to fetch the data from another....Try doing it like this...
AlertDialog.Builder add_test_builder = new AlertDialog.Builder(TestActivity.this);
final View add_test_view = getLayoutInflater().inflate(R.layout.add_test_menu, null);
final EditText test_title = (EditText) add_test_view. findViewById(R.id.testTitle);
continue_button.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title); } });
I think you should define EditText before and outside of your onlick method. Or get string after your onlick method.
IMO you may call editText string outside of Click method like above
final EditText test_title;
continue_button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
View add_test_view = getLayoutInflater().
inflate(R.layout.add_test_menu, null);
// The view of the test attribute dialog
EditText test_title = (EditText) add_test_view.
findViewById(R.id.testTitle);
// Test title widget to hold title of test
}
});
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title);

How can I create dynamic text views according to a selected integer from a spinner?

03-05 11:31:07.042 1897-1897/com.example.project.a D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
03-05 11:31:07.050 1897-1897/com.example.project.a E/AndroidRuntime﹕ FATAL
EXCEPTION: main
Process: com.example.project.a, PID: 1897
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project.a/com.example.project.a.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.removeAllViews()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
// Toast.makeText(getApplicationContext(),"The day qqq"+arg0.getItemAtPosition(arg2).toString(),Toast.LENGTH_LONG).show();
String control2=arg0.getItemAtPosition(arg2).toString();
int noOfBulb= (int) spinner1.getSelectedItem();
final TextView tryText2=(TextView)findViewById(R.id.textView);
tryText2.setText("No"+noOfBulb);
mdynamiclayout = (LinearLayout) findViewById(R.id.dynamiclayout);
mdynamiclayout.removeAllViews();//need to remove the view before it create
for (int i = 0; i < noOfBulb; i++) {//6 is your selected item from spinner it can be any nymber
TextView t = new TextView(MainActivity.this);
t.setText("value" + i);
// t.setTextSize(20);
// t.setTextColor(Color.BLUE);
mdynamiclayout.addView(t);
}
}
public void onNothingSelected(AdapterView<?> arg0){}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SelectBulbs();
rl = (RelativeLayout) findViewById(R.id.rl);
tv1 = new TextView (MainActivity.this);
tv1.setText("Dynamic TextView");
tv1.setTextColor(Color.RED);
tv1.setTextSize(20);
RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams
((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params1.leftMargin=115;
params1.topMargin=120;
rl.addView(tv1);
public class Unit {
private String _bulbNo;
public Unit(String bulbNo) {
_bulbNo = bulbNo;
}
public String getBulbNo(){
return _bulbNo;
}
}
// I created this class
private void addBulbsFans(String bulb)
{
Units.add(new Unit(bulb));
}
//I add this method to MainActivity.java .After this i need to know how to pass the spinner value from a buttonclick event.
If you want to create a dynamic textview in vertical order then create LinearLayout in xml and Orientation as Vertical as like below
<LinearLayout
android:id="#+id/dynamiclayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/registerlayout"
android:layout_below="#+id/registerlayout"
android:layout_marginLeft="16dp"
android:layout_marginTop="34dp"
android:orientation="vertical" >
</LinearLayout>
Then add below line of code in your activity
private LinearLayout mdynamiclayout;
mdynamiclayout = (LinearLayout) findViewById(R.id.dynamiclayout);
mdynamiclayout.removeAllViews();//need to remove the view before it create
for (int i = 0; i < 6; i++) {//6 is your selected item from spinner it can be any nymber
TextView t = new TextView(MainActivity.this);
t.setText("value" + i);
mdynamiclayout.addView(t);
}
Passing one activity to another activity :
Intent intent_value = new Intent(Mainactivity.this,
yoursecondactivity.class);
intent_value.putExtra("key", value);
intent_value.putExtra("key2", value2);
startActivity(intent_value);
Retrieve value:
Intent getValues = getIntent();
String value1 = getValues.getStringExtra("key");
Let me know if you need any help
You can simply convert selected String to integer by following
int value = Integer.valueOf(spiner.getselecteditem);
You use Integer.valueOf(), in your case it would be like that:
String[] bulbs = {"0","1","2","3","4","5"};
Integer[] bulbsConvert = new Integer[6];
//Array to int
for(String item : bulbs){
bulbsConvert.add(Integer.valueOf(item));
}

check EditText value onto ListView android

i am using ListView in main activity and class adapter extends ArrayAdapter with login form only one row.
code adapter like this"
public class AdapterLogin extends ArrayAdapter<ListArrayItem> {
Context mContext;
int layoutResourceId;
ListArrayItem data[] = null;
public AdapterLogin(Context mContext, int layoutResourceId, ListArrayItem[] data) {
super(mContext, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.data = data;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
}
//here i have for login like this
lin_form = new LinearLayout(mContext);
EditText email_input = new EditText(mContext);
Button btn_sign = new Button(mContext);
btn_sign.setOnClickListener(login_btn_clicked);
TextView login_status_message = new TextView(mContext);
lin_form.addView(email_input);
lin_form.addView(btn_sign);
lin_form.addView(login_status_message);
rowitem = (RelativeLayout)convertView.findViewById(R.id.rowitem);
rowitem.addView(lin_form);
return convertView;
}
public OnClickListener login_btn_clicked = new OnClickListener() {
String email_value = email_input.getText().toString();
// i want to see email_value but doesnt show me any thing
login_status_message.setText("email value:"+ email_value);
};
in main activity i have a code like this:
FillFooter fillfooter= new FillFooter();
fillfooter.setFooter(MainActivity.this,"mainactivity");
fillfooter.fillFooter();
public static void gotoLogin(Context context){
Activity activity = (Activity)context;
activity.setTitle("Broonza: Вход");
list = new HashMap<String, String>();
listarraymain[0] = new ListArrayItem(1, list);
AdapterLogin adapter = new AdapterLogin(context, R.layout.row_item, listarraymain);
listviewtmain.clearFocus();
listviewtmain.setAdapter(adapter);
}
in the class fill footer
public class FillFooter {
public void setFooter(Context context,String typeactivity){
this.context = context;
this.activity = (Activity) context;
linaccount = new LinearLayout(context);
linaccount.setOnClickListener(gotologin);
}
public OnClickListener gotologin= new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.gotoLogin(context);
}
};
}
row_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="1dp"
android:paddingBottom="0dp"
android:paddingTop="10dp"
android:id="#+id/rowitem" >
load form login with all fields from adapter to listview work fine, but when clicking button login if email field content text doesn't show that text.
The problem is not in the printed error!, The problem in the printing field email value! OnCLickListener() doesnt work. it will work only if i will add text for email_field onto inside adapter like this! email_input.setText("example#mail.ru")
I think that instead of
if(error !=""){
login_status_message.setText(error);
}
should be this:
if(!error.equals(""){
login_status_message.setText(error);
}
This is basically a string comparsion. If you want to compare a string to a string, you should use equals() instead of !=.
Your problem is that the error value is always null and you can not see the value of email, it is not calling login_status_message.setText("email value:"+ email_value);
Change this
btn_sign.setOnClickListener(login_btn_clicked);
TextView login_status_message = new TextView(mContext);
by this:
TextView login_status_message = new TextView(mContext);
btn_sign.setOnClickListener(login_btn_clicked);
Your is initializing under the getView method and is local to that block;
How you are accessing this field outside the method?
You have created the object local with the method as-
EditText email_input = new EditText(mContext);
TextView login_status_message = new TextView(mContext);
inside the getView method.
You need to put your Listener inside the getView method as
btn_sign.setOnClickListener(new OnClickListener() {
String email_value = email_input.getText().toString();
// i want to see email_value but doesnt show me any thing
login_status_message.setText("email value:"+ email_value);
});
Re-examine the code if you are having another duplicate fields for that.
Thank you for all). after restart eclipse, it work fine.

how add and delete rows to table layout in java programically

I am new in java and android programing. I want to add rows(include some text box) to table layout by code and delete some of them.and finaly get their text box valus.how can i do it?
Here is a simple example to do what you want:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/table"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TableLayout>
Activity:
public class TableLayoutActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table_layout);
final TableLayout tableLayout = (TableLayout) findViewById(R.id.table);
for (int i = 0; i < 5; i++) {
// Creation row
final TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
// Creation textView
final TextView text = new TextView(this);
text.setText("Test" + i);
text.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
// Creation button
final Button button = new Button(this);
button.setText("Delete");
button.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TableRow parent = (TableRow) v.getParent();
tableLayout.removeView(parent);
}
});
tableRow.addView(text);
tableRow.addView(button);
tableLayout.addView(tableRow);
}
}
}
I recently got the same problem. I fixed it like this.
Suppose your TableLayout is called table and als has this id in the xml layout.
<TableLayout
android:id="#+id/table"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
Suppose you have a list of Person objects, this is the way to populate the table:
ArrayList<Person> persons = getPersonList(); // --> suppose getting the list from this function
TableLayout table = (TableLayout) findViewById(R.id.table);
for(Person person : persons) {
TableRow row = new TableRow(this);
TextView tvName = new TextView(this);
TextView tvAge = new TextView(this);
TextView tvMail = new TextView(this);
tvName.setText(person.getName());
tvAge.setText(String.valueOf(person.getAge());
tvMail.setText(person.getMail());
row.addView(tvName);
row.addView(tvAge);
row.addView(tvMail);
table.addView(row);
}
This basically means that each person has its own row. For every property of your person, 1 column is used.
Regards

Categories