setText in NavDrawer Fragment from MainActivity - android-fragmentactivity

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

Related

VS 2017 - xamarin - TabHost trouble with preferences TAB

Creating with visual studio a skeleton app with tabbed views. One tab is for settings but having trouble using preferences api.
I get this error :
android.view.View cannot be cast to android.view.ViewGroup
Here's the code:
//***********************
//class for settings tab
//***********************
[Activity(Label = "Settings")]
[MetaData(PreferenceManager.MetadataKeyPreferences, Resource = "#drawable/preferences")]
public class Settings : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
View vg = new View(this);
TextView textview = new TextView(vg.Context);
textview.Text = "This is the Settings Tab";
SetContentView(vg);
textview.Id = TextView.GenerateViewId();
vg.Id = View.GenerateViewId();
FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction();
SettingsFragment cfg = new SettingsFragment();
fragmentTx.Add(vg.Id, cfg);
// Commit the transaction.
fragmentTx.Commit();
}
}
public class SettingsFragment : PreferenceFragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
AddPreferencesFromResource(Resource.Xml.preferences);
/*var intent = new Intent(this.Activity, typeof(Settings));
AddPreferencesFromIntent(intent);*/
}
}
Found! Replaced View with a FrameLayout:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
SetContentView(frame);
frame.Id = FrameLayout.GenerateViewId();
FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction();
SettingsFragment cfg = new SettingsFragment();
fragmentTx.Add(frame.Id, cfg);
// Commit the transaction.
fragmentTx.Commit();
}

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

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;
}
}}

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

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
}
}