Cant open file.txt from raw folder on a fragment - java

I'm trying to open file.txt from my raw folder through a fragment.
here is my code on KonsumerFragment.java
public class KonsumerFragment extends Fragment implements View.OnClickListener{
public KonsumerFragment() {
// Required empty public constructor
}
float marginValue;
Spinner spinnerProduct;
Spinner spinnerType;
EditText pengajuan;
EditText tenor;
TextView tvAngsuran;
String[] arrayMargin;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_konsumer, container, false);
//Define Variables
spinnerProduct = (Spinner) v.findViewById(R.id.spinnerProduct) ;
spinnerType = (Spinner) v.findViewById(R.id.spinnerType);
pengajuan = (EditText) v.findViewById(R.id.etPengajuan);
tenor = (EditText) v.findViewById(R.id.etTenor);
// Inflate the layout for this fragment
Button hitung = (Button) v.findViewById(R.id.btnHitung);
hitung.setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
try {
switch (view.getId()){
case R.id.btnHitung :
//simulate();
readMargin();
break;
}
} catch (Exception e){
e.getCause();
e.printStackTrace();
}
}
public void readMargin() throws FileNotFoundException {
try {
InputStream in = getContext().getResources().openRawResource(R.raw.margingriyafix);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
String result = "";
while(line !=null){
result += line + "\n";
}
arrayMargin = result.split("\\n");
for (int i=0 ; i<arrayMargin.length ; i++){
System.out.println(arrayMargin[i]);
}
System.out.println(arrayMargin);
} catch (Exception e){
System.out.println(e);
e.getCause();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
KonsumerFragment konsFragment = new KonsumerFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, konsFragment);
transaction.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_konsumer) {
KonsumerFragment konsFragment = new KonsumerFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, konsFragment);
transaction.commit();
} else if (id == R.id.nav_produktif) {
ProduktifFragment prodFragment = new ProduktifFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, prodFragment);
transaction.commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
the part of the reading file has been in the right way. I tested it running on MainAcivity directly. but it won't run on Fragment. it has been successfully running on an Activity, I believe that the problem comes from the InputStream, but anyway I've tried doing like
getActivity().getResources().openRawResource(R.raw.margingriyafix);
and also
getContext().getResources().openRawResource(R.raw.margingriyafix);
still not working.
please anyone help me.

Related

How to implement navigation activity and Recyclerview in MainActivity

I started off with a Navigation drawer activity and I added a recyclerView into the content_main.xml but I have been unable to implement the RecyclerView into the ManiActivity.java file.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
That is what my MainAcitity.java looks like when I haven't only implemented the NavigationView Activity.
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
And I also need this(the recyclerview) into my MainActivity.java There isn't room for both
This code below is my adapter class and the whole struggle is to add this to the MainActivity.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData = Collections.emptyList();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// binds the data to the textview in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myTextView;
public ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
You need to implement both NavigationView.OnNavigationItemSelectedListener and MyRecyclerViewAdapter.ItemClickListener interfaces on the MainActivity class. This way you would be able to call the adapter class for the Recycler view.Your code should look like this:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
In Java, a class can implement more than one interfaces and a class can only extend from one parent. Implementation of more than one interfaces eliminates multiple inheritance which is not allowed in Java.
For example:
ClassA implements ClassB, ClassC
Your edited code can be found here
Problem seems to be associated with Adapter class. I would like to see your code for adapter.
1. Make sure if count is not equal to zero.
2. Make sure you are inflating a proper view in adapter class.
3. The view you are inflating must have external layout Relative or Linear or Constraint.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
TabLayout tabLayout;
ViewPager viewPager;
NavigationView navigationView;
View navHeaderView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navHeaderView = navigationView.getHeaderView(0);
viewPager = (ViewPager) findViewById(R.id.viewPagerContainer);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
textViewNavigationName = (TextView)
navHeaderView.findViewById(R.id.textViewNavigationName);
textViewNavigationEmail = (TextView)
navHeaderView.findViewById(R.id.textViewNavigationEmail);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
Fragment_Home objFragment1 = new Fragment_Home();
fragmentTransaction.add(R.id.viewPagerContainer, objFragment1).addToBackStack("backkkkkkkkkkkkk");
fragmentTransaction.commit();
}
}
public class Fragment_Home extends Fragment
{
private static final String ARG_PAGE_KEY = "arg_page";
String nextPageToken;
String prevPageToken;
String pageToken;
int sizeOfPlaylist;
int sizeOfCurrentList;
int firstItemPosition;
MenuItem nextItem;
MenuItem lastItem;
LinearLayout linearLayoutProgress, linearLayoutNoConnection;
Button buttonReload;
RecyclerView recyclerViewVideos;
AllVideosAdapterR adapter;
TextView textViewProgress;
public static Fragment_Home newInstance(int pageNumber) {
Fragment_Home myFragment = new Fragment_Home();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE_KEY, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
LayoutInflater inflater1 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater1.inflate(R.layout.fragment_home, container, false);
getActivity().invalidateOptionsMenu();
findControls(view);
gettingList();
buttonReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gettingList();
}
});
return view;
}
public void findControls(View view)
{
recyclerViewVideos = (RecyclerView)view.findViewById(R.id.recyclerViewVideos);
linearLayoutProgress = (LinearLayout)view. findViewById(R.id.linearLayoutProgress);
textViewProgress = (TextView) view.findViewById(R.id.textViewProgress);
linearLayoutProgress.setVisibility(View.INVISIBLE);
linearLayoutNoConnection = (LinearLayout)view.findViewById(R.id.linearLayoutNoConnection);
linearLayoutNoConnection.setVisibility(View.INVISIBLE);
buttonReload = (Button)view.findViewById(R.id.buttonReload);
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public void setAdapter(List<Item> listItems) {
recyclerViewVideos.setLayoutManager(new
LinearLayoutManager(getActivity()));
adapter = new AllVideosAdapterR(getActivity(), listItems);
recyclerViewVideos.setAdapter(adapter);
}
public void showProgress(String message) {
textViewProgress.setText(message);
linearLayoutProgress.setVisibility(View.VISIBLE);
}
public void stopProgress() {
linearLayoutProgress.setVisibility(View.INVISIBLE);
}
public void gettingList() {
if (!isDeviceOnline()) {
linearLayoutNoConnection.setVisibility(View.VISIBLE);
} else {
linearLayoutNoConnection.setVisibility(View.INVISIBLE);
}
showProgress("Loading videos..");
Retrofit retrofit = newRetrofit.Builder().baseUrl(BaseUrls.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
WebApis call1 = retrofit.create(WebApis.class);
Call<ListResponse> call = call1.requestList();
call.enqueue(new Callback<ListResponse>() {
#Override
public void onResponse(Call<ListResponse> call, Response<ListResponse> response) {
System.out.println("size....................." + response.body().getItems().size());
setAdapter(response.body().getItems());
sizeOfPlaylist = response.body().getPageInfo().getTotalResults();
try {
nextPageToken = response.body().getNextPageToken();
prevPageToken = response.body().getPrevPageToken();
firstItemPosition = response.body().getItems().get(0).getSnippet().getPosition();
sizeOfCurrentList = response.body().getItems().size();
} catch (Exception e) {
Toast.makeText(getActivity(), "More pages not available", Toast.LENGTH_SHORT).show();
}
stopProgress();
}
#Override
public void onFailure(Call<ListResponse> call, Throwable t) {
stopProgress();
Toast.makeText(getActivity(), "Check your Network connection", Toast.LENGTH_LONG).show();
linearLayoutNoConnection.setVisibility(View.VISIBLE);
}
});
}
public void gettingNextList(String token) {
showProgress("Loading videos..");
Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrls.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
WebApis call1 = retrofit.create(WebApis.class);
Call<ListResponse> call = call1.requestNextList(token);
call.enqueue(new Callback<ListResponse>() {
#Override
public void onResponse(Call<ListResponse> call, Response<ListResponse> response) {
System.out.println("size....................." + response.body().getItems().size());
setAdapter(response.body().getItems());
try {
nextPageToken = response.body().getNextPageToken();
prevPageToken = response.body().getPrevPageToken();
firstItemPosition = response.body().getItems().get(0).getSnippet().getPosition();
sizeOfCurrentList = response.body().getItems().size();
} catch (Exception e) {
Toast.makeText(getActivity(), "More pages not available", Toast.LENGTH_SHORT).show();
}
stopProgress();
}
#Override
public void onFailure(Call<ListResponse> call, Throwable t) {
stopProgress();
Toast.makeText(getActivity(), "Network Problem", Toast.LENGTH_LONG).show();
}
});
}
public interface WebApis {
#GET(BaseUrls.GETTING_LIST)
Call<ListResponse> requestList();
#GET(BaseUrls.GETTING_LIST)
Call<ListResponse> requestNextList(#Query("pageToken") String pageToken);
}
}

Show Progress Dialog from class method

in my main activity I initialized a class with a method which download data from my server.
I want to show a Progress Dialog until the download. But it doesn't show the Progress Dialog.
My Main Activity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setFragmentManager(new MainActivityFragment());
Updater updater = new Updater(this,(ViewGroup) findViewById(R.id.fragment));
updater.check();
}
public void setFragmentManager(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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();
switch (id){
case R.id.action_settings:
return true;
case R.id.medi_calc_item:
setFragmentManager(new MediCalcFragment());
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_start:
setFragmentManager(new MainActivityFragment());
break;
case R.id.nav_medis:
setFragmentManager(new MediAbcFragment());
break;
case R.id.nav_bos:
setFragmentManager(new BosAbcFragment());
break;
default:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
My Class:
public class Updater {
private Context context;
private ViewGroup viewGroup;
private VersionsDAO versionsDAO;
private MediDAO mediDAO;
private RegioDAO regioDAO;
private HashMap<String,Integer> onlineVersions;
private HashMap<String,Integer> versions;
private ProgressDialog progressDialog;
public Updater(Context context, ViewGroup viewGroup) {
this.context = context;
this.versionsDAO = new VersionsDAO(context);
this.mediDAO = new MediDAO(context);
this.viewGroup = viewGroup;
this.onlineVersions = new HashMap<>();
this.regioDAO = new RegioDAO(context);
this.progressDialog = new ProgressDialog(context);
}
public void check(){
progressDialog.setMessage(context.getString(R.string.update_cities));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.show();
RequestQueue queue = Volley.newRequestQueue(this.context);
String url ="http://resper.de/resperApi.php?cmd=deStadt";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
for(int i = 0; i < jArray.length(); i++){
JSONObject jObject = jArray.getJSONObject(i);
regioDAO.insertDeStadt(jObject.getInt("id"), jObject.getString("name"), jObject.getInt("bl"), jObject.getInt("rb"), jObject.getInt("kreis"), jObject.getInt("lk"));
}
versionsDAO.updateVersion("deStadt", onlineVersions.get("deStadt"));
progressDialog.cancel();
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverNotAvailable();
}
});
queue.add(stringRequest);
progressDialog.cancel();
}
}
Remove progressDialog.cancel(); from last line. That is after queue.add(stringRequest); and try again.

how to perform an action by selecting an item from the recyclerView on the fragment

I am using the navigation drawer template in the Android Studio
I use one activity only ... fragments are replaced over that one activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// here I call the fragment
FragmentManager fm=getFragmentManager();
fm.beginTransaction().replace(R.id.content_main_frame, new homeFragment()).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
public class homeFragment extends Fragment{
RecyclerView recyclerView;
String[] fields={"ALV","NIJU","AJITH","ASWIN"};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
//for getting recyclerview id
recyclerView= (RecyclerView) rootView.findViewById(R.id.recyclerView_home);
// for specifying layout manager
LinearLayoutManager manager=new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(manager);
homeListAdapter adapter = new homeListAdapter(this.getActivity(), fields);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
return rootView;
}
}
public class homeListAdapter extends RecyclerView.Adapter<homeListAdapter.homeViewHolder> {
private Context context;
private String[] field;
public homeListAdapter(Context context, String[] field){
this.context=context;
this.field=field;
}
#Override
public homeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view = inflater.from(parent.getContext()).inflate(R.layout.item_home,parent,false);
homeViewHolder viewHolder= new homeViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(homeViewHolder holder, int position) {
holder.card_home_title.setText(field[position]);
}
#Override
public int getItemCount() {
return field.length;
}
// View holder
public static class homeViewHolder extends RecyclerView.ViewHolder{
public CardView card_view;
public TextView card_home_title;
public homeViewHolder(View itemView) {
super(itemView);
card_view = (CardView) itemView.findViewById(R.id.card_view);
card_home_title = (TextView) itemView.findViewById(R.id.card_text);
}
}
}
public class ItemHome implements Serializable {
public int id;
public String title;
}
When I press ALV I want to replace by this alvfragment, and when I press the Niju I want to display this Nijufragment.
Screenshot:
If i understand you correctly you want to replace fragments from the navigation drawer, For that you need to go to MainActivty and this is an example for how to do that:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
//use here the desired nav
} else if (id == R.id.nav_ALV) {
FragmentManager fm=getFragmentManager();
fm.beginTransaction().replace(R.id.content_main_frame, new ALVFragment).commit();

Android Fragment Orientation Causes Attach Issues

Hello everyone I have a question on rotating fragments and restoring them after detaching them. Currently I have three fragments: Fragment_Data, Fragment_Log, and Fragment_Control. My problem is if I rotate Fragment_Data, then detach and add Fragment_Log, then detach Fragment_Log and attempt to attach Fragment Data it fails to reattach. If I keep the device vertical and repeat the same steps the fragments don't have any issues reattaching. I try to detach, add, and attach the fragments in my PanelManager method.
What exactly is going one during the lifecycle of the Fragment_Data that causes issues when trying to reattach?
MainActivty.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentControl.ButtonSetListener{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentControlTransction = fragmentManager.beginTransaction();
FragmentTransaction fragmentDataTransaction = fragmentManager.beginTransaction();
FragmentControl fragmentControl = new FragmentControl();
FragmentData fragmentData = new FragmentData();
FragmentLog fragmentLog = new FragmentLog();
FragmentGraph fragmentGraph = new FragmentGraph();
//Create Fragment Manager
FragmentManager panelManager = getFragmentManager();
//Boolean values for panels
boolean data_panel = true; //True because it is the first panel created in the View; id = 1
boolean log_panel = false; //id = 2
boolean graph_panel = false; //id = 3
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if(savedInstanceState != null){
return;
}
//Generate Fragment_Data and Fragment_Control Panels
//These are the first two panels introduced into the app
fragmentControlTransction.add(R.id.fragment_control_panel, fragmentControl, "control");
fragmentControlTransction.commit();
fragmentDataTransaction.add(R.id.fragment_data_panel, fragmentData, "data");
fragmentDataTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.data_log) {
PanelManager(2);
} else if (id == R.id.data_graph) {
PanelManager(3);
} else if (id == R.id.nav_share) {
PanelManager(1);
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void PanelManager(int panel_id){
if(panel_id == 1){
//detach any panel attached to the fragment_data_panel
panelManager.beginTransaction().detach(getFragmentManager().findFragmentById(R.id.fragment_data_panel)).commit();
//Switch to data panel since it already exists
panelManager.beginTransaction().attach(fragmentData).commit();
} else if(panel_id == 2){
//detach any panel attached to the fragment_data_panel
panelManager.beginTransaction().detach(getFragmentManager().findFragmentById(R.id.fragment_data_panel)).commit();
//Switch to log panel
if(log_panel == false){
//If log panel is false, create log_panel for the first time
log_panel = true;
panelManager.beginTransaction().add(R.id.fragment_data_panel, fragmentLog).commit();
} else {
//Log_panel exists, so just attach fragment back
panelManager.beginTransaction().attach(fragmentLog).commit();
}
} else if(panel_id == 3){
//detach any panel attached to the fragment_data_panel
panelManager.beginTransaction().detach(getFragmentManager().findFragmentById(R.id.fragment_data_panel)).commit();
//Switch to graph panel
if(graph_panel == false){
//If log panel is false, create graph_panel for the first time
graph_panel = true;
panelManager.beginTransaction().add(R.id.fragment_data_panel, fragmentGraph).commit();
} else {
//Log_panel exists, so just attach fragment back
panelManager.beginTransaction().attach(fragmentGraph).commit();
}
}
}
//Call updateList method in FragmentLog to update ListView
#Override
public void app_log_update(String data, int icon) {
FragmentLog fragmentLog = (FragmentLog)getFragmentManager().findFragmentById(R.id.fragment_data_panel);
fragmentLog.updateList(data, icon);
}
}
FragmentData.java
public class FragmentData extends Fragment implements View.OnClickListener{
public EditText message_text;
public TextView display_message;
public Button button;
public String return_message = null;
boolean has_text_entered = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
return_message = savedInstanceState.getCharSequence("savedText").toString();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_data, container, false);
button = (Button)view.findViewById(R.id.set_text_button);
button.setOnClickListener(this);
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setText("This is a temp statement");
if(return_message != null){
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setText(return_message);
}
return view;
}
#Override
public void onClick(View v) {
has_text_entered = true;
message_text = (EditText)getActivity().findViewById(R.id.text_message);
String message = message_text.getText().toString();
display_message = (TextView)getActivity().findViewById(R.id.display_message);
display_message.setText(message);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView text = (TextView)getActivity().findViewById(R.id.display_message);
CharSequence userText = text.getText();
if(userText != null){outState.putCharSequence("savedText", userText);}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
}
Thank you for the help everyone!

new fragment cannot be loaded by clicking on Drawer item in Android Studio

I've implemented the following code , but when I run the app and click on an item in Drawer nothing happened. I guess it's a problem related to the Listener but I couldn't grasp how to fix it. or maybe other problem!
once I click on one item the only thing happen is the following two lines in the logcat :
01-12 03:14:26.606 1565-1565/? I/LatinIME: Starting input. Cursor position = -1,-1
01-12 03:14:29.601 1565-1565/? I/LatinIME: Starting input. Cursor position = 0,0
here is the code:
public class Welcome extends AppCompatActivity {
private DrawerLayout mDrawer,dlDrawer;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
dlDrawer.setDrawerListener(drawerToggle);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.drawer_layout, new EditPersonal());
tx.commit();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, dlDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = EditPersonal.class;
break;
case R.id.nav_second_fragment:
fragmentClass = Chronogram.class;
break;
case R.id.nav_third_fragment:
fragmentClass = BloodTest.class;
break;
case R.id.nav_forth_fragment:
fragmentClass = GlucoseTest.class;
break;
case R.id.nav_fifth_fragment:
fragmentClass = SendRecord.class;
break;
case R.id.nav_sixth_fragment:
fragmentClass = ReviewLogin.class;
break;
case R.id.nav_seventh_fragment:
fragmentClass = SignOut.class;
break;
default:
fragmentClass = EditPersonal.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit();
// Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
// ...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
}
the app screen shot:
On your switch case, try something like this:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
case R.id.nav_first_fragment:
EditPersonal editPersonal= new EditPersonal();
fragmentTransaction.replace(R.id.flContent, editPersonal);
fragmentTransaction.commit();
break;
Do this on other cases too.
Have you tried putting logs into your code to see where the logic flows to or fails to flow to?
For example inside your switch statement, try seeing if menuItem.getItemId() actually matches your case statements. It'd help to see if your listener is actually the problem or if it's just not matching the cases. Or it could be a problem with your fragment manager.
Check out http://developer.android.com/reference/android/util/Log.html. You should be able to see the logs in logcat. Good luck!
Basically I have changed the code using the Activity (Navigation Drawer Activity) of Android studio itself. so here is the code :
public class Welcome extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.review_login_listview, menu);
return true;
}
#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.menu_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_first_fragment) {
// Handle the camera action
}
else {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Categories

Resources