I am pretty new with Android and I am learning it by reading a Deitel book. I decided to develop an app with tabs and I am using Fragments (as you can see).
I read on my book/on the internet how to implement an onClick event for a button, but when I try to run the app in my Android phone, it crashes.
Code
public class GamesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_games, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText val1 = (EditText) v.findViewById(R.id.editText1);
EditText val2 = (EditText) v.findViewById(R.id.editText2);
EditText val3 = (EditText) v.findViewById(R.id.editText3);
EditText sol1 = (EditText) v.findViewById(R.id.editText4);
EditText sol2 = (EditText) v.findViewById(R.id.editText5);
//Solve the equation using a method of a class I created
equazioni2grado Equazione = new equazioni2grado();
Equazione.solveEquation(val1.getText().toString(), val2.getText().toString(), val3.getText().toString());
//Show the results
sol1.setText( Equazione.getSol1AsFraction() );
sol2.setText( Equazione.getSol1AsFraction() );
}
});
return view;
}
}
XML
link
I put the XML in a pastebin because it's pretty long. The XML looks like this:
I read that I can define the onClick event in the XML or in the java file, both ways are possible. I am doing it programmatically as you can see.
I can't find where is my mistake. Any idea?
Note: The object Equazione has the method that is:
public void solveEquation(String x, String y, String z) { ... }
EditText val1 = (EditText) v.findViewById(R.id.editText1);
Use view instead of v as below
EditText val1 = (EditText) view.findViewById(R.id.editText1);
try the code below:
public class GamesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_games, container, false);
Button button = (Button) view.findViewById(R.id.button1);
EditText val1 = (EditText) view.findViewById(R.id.editText1);
EditText val2 = (EditText) view.findViewById(R.id.editText2);
EditText val3 = (EditText) view.findViewById(R.id.editText3);
EditText sol1 = (EditText) view.findViewById(R.id.editText4);
EditText sol2 = (EditText) view.findViewById(R.id.editText5);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Solve the equation using a method of a class I created
equazioni2grado Equazione = new equazioni2grado();
Equazione.solveEquation(val1.getText().toString(), val2.getText().toString(), val3.getText().toString());
//Show the results
sol1.setText( Equazione.getSol1AsFraction() );
sol2.setText( Equazione.getSol1AsFraction() );
}
});
return view;
}
}
And can you paste LogCat?
You need to call findViewById on the view that represents the layout you've inflated. In this case, it's the object "view", returned from inflater.inflate().
One way of doing that is declaring view as a final variable and then replacing the calls "v.findViewById..." with "view.findViewById...".
Related
I need the value of inflated editText, I am inflating the design layout which is the child layout and MainActivity is a parent layout.
below is the MainActivity class
public class MainActivity extends AppCompatActivity {
View array[];
String text;
LinearLayout container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edittext1 = (EditText) findViewById(R.id.email);
for (int i = 0; i < 4; i++) {
LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearlayout);
View v = getLayoutInflater().inflate(R.layout.design, myLayout, false);
myLayout.addView(v);
int id = View.generateViewId();
v.setId(id);
EditText edittext = (EditText) v.findViewById(R.id.edittext);
text = edittext.getText().toString();
}
edittext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplication(), "" + text, Toast.LENGTH_SHORT).show();
}
});
}
}
Here is total code of store object and retrieval,
read all comments please,
public class MainActivity extends AppCompatActivity {
View array[];
String text;
LinearLayout container;
// list of edittext
List<EditText> edtlist = new ArrayList()<EditText>;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edittext1 = (EditText) findViewById(R.id.email);
for (int i = 0; i < 4; i++) {
LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearlayout);
View v = getLayoutInflater().inflate(R.layout.design, myLayout, false);
myLayout.addView(v);
int id = View.generateViewId();
v.setId(id);
EditText edittext = (EditText) v.findViewById(R.id.edittext);
// store object in list
edtlist.add(edittext);
text = edittext.getText().toString();
}
edittext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplication(), "" + text, Toast.LENGTH_SHORT).show();
}
});
// call this whenever you want in any event
// here 0 is first edittext
// you can get all text value using for loop
// list.get(0).getText().toString();
}
}
You are looking for something like ,I'm not sure about it maybe it works maybe it wont.! it just a rough concept based code havnt Implemented yet.!
List<EditText> edtxtList;
List<String> edtxtStrList;
for (int i = 0; i < 4; i++) {
LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearlayout);
View v = getLayoutInflater().inflate(R.layout.design, myLayout, false);
myLayout.addView(v);
int id = View.generateViewId();
v.setId(id);
EditText edittext = (EditText) v.findViewById(R.id.edittext);
text = edittext.getText().toString();
edtxtList.add(edittext);// try something like this.!
}
Then use Foreach loop on EditText;
for (EditText edText : edtxtList) {
if(!edText.getText().trim()=null){
edtxtStrList.add(edText.getText().trim());
}
}
I havnt tried It yet but maybe this ruff concept may helps you.!
Maybe this Method helps You.!
ArrayList<EditText> myEditTextList = new ArrayList<EditText>();
for( int i = 0; i < myLayout.getChildCount(); i++ )
if( myLayout.getChildAt( i ) instanceof EditText )
myEditTextList.add( (EditText) myLayout.getChildAt( i ) );
In Above code mLayout is your layout.!
<LinearLayout android:id="#+id/myLinearLayout" >
//Here is where your EditTexts would be declared
</LinearLayout>
i want when click on User info list view item (fill with adapter) , get user_id,
i use this code in main activity :
// long click on listview items
LIST_USER.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Clicked item id", " "+ id);
// Intent intent = new Intent(getBaseContext(), UpdateActivity.class);
// intent.putExtra("EXTRA_ID", id);
// startActivity(intent);
return true;
}
});
yet no problem !
but when send user_id to update activity database has stopped !!
use this code in update activity :
public class UpdateActivity extends AppCompatActivity {
private DatabaseHelper DB_HELPER;
private TextView TXT_VIEW;
private EditText EDT_NAME;
private EditText EDT_AGE;
private EditText EDT_GENDER;
private EditText EDT_PASS;
private EditText EDT_DESC;
private EditText EDT_PIC;
private Button BTN_UPDATE;
private Button BTN_DELETE;
private String STR_ID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
TXT_VIEW = (TextView) findViewById(R.id.textView);
EDT_NAME = (EditText) findViewById(R.id.editText);
EDT_AGE = (EditText) findViewById(R.id.editText2);
EDT_GENDER = (EditText) findViewById(R.id.editText3);
EDT_PASS = (EditText) findViewById(R.id.editText4);
EDT_DESC = (EditText) findViewById(R.id.editText5);
EDT_PIC = (EditText) findViewById(R.id.editText6);
BTN_UPDATE = (Button) findViewById(R.id.button) ;
BTN_DELETE = (Button) findViewById(R.id.button2);
DB_HELPER = new DatabaseHelper(this);
STR_ID = getIntent().getStringExtra("EXTRA_ID");
TXT_VIEW.setText(STR_ID);
display user_id in log info :
thank's
The starting problem is in the types, you are passing a long and reading it as a string, the cast exception is raised in the onCreate and resulting in the crash. This should make it work:
private long STR_ID;
//...
STR_ID = getIntent().getLongExtra("EXTRA_ID");
TXT_VIEW.setText(String.valueOf(STR_ID));
In this adapter class, I am trying to read user-entered EditText values upon button click. Both EditText and button are inside a ListView item. What is the best way to read that value? The way I have tried below did not capture the correct value from the EditText field.
#Override
public View getView(final int position, View convertView, final ViewGroup parent)
{
box = null;
db = new database(getContext());
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, null);
box = new container();
box.X = (TextView) convertView.findViewById(R.id.manage_X);
box.Y = (TextView) convertView.findViewById(R.id.manage_Y);
box.Z = (TextView) convertView.findViewById(R.id.manage_Z);
box.button = (Button) convertView.findViewById(R.id.manage_button);
convertView.setTag(box);
}
else
{
box = (container) convertView.getTag();
}
box.X.setText( getItem(position).getX() );
box.Y.setText( String.valueOf(getItem(position).getY()) );
box.button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
View view = View.inflate( getContext(), R.layout.activity_manage, null );
string_is = (EditText) view.findViewById(R.id.manage_Z);
value_is = new Integer( string_is.getText().toString() );
// In my ListView, I have an item with 1 EditText and a button.
// User can enter a value for Z, which is EditText.
// I want to read that value upon button click and do things with it.
// My above method does not capture the correct Z value.
});
return convertView;
}
public class container
{
TextView X;
TextView Y;
TextView Z;
Button button;
}
Try implementing editText.addOnTextChangedListener() just like you set the OnClickListener for your button. On every text changed, store the changed string in some string variable and access the variable when you click the button.
You should not reinflate you view again, this will create a new view and your findViewById will return a new View.
Your code with the correction:
box.button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
string_is = (EditText) box.findViewById(R.id.manage_Z);
value_is = new Integer( string_is.getText().toString() );
}
});
box.button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
string_is = (EditText)box.findViewById(R.id.manage_Z);
value_is = new Integer( string_is.getText().toString() );
}
});
Above worked. But I ran into a strange issue. I can only read the editText value of the 2nd listView item. I have several items in the list and when I click the other buttons, they give the following error message:
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
E/RichInputConnection: Unable to connect to the editor to retrieve text.
D/RichInputConnection: Will try to retrieve text later.
I want to make an app with a long list of strings in a string-array.
What I want to do is have a button la shows a random string when the button is clicked.
Could someone help please.
Thanks
Here is my code :
public class PagesFragment extends Fragment {
public PagesFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/pagefonts.ttf");
txt.setTypeface(font);
TextView tv = (TextView) rootView.findViewById(R.id.jamais);
Button btn = (Button)rootView.findViewById(R.id.next);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String[] myString = getResources().getStringArray(R.array.je_nai_jamais);
tv.setText(myString[rgenerator.nextInt(myString.length)]);
}
});
return rootView;
}
}
I am getting errous here
tv.setText(myString[rgenerator.nextInt(myString.length)]);
This will do it:
public void onClick(View v) {
int i = Math.floor(Math.random() * strings.length);
((Button) v).setText(strings[i]);
}
where strings is your array of strings.
First Generate A Random with in a range of 0 to length of your String . And Then Corresponding to random number Select String element.
Random rnd = new Random();
int myValue = r.nextInt(max-offset)+offset;
yourTextView.setText(yourStringArray[myValue]);
If you want to get the string array from resources you want to do
String[] args = getResources().getStringArray(R.array.yourarray'sname);
Button button = (Button)findViewById(yourbutton'sid);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int number = Math.ceil(Math.random() * args.length);
TextView tv = (TextView)findViewById(yourtextview'sid);
tv.setText(args[number]);
});
Well thanks but none of your codes worked for me so I try around and this one worked for me.
See :
Button next;
public FragmentJeNaiJamais(){}
Random rgenerator = new Random();
Vibrator myVibrator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jamais, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/pagefonts.ttf");
txt.setTypeface(font);
myVibrator = (Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
final TextView iv = (TextView) rootView.findViewById(R.id.jamais);
next = (Button)rootView.findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
myVibrator.vibrate(70);
String[] args = getResources().getStringArray(R.array.je_nai_jamais);
iv.setText(args[new Random().nextInt(args.length)]);
Typeface fonts = Typeface.createFromAsset(getActivity().getAssets(), "fonts/artbrush.ttf");
iv.setTypeface(fonts);
}
});
return rootView;`
}
}
It may be helpful for some one
I am adding programatically and dynamically some elements (buttons and text views) with android. I also need to set the setOnClickListener event for each of these buttons and from that event execute some action on the click of button:
do
{
EditText txt1 = new EditText(this);
EditText txt2 = new EditText(this);
Button showtxt = new Button(this);
linearLayout.addView(showtxt );
linearLayout.addView(txt1);
linearLayout.addView(txt2);
showtxt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String aaa= txt1 .getText().toString();//HOW TO ACCESS txt1 and txt2 from here
String bbb= txt2 .getText().toString();
}
}
}
while(somecondition)
I am almost new to android. How can I access to txt1 and txt2 in the click callback function?
You need to make the define the variables where they will have class wide scope:
public class Example extends Activity {
EditText txt1;
EditText txt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
txt1 = new EditText(this);
txt2 = new EditText(this);
...
Now your onClick function will be able to see txt1 and txt2.
Alternatively
Since you appear to be creating a lot of txt1 and txt2 in one LinearLayout, you can pass your Button a reference to its EditTexts:
do {
...
// EditText[] array = { txt1, txt2 };
// is the short version of
EditText[] array = new EditText[2];
array[0] = txt1;
array[1] = txt2;
showtxt.setTag(array);
showtxt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText[] array = (EditText[]) v.getTag();
String aaa = array[0].getText().toString();
String bbb = array[1].getText().toString();
Log.v("Example", aaa + " " + bbb);
}
});
} while(some condition)
This may not be not ideal, however without any further context I cannot guess your ultimate goal. Hope that helps!
Last Suggestion
If we call the Button and two EditTexts a row, you could store each row in a ViewGroup or View of its own. Say you wanted to have background colors for each row:
View row = new View(this); // or this could be another LinearLayout
row.setBackgroundColor(0x0000ff);
// Create and add the Button and EditTexts to row, as in row.addView(showtxt), etc
...
linearLayout.addView(row);
showtxt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View row = v.getParent()
String aaa = ((EditText) row.getChildAt(1)).getText().toString();
String bbb = ((EditText) row.getChildAt(2)).getText().toString();
Log.v("Example", aaa + " " + bbb);
}
});