On every button click data is added to listview but in an unexpected manner . Data is repeated in the listview - dot42

[Activity]
public class MainActivity : Activity
{
public string[] items = new string[100]; // string to store data from editText
int i =0;
ArrayAdapter<string > adapter;
protected override void OnCreate(Bundle savedInstance)
{
base.OnCreate(savedInstance);
SetContentView(R.Layouts.MainLayout);
var btn1= FindViewById <Button> (R.Ids.btn1);
btn1.Click += AddItem; // calls a function on button click to add data to listview
}
public void AddItem(object sender,EventArgs eventargs)
{
try
{
var et1 = FindViewById <EditText>(R.Ids.et1);
items[i] = et1.Text.ToString();
i++;
view(); //to add data to listview
}
catch(Exception ex)
{
error(ex.ToString());
}
}
public void view ()
{
adapter = new ArrayAdapter<string>(GetApplicationContext(),Android.R.Layout.Simple_list_item_1,items);
ListView listview = FindViewById<ListView>(R.Ids.listview1);
listview.SetAdapter(adapter);
listview.SetTextFilterEnabled(true);
}
}

You should not call view() from AddItem because all code in view is initialization code. Rename it initList or so and call it from OnCreate.
You also don't need items (or i). Just add the string to adapter.
-- EDIT
[Activity]
public class MainActivity : Activity
{
private ArrayAdapter<string> adapter;
protected override void OnCreate(Bundle savedInstance)
{
base.OnCreate(savedInstance);
SetContentView(R.Layouts.MainLayout);
ListView list = FindViewById<ListView>(R.Ids.list);
adapter = new ArrayAdapter<string>(this, Android.R.Layout.Simple_list_item_1);
list.SetAdapter(adapter);
Button button = FindViewById<Button>(R.Ids.button);
button.Click += button_Click;
}
void button_Click(object sender, EventArgs e)
{
EditText text = FindViewById<EditText>(R.Ids.text);
adapter.Add(text.Text.ToString());
}
}

Related

ActionBar back button crash my app

I have problem with my school project when I want to back to my CurentCourseActivity using back button form action bar I have NE
Attempt to invoke virtual method 'java.util.List `com.example.pingu.mylanguages.Language.getList()' on a null object reference at
com.example.pingu.mylanguages.CurentCourseActivity.onCreate(CurentCourseActivity.java:37)`
While I use normal back button problem is not appear.
When we choose Lesson from GridView that makes a new activity. When we choose the back button from ActionBar then I have NE.
CourentCourseActivity:
public class CurentCourseActivity extends AppCompatActivity {
private Language language;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("s","onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_curent_course);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState!=null){
language = (Language) savedInstanceState.getSerializable("Lang");
Log.d("xx","Coś ma");
}
if (getIntent().getExtras() != null) {
language = (Language) getIntent().getSerializableExtra("Lang"); //Obtaining data
}
GridView grid = (GridView) findViewById(R.id.grid);
CurrentCourseAdapter adapter = new CurrentCourseAdapter(this, R.layout.grid_item_curent_course, language.getList());
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(CurentCourseActivity.this,LessonActivity.class);
intent.putExtra("Lesson",(Lesson)language.getList().get(i));
startActivity(intent);
}
});
getSupportActionBar().setTitle(language.getName());
}
}
LessonActivity:
public class LessonActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(getIntent().getExtras()!=null){
Lesson lesson = (Lesson) getIntent().getSerializableExtra("Lesson");
getSupportActionBar().setTitle(lesson.getNamel());
}
}
}
The answer is simplest then I expect. So I need to overide this button and do it as normal back button because ActrionBar back button destroy parent activity.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}

Pass TextView from onCreate to OptionsItemSelected

I'm trying to save to a database using the code below.
Logcat shows values as empty (client, email, address, balance).
It seems the TextViews are not being passed into the OnOptionsItemSelected method. Any idea of how I can pass the TextViews from OnCreate method to OnOptionsItemSelected?
public class NewClient extends Activity {
private ActionBar actionBar;
//private DatabaseHandler dbHelper;
static SimpleCursorAdapter dataAdapter;
private TextView client_name;
TextView client_code;
TextView email;
TextView addressline1;
TextView addressline2;
TextView balance;
ClientsFragment client = new ClientsFragment();
//String carried_code;
//String carried_name;
DatabaseHandler db;
static Cursor cursor;
private TextView ObtainAdd;
private String ObtainAdd1;
private String ObtainAdd2;
public static TextView textViewC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_client);
db = new DatabaseHandler(this.getApplicationContext());
actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
// dbHelper.open();
// Get the layout inflater
client_code = (TextView)findViewById(R.id.code_field);
//set
//get the Text-view for
client_name = (TextView)findViewById(R.id.client_name_field);
email = (TextView)findViewById(R.id.invoice_email_add_field);
addressline1 = (TextView)findViewById(R.id.contact_info_field);
balance = (TextView)findViewById(R.id.balance_field);
//Generate ListView from SQLite Database
// displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.client_activity_actions, menu);
final View menuItemView = findViewById(R.id.action_save);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_save:
openSave();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSave() {
String Updated_Name = client_name.getText().toString();
// TextView prod_price = (TextView) newProd.findViewById(R.id.price_text);
String Updated_code = client_code.getText().toString();
String Updated_email = email.getText().toString();
String Updated_add1 = addressline1.getText().toString();
String Updated_add2 = "add2";// addressline2.getText().toString();
String Updated_balance = balance.getText().toString();
//get double value of code
//updating products
// product.setID(position);
client.setClientName(Updated_Name);
client.setCode(Updated_code);
client.setEmail(Updated_email);
client.setAddressl1(Updated_add1);
client.setAddressl2(Updated_add2);
client.setBalance(Updated_balance);
//update database
// db.updateProduct(product);
db.addClient(client);
// db.close();
// cursor.close();
//cursor = db.getAllProducts();
displayListView();
//dataAdapter = new SimpleCursorAdapter(this, R.layout.list_entry, cursor, columns, to, 0);
//dataAdapter.swapCursor(NewClient.cursor);
//startActivity(new_client_intent);
}
private void displayListView() {
cursor = db.getAllClients();
}
}
I fixed it by removing the Inflater for the textView out of the onCreate method. Now it works perfectly :-)

Populating a spinner used in more than two activities

I have an action bar spinner and two Activities in my app. The spinner, which is populated from a database, needs to be visible in both my activities. How should I generate it without duplicating my code? Should I create a static method or something else?
private NotesDbAdapter mDbHelper;
private List<String> listUniqueCat;
int selectedPos;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joke_details);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
//this method returns list of strings from a database
listUniqueCat = mDbHelper.getUniqueCategories();
// create an array adapter to popluate dropdown list
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, listUniqueCat);
// enable dropdown list naaavigation in action bar
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// defining navigation listiner
ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId)
{
selectedPos = getActionBar().getSelectedNavigationIndex();
Toast.makeText(getBaseContext(), "selected index is "+ selectedPos ,
Toast.LENGTH_LONG).show();
return false;
}
};
// setting dropdown items and item navigation listener for action bar
getActionBar().setListNavigationCallbacks(adapter, navigationListener);
}
I think you need to create one BaseActivity with tabs like
abstract public class BaseActivity extends FragmentActivity {
}
and all other activities extends BaseActivity
small example for you
BaseActivity.java
abstract public class BaseActivity extends Activity implements TabListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
ActionBar actionBar = getActionBar();
// add tabs to actionbar
actionBar.addTab(actionBar.newTab().setText("TAB 1")
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("TAB 2")
.setTabListener(this));
}
}
FirstActivity.java
public class FirstActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(getApplicationContext(),
tab.getText() + " selected in FirstActivity",
Toast.LENGTH_SHORT).show();
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
SecondActivity.java
public class SecondActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(getApplicationContext(),
tab.getText() + " selected in SectondActivity",
Toast.LENGTH_SHORT).show();
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}

How to refresh item in a popup menu?

i have a popup menu (that comes out when the user uses right click on specified elements), wich items are readed from a list.
I want that when an item is selected, that item is disabled in the popupMenu (then if some action happen it will return enabled).
I have implemented the popupMenu, but i cannot implement this enable/disable JMenuItem element. Anyone can help me? Thanks
class PopupTriggerListener extends MouseAdapter {
public void mousePressed(MouseEvent ev) {
if (ev.isPopupTrigger()) {
menu.show(ev.getComponent(), ev.getX(), ev.getY());
x = ev.getX();
y = ev.getY();
}
}
public void mouseReleased(MouseEvent ev) {
if (ev.isPopupTrigger()) {
menu.show(ev.getComponent(), ev.getX(), ev.getY());
x = ev.getX();
y = ev.getY();
}
}
public void mouseClicked(MouseEvent ev) {
}
}
}
JLabel label = new MyLabel("right-click");
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuItem item = new JMenuItem("Test1");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Menu item Test1");
JLabel newLabel = new JLabel("test");
label.add(newLabel);
newLabel.setBounds(x, y, 40, 10);
}
});
menu.add(item);
item = new JMenuItem("Test2");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Menu item Test2");
}
});
menu.add(item);
getContentPane().add(label);
pack();
setSize(300, 100);
}
public static void main(String[] args) {
new Test().setVisible(true);
}
The way this is mostly done is using Actions. Actions are extensions of the ActionListener interface. You can set the Action of, for example, a JMenuItem and in the Action you can set enabled to false. This will automatically disable the JMenuItem. Alternately you can enable it by setting enabled to true on the Action.
Here is the Action API #Oracle: Action API JAVA
And here is a discourse on how to use Actions: How to use Actions JAVA

how to refresh the linear layout view after deleting an element

I have a simple app, in one activity I take name and date of birth. I store it in the database. and in the main activity I have linearlayout which will show all the names.
When I click on any of the name in the main activity, it should delete that name from the database and also refresh the view.
I am able to delete the entry from database, but my linear layout view is not being updated. Can some one pls help.
public class child extends Activity {
private Intent intent;
private LinearLayout layout;
private LayoutInflater linflater;
private int i =0;
private Cursor cr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child);
layout = (LinearLayout)findViewById(R.id.layout);
Button addBtn = (Button)findViewById(R.id.AddButton);
Button remBtn = (Button)findViewById(R.id.RemoveButton);
intent = new Intent(this,login.class);
layout = (LinearLayout) findViewById(R.id.mylayout1);
linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Check the database if there are any entries available. If available, then
//list them on the main screen
final myDBAdapter mydb = new myDBAdapter(getApplicationContext());
mydb.open();
cr = mydb.GetMyData();
if(cr.getCount()>0)
{
cr.moveToFirst();
for (int i=0;i<cr.getCount();i++)
{
cr.moveToPosition(i);
buildList(cr.getString(1),cr.getString(2));
}
}
//Start the login activity which will return the newly added baby name
addBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(intent, 1001);
}
});
//Remove all the entries from Database
remBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(cr.getCount()>0)
{
cr.moveToFirst();
for (int i=0;i<cr.getCount();i++)
{
Toast.makeText(getApplicationContext(), cr.getString(1),
Toast.LENGTH_LONG).show();
mydb.RemoveEntry(cr.getString(1));
cr.moveToPosition(i);
}
}
}
});
mydb.close();
}
private void buildList(final String bname,String bsex)
{
final View customView = linflater.inflate(R.layout.child_view,
null);
TextView tv = (TextView) customView.findViewById(R.id.TextView01);
//tv.setId(i);
tv.setText(bname);
tv.setTextColor(getResources().getColor(R.color.black));
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDBAdapter mydb = new myDBAdapter(getApplicationContext());
mydb.open();
if (mydb.RemoveEntry(bname)>0)
{
Toast.makeText(getApplicationContext(), "Row deleted",
Toast.LENGTH_LONG).show();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
WHAT IS REQUIRED HERE TO UPDATE THE VIEW???
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
Toast.makeText(getApplicationContext(), "Row not deleted",
Toast.LENGTH_LONG).show();
}
}
});
layout.addView(customView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1001)
{
if(resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
buildList(extras.getString("bname"),extras.getString("bsex"));
}
}
}
}
Hmm I'm also trying to get this to work, Have you tried looking at maybe refreshing the LinearLayout every say 5 seconds using a game loop? This may prove to be useful as it helped me with my problem http://aubykhan.wordpress.com/2010/04/25/android-game-programming-the-game-loop/
You may also be able to call onCreate(Bundle) function again while this is a terrible terrible way to do this it will work.