Pass TextView from onCreate to OptionsItemSelected - android-actionbar

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 :-)

Related

setText in NavDrawer Fragment from MainActivity

I keep on getting this null object reference on setText method. Works fine with the navigation header but in the fragments it just keeps on crashing. I've tried making it this way or using Bundle to pass the strings and doesn't seem to be working.
How should I test it or what changes should I make?
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
//NavHeader
private TextView header_name, header_email;
//SessionManager
SessionManager sessionManager;
//maps
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final String FINELOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSELOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private Boolean mLocationPermissionsGranted = false;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
private FusedLocationProviderClient mFusedLocationProviderClient;
private GoogleMap mMap;
String pontopartida, pontochegada;
private EditText ponto_partidaInput, ponto_chegadaInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//GET USER DATA
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
header_name = (TextView) headerView.findViewById(R.id.header_name);
header_email = (TextView) headerView.findViewById(R.id.header_email);
HashMap<String, String> user = sessionManager.getUserDetail();
String mName = user.get(sessionManager.NAME);
String mEmail = user.get(sessionManager.EMAIL);
header_name.setText(mName);
header_email.setText(mEmail);
Log.d("Name: ", mName);
Log.d("Email: ", mEmail);
FragmentManager MyAccfrag = getSupportFragmentManager();
MyAccountFragment fragment = (MyAccountFragment) MyAccfrag.findFragmentById(R.id.nav_myaccount);
fragment.setText(mName, mEmail);
...
public class MyAccountFragment extends Fragment {
private TextView account_name;
private TextView account_email;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_myaccount, container, false);
account_name = (TextView) view.findViewById(R.id.name_accountfrag);
account_email = (TextView) view.findViewById(R.id.email_accountfrag);
return view;
}
public void setText (String Name, String Email){
account_name.setText(Name);
account_email.setText(Email);
}
}

Load data from web service and show in Recycler View inside a FragmentPagerAdapter

I have 3 fragments inside a FragmentPagerAdapter and I want to call a web service and load data asynchronous in a Recycler View .
Everything work correctly and data recevie successfully but Recycler View show nothing at all until I swipe Fragment at least 2 position and after back to that fragment recycler view show data.
what's problem? how can I solve it?
these are my code:
ActivityMain.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
ViewPager pager = (ViewPager) findViewById(R.id.fragmentPagerMain);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
FragmentNavigationDrawer fragNavDrawer = (FragmentNavigationDrawer) getSupportFragmentManager().findFragmentById(R.id. fragment_navigation_drawer);
fragNavDrawer.setUp((DrawerLayout) findViewById(R.id.drawerLayout), toolbar);
MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager() );
pager.setAdapter(adapter);
pager.setCurrentItem(3);
SlidingTabLayout tabs = (SlidingTabLayout) findViewById(R.id.pagerTabLayout);
tabs.setViewPager(pager);
}
FragmentPagerAdapter.java
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentList.getInstance(position);
case 1:
return FragmentList.getInstance(position);
case 2:
return FragmentList.getInstance(position);
default:
return FragmentList.getInstance(position);
}
}
FragmentList.java
public class FragmentList extends Fragment {
private ViewGroup view;
private ArrayList<ModelPurchase> data = new ArrayList<>();
private MyRecyclerPurchaseList adapter;
private RecyclerView recyclerView;
public static Fragment getInstance(int catId) {
FragmentList fragment = new FragmentList();
Bundle bundle = new Bundle();
bundle.putInt("catId", catId);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = (ViewGroup) inflater.inflate(R.layout.fragment_list, container, false);
new HttpRequests().new PurchasedList(new HttpRequests.RequestCompeleteListener() {
#Override
public void onCompeletd(ArrayList<ModelPurchase> arrayList) {
data = arrayList;
adapter.notifyDataSetChanged();
}
}).getList();
recyclerView = (RecyclerView) view.findViewById(R.id.listAll);
adapter = new MyRecyclerPurchaseList(getActivity(), data);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}}
I had approximately the same issue. Setting an adapter to a RecyclerView needs to be done in OnCreateView. So you we need somehow to recall OnCreateView when our data has finished loading.
This can be done by detaching then reattaching the fragment, so your code will look like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = (ViewGroup) inflater.inflate(R.layout.fragment_list, container, false);
// use a boolean to prevent loading data twice...
if ( !dataIsLoaded )
{
new HttpRequests().new PurchasedList(new HttpRequests.RequestCompeleteListener() {
#Override
public void onCompeleted(ArrayList<ModelPurchase> arrayList) {
data = arrayList;
dataIsLoaded = true;
adapter.notifyDataSetChanged();
// Detach then attach the fragment
FragmentTransaction = ft getFragmentManager().beginTransaction();
ft.detach(FragmentList.this);
ft.attach(FragmentList.this);
ft.commit();
}
}).getList();
}
else
{
recyclerView = (RecyclerView) view.findViewById(R.id.listAll);
adapter = new MyRecyclerPurchaseList(getActivity(), data);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
}}

Contact Picker Code

i need some help with a contacts picker class that ive got.
The class retrieves the contacts list and allows me to choose one, but when I go and choose another one, it just replaces the first one.
I want to make a list of contacts in my app and not only one.
Thank you,
Noam
The Code:
public static final int PICK_CONTACT = 1;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
TextView tv = (TextView) findViewById(R.id.txtSelContact);
tv.setText(name + "-" + phoneNumber);
}
break;
}
}
}
}
And here is the on create function:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
final ListView lv = (ListView) findViewById(R.id.ContactListView);
lv.setAdapter(arrayAdapter);
}
This is the layout.xml (for some reason it didn't let me post the code so i linked to an image) :
https://imagizer.imageshack.us/v2/516x255q90/4/igi5.png
Lines 29 - 35:
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
as far as I see you are writing results into the same textview:
//Set
TextView tv = (TextView) findViewById(R.id.txtSelContact);
tv.setText(name + "-" + phoneNumber);
You could specify a Listview in your Layout
<ListView
android:id="#+id/ContactListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
and use an arrayadapter to add your result to this Listview:
public class MainActivity extends Activity {
public static final int PICK_CONTACT = 1;
private ArrayList<String> contactList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
final ListView lv = (ListView) findViewById(R.id.contactListView);
lv.setAdapter(arrayAdapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
arrayAdapter.add(name + "-" + phoneNumber);
arrayAdapter.notifyDataSetChanged();
}
break;
}
}
}
}

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

[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());
}
}

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.