How to retrieve editText1 in DialogFragment using view from xml-resourcefile - android-dialogfragment

How to retrieve editText1 in this DialogFragment? It exists in vraag_banen.xml but getView() is null.
The dialog shows fine, also no compilation errors, however I cannot figure out how to write the eventhandler for the PositiveButton, using a custom view from an xml resourcefile.
package mypackage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class VraagBanenDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.vraag_banen, null))
// Add action buttons
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Activity pa = getActivity().getParent(); //-> TabsMenu
Context bc = getActivity().getBaseContext(); //-> ContextImpl
View vi = getView(); //-> null
Class<? extends OnClickListener> cl = this.getClass(); //-> Class (nl.computerhuys.tabnavui.VraagBanenDialogFragment$1)
String acn = getActivity().getClass().getName(); //-> nl.computerhuys.tabnavui.Spel
String cn = getClass().getName(); //-> nl.computerhuys.tabnavui.VraagBanenDialogFragment$1
OnClickListener t = this; //-> VraagBanenDialogFragment$1
EditText editText1 = (EditText) getView().findViewById(R.id.editText1);
EditText editText2 = (EditText) getView().findViewById(R.id.editText2);
int baan1 = Integer.valueOf(editText1.getText().toString());
int baan2 = Integer.valueOf(editText2.getText().toString());
InitSpel.addBaanNummer(baan1);
InitSpel.addBaanNummer(baan2);
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
VraagBanenDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}

found a way: name the anonymous view:
View v = inflater.inflate(R.layout.vraag_banen, null)
and then use v to refer to the view, instead of getView():
EditText editText1 = (EditText) v.findViewById(R.id.editText1).
Etc. That works.

Related

How to save the current state of switches in Android Studio?

I know very little about programming. I downloaded Android Studio and started tinkering with it. I tried to make the app that they put on the tutorial and it worked. However I tried to add more functionality to it and I've failed so far. Excuse me if you see unnecessary junk on my code, I'm just kinda trying everything at first and I do feel a little misguided.
Anyways, onto the question. I have a Switch (id:toggle_text) with an OnClick action (change_font). When the switch is toggled it should change the font size of a different activity through intent1. Currently not only does it not send the font size variable (the variable keeps the default value you put on getIntExtra), but now that I tried to add the ability to save the current state it just shows errors. Here's the code:
package com.example.myfirstapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;
import android.widget.TextView;
import static com.example.myfirstapp.R.id.toggle_text;
import static com.example.myfirstapp.R.string.change_font;
public class ShowAnOption extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_an_option);
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyz", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}
public void change_font(View v) {
int fssize;
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
fssize=20;
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
fssize=40;
}
Intent intent1 = new Intent (getBaseContext(), DisplayMessageActivity.class);
intent1.putExtra("Font_Size", fssize);
}
}
It says "cannot resolve symbol toggle" on toggle.setChecked() and the if statement. What can I do to fix this? Also, why does it not get sent to the other activity? Here's the code on the other activity:
package com.example.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
Intent intent1 = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int Font_Size = intent1.getIntExtra("Font_Size",50);
TextView textView = new TextView(this);
textView.setTextSize(Font_Size);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
Thanks and sorry for the long read. If there's anything else that needs to be known let me know and I'll gladly show.
We did not try to change the font size but here is how to use the switch widget.
Our design is two activities MainActivity and SwitchActivity we changed a CheckBox from unchecked to checked The switch is on the MainActivity code below
setOnCheckedChangeListener();
private void setOnCheckedChangeListener() {
swAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(MainActivity.this, "Switch On", Toast.LENGTH_SHORT).show();
Intent intentSP = new Intent(MainActivity.this, SwitchActivity.class );
Bundle extras = new Bundle();
extras.putString("FONT","true" );
intentSP.putExtras(extras);
startActivity( intentSP );
} else {
Toast.makeText(MainActivity.this, "Switch Off", Toast.LENGTH_SHORT).show();
}
}
});
}
Now in the SwitchAcvity we capture the value from the intent and fire the method
doWhat()
Intent intentSP = getIntent();
Bundle bundle = intentSP.getExtras();
tORf = bundle.getString("FONT");
doWhat(null);
And here is the doWhat method
public void doWhat(View view){
if(tORf.equals("true")){
chkBoxOne.setChecked(true);
}else {
Toast.makeText( SwitchActivity.this, "NOT TRUE", Toast.LENGTH_LONG ).show();
}
}

JavaFX Custom Table Cell - Strange behavior

I have this code:
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Callback;
public class Example extends Application
{
#Override
public void start(Stage stage) throws Exception
{
TableView<Color> table = new TableView<>();
ObservableList<Color> colors = FXCollections.observableArrayList();
table.setItems(colors);
table.setEditable(true);
TableColumn<Color, Color> column = new TableColumn<>();
column.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue()));
column.setCellFactory(param ->
{
ObservableList<Color> menuColors = FXCollections.observableArrayList();
menuColors.addAll(Color.RED, Color.GREEN, Color.BLUE);
return new ComboBoxTableCell(menuColors);
});
Button button = new Button("Add row");
button.setOnAction(event -> colors.add(Color.BLACK));
VBox box = new VBox(table, button);
table.getColumns().add(column);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
stage.setScene(new Scene(box));
stage.show();
}
public class ComboBoxTableCell extends TableCell<Color, Color>
{
private ComboBox<Color> comboBox;
public ComboBoxTableCell(ObservableList<Color> colors)
{
comboBox = createFancyComboBox(colors);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
public void updateItem(Color item, boolean empty)
{
if (item == null || empty)
setGraphic(null);
else
setGraphic(comboBox);
}
}
private ComboBox<Color> createFancyComboBox(ObservableList<Color> colors)
{
ComboBox<Color> comboBox = new ComboBox<>(colors);
Callback<ListView<Color>, ListCell<Color>> factory = list -> new ColorSquare();
comboBox.setCellFactory(factory);
comboBox.setButtonCell(factory.call(null));
comboBox.setValue(colors.get(0));
return comboBox;
}
public static class ColorSquare extends ListCell<Color>
{
#Override
public void updateItem(Color item, boolean empty)
{
super.updateItem(item, empty);
Rectangle rect = new Rectangle(18, 18);
if (item != null)
{
rect.setFill(item);
setGraphic(rect);
}
}
}
public static void main(String[] args)
{
launch(args);
}
}
If I try to run it, click on the button, change the color to for Green and click 8 times on the button, the green square will disapper.
How do I fix this and why is it happening? The real code isn't much different from this, this is the only problem I have. Thank you.
I have noticed that at times the rerendering of a table cell doesn't work right after a certain number of attempts. I had one where I was updating a remaining amount when the user entered a value in another cell.
To solve this I would toggle visibility of the column.
column.setVisible(false);
column.setVisible(true);
I would do this immediately after the action that changed the value in the cell.
It's a hack but seems to work.

ActionBarActivity with fragment and Tab Bar how to implement it

As you see my Code, it dont have error when run debug, I put the tabhost into my fragment, but when app run. It dont show the tabhost
package com.example.phamxuanson.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mTitle = getTitle();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Please see my piuctures
i.imgur.com/AuPA4GO.png
i.imgur.com/Vlrxuhz.png
i.imgur.com/or8m6Mj.png
Why wasn’t tabhost shown?

The operator - under defined for the arguement type(s) EditText, int

Im trying to create an activity which adds name, age, and maxhr to sqlite and will be displayed in a listview in Eclipse. name and age is an input text. Maxhr is age(input text) minus 220. But im getting "The operator - under defined for the arguement type(s) EditText, int" error. I can't seem to find the answer for this error. Does anyone know how to fix it?
package com.heartrate.monitoring.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.heartratemonitoringapp.R;
import com.heartrate.monitoring.dao.UserDAO;
import com.heartrate.monitoring.model.User;
public class AddUserActivity extends Activity implements OnClickListener {
public static final String TAG = "AddUserActivity";
private EditText mTxtName;
private EditText mTxtAge;
private Button mBtnAdd;
private UserDAO mUserDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
getActionBar().setDisplayHomeAsUpEnabled(true);
initViews();
this.mUserDao = new UserDAO(this);
}
private void initViews() {
this.mTxtName = (EditText) findViewById(R.id.txt_name);
this.mTxtAge = (EditText) findViewById(R.id.txt_age);
this.mBtnAdd = (Button) findViewById(R.id.btn_add);
this.mBtnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Editable name = mTxtName.getText();
Editable age = mTxtAge.getText();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)){
// add the user to database
double mhr;
double maxhr;
mhr = Double.parseDouble(mTxtAge.getText().toString());;
maxhr = mhr - 220;
User createdUser = mUserDao.createUser(
name.toString(), age.toString(),
maxhr.toString());
Log.d(TAG, "added user : "+ createdUser.getName());
Intent intent = new Intent();
intent.putExtra(ListUserActivity.EXTRA_ADDED_USER, createdUser);
setResult(RESULT_OK, intent);
Toast.makeText(this, R.string.user_created_successfully, Toast.LENGTH_LONG).show();
finish();
}
else {
Toast.makeText(this, R.string.empty_fields_message, Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mUserDao.close();
}
}
Remove the extra ; on this line: mhr = Double.parseDouble(mTxtAge.getText().toString());;

Search in ListView android

I'm using the following class to so search in listView of countries
package com.androidhive.androidlistviewwithsearch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity {
private ListView lv;
SimpleCursorAdapter cursorAdapter;
ArrayAdapter<String> adapter;
EditText inputSearch;
private SQLiteAdapter mySQLiteAdapter;
ArrayList<HashMap<String, String>> productList;
public static final String COUNTRY_NAME = "COUNTRY_NAME";
String[] countryName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
int isEmpty = mySQLiteAdapter.isEmpty();
if (isEmpty == 0) {
mySQLiteAdapter.insert("Afghanistan", "102", "119", "119");
mySQLiteAdapter.insert("Albania", "127", "128", "129");
mySQLiteAdapter.insert("Algeria", "14", "14", "17");
mySQLiteAdapter.insert("American Samoa", "911", "911", "911");
mySQLiteAdapter.insert("Andorra", "118", "118", "110");
mySQLiteAdapter.insert("Angola", "118", "118", "110");
mySQLiteAdapter.insert("Panama", "911", "911", "911");
mySQLiteAdapter.insert("Papua New Guinea /Port Moresby", "", "110", "000");
mySQLiteAdapter.insert("Yemen", "191", "191", "194");
mySQLiteAdapter.insert("Zambia", "991/112", "993/112", "999/112");
mySQLiteAdapter.insert("Zimbabwe", "994/999", "993/999", "995/999");
}
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
List<String> list = new ArrayList<String>();
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
String countries = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.COUNTRIES_CONTENT)).toString().trim();
System.out.println("countries: " + countries);
list.add(countries);
cursor.moveToNext();
}
}
countryName = new String[list.size()];
countryName = list.toArray(countryName);
mySQLiteAdapter.close();
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, countryName);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
Intent intent ;
Bundle b = new Bundle();
b.putString(COUNTRY_NAME, countryName[position]);
intent = new Intent(getApplicationContext(), CountryNumbers.class);
intent.putExtras(b);
startActivity(intent);
finish();
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
this code works well and do a search and it also do the setOnItemClickListener that opens the Activity that contains info about the selected country.
But when I do search and I wrote "E" for example, I found the list changed and gets countries that starts with "E" but When I press for example the second country that gets from search, it opens the country with second index in "countryName" array.
How can I solve this issue and get the info of the selected country from the search?
Hope anyone got my mean.
Thanks in advance.
I solved it by replacing this line
b.putString(COUNTRY_NAME, countryName[position]);
by this line
b.putString(COUNTRY_NAME, adapter.getItem(position));