I have the following listView:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//CheckBoxAdapter cb = new CheckBoxAdapter(this.getActivity(),R.layout.item, getResources().getStringArray(R.array.products));
//lv.setAdapter(cb);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_list_item_1, categories);
ListView lv = (ListView) this.getActivity().findViewById(R.id.listProduct);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String type = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getContext(), parent.getItemAtPosition(position)+" is selected", Toast.LENGTH_LONG).show();
try {
MainActivity.AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
} catch (TimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
But currently I cannot reference addSubscription which is nonstatic
MainActivity.AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
I need to create a non static listener which can call addsubscription, is it possible with a listview? If not can I use another type of view?
Simply if your fragment is placed in MainActivity do this:
((MainActivity)getActivity()).AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
Do the following in the listener:
YourFragmentName.this.((MainActivity)getActivity()).AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
I would not use getActivity() and cast it as this approach seems to fragile to me.
I typed this out of my head without an IDE so there might be typos.
Let the Activity implement an interface SubscriptionHandler
public interface SubscriptionHandler {
public void addSubscription(String identifier);
}
Actitiy
public MainActivity extends AppCompatActivity implements SubscriptionHandler {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_id);
fragment.setSubscriptionHandler(this);
}
#Override
public void addSubscription(String identifier){
//logic
}
}
and then use this in the Fragment
public class MyFragment extends Fragment {
#Nullable private SubscriptionHandler subscriptionHandler;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_list_item_1, categories);
ListView lv = (ListView) this.getActivity().findViewById(R.id.listProduct);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String type = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getContext(), parent.getItemAtPosition(position)+" is selected", Toast.LENGTH_LONG).show();
try {
if(subscriptionManager != null) {
subscriptionHandler.addSubscription(String.valueOf(parent.getItemAtPosition(position)));
}
} catch (TimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
public void setSubscriptionHandler (SubscriptionHandler subscriptionHandler) {
this.subscriptionHandler = subscriptionHandler;
}
}
Related
I'm pulling the weekly data of students from firebase and adding an arraylist inside a class and I return this arraylist to Teacheractivity and I send this arraylist to spinner inside spinner class when i run emulator i can see data in spinner but when i click nothing happens. It doesn't give any error. I wrote it in separate classes to write clean code. Could this be a problem? I don't understand why this happened.
My TeacherActivity
public class TeacherDersActivity extends AppCompatActivity {
ActivityTeacherDersBinding binding;
String lesson_name;
ArrayList<String> WeekContentArraylist;
_Spinner spinner;
GetWeeks getWeeks;
static void SpinnerList(_Spinner spinner)
{
spinner.init();
}
public void init() {
Intent intent = getIntent();
lesson_name= intent.getStringExtra("teacher_lesson");
getWeeks = new GetWeeks(this);
WeekContentArraylist = getWeeks.GetWeekContent(lesson_name);
spinner = new _Spinner(TeacherDersActivity.this, WeekContentArraylist);
SpinnerList(spinner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityTeacherDersBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
init();
}
}
GetWeeks class from which I pull data from Firebase
My GetWeeks class
public class GetWeeks {
FirebaseFirestore mFirestore;
ArrayList<String> arrayListWeekContent;
Activity _activity;
public GetWeeks(Activity activity)
{
_activity = activity;
mFirestore = FirebaseFirestore.getInstance();
arrayListWeekContent = new ArrayList<>();
}
public void init()
{
}
protected ArrayList<String> GetWeekContent(String lesson_name)
{
mFirestore.collection("Lessons")
.document(lesson_name)
.collection("Documents")
.document("Docs1")
.get()
.addOnSuccessListener(_activity, new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(#NonNull DocumentSnapshot documentsnapshots) {
arrayListWeekContent.add(documentsnapshots.getString("Week1"));
arrayListWeekContent.add(documentsnapshots.getString("Week2"));
arrayListWeekContent.add(documentsnapshots.getString("Week3"));
arrayListWeekContent.add(documentsnapshots.getString("Week4"));
arrayListWeekContent.add(documentsnapshots.getString("Week5"));
arrayListWeekContent.add(documentsnapshots.getString("meetLink"));
}
}).addOnFailureListener(_activity, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
System.out.println("GetWeeks FAIL");
}
});
return arrayListWeekContent;
}
}
My Spinner class
public class _Spinner extends Activity {
Activity activityTeacherDers;
ArrayList<String> WeekContentArraylist;
public _Spinner(Activity activityTeacherDers, ArrayList<String> WeekContentArraylist)
{
this.activityTeacherDers = activityTeacherDers;
this.WeekContentArraylist= WeekContentArraylist;
}
public void init()
{
Spinner spinner = activityTeacherDers.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activityTeacherDers,
android.R.layout.simple_spinner_item,WeekContentArraylist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("Heloooasdasdsa dataa "); //<---- nothing happen hear
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
I have MainActivity and SpinnerActivity, I want to get selected spinner item value from SpinnerActivity into the MainActivity. I tried to declare String as Static, I also tried with getter but without any success.
in Spinner Activity I also have if statement, how can I get value outside "if statement" and "#Override method" into another class?
MainActivity.class
public class MainActivity extends AppCompatActivity {
SpinnerActivity spinnerActivity = new SpinnerActivity();
Spinner spinnerProvince;
String selectedSpinnerProvince = spinnerActivity.inSpinnerSelectedProvince;
// String selectedSpinnerProvince = SpinnerActivity.inSpinnerSelectedProvince;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerProvince = findViewById(R.id.spinnerProvince);
populateSpinnerProvinces();
spinnerProvince.setOnItemSelectedListener(spinnerActivity);
}
public void populateSpinnerProvinces() {
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.province));
provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProvince.setAdapter(provincesAdapter);
}
}
SpinnerActivity.class
public class SpinnerActivity implements android.widget.AdapterView.OnItemSelectedListener {
public String inSpinnerSelectedProvince;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.spinnerProvince) {
inSpinnerSelectedProvince = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
} else {// code here}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I were about to advice you to use Intent to share data between both activities when i noticed that your "SpinnerActivity" is not really an Activity since it not extends Android Activity class (AppCompactActivity or other classes like this).
Your SpinnerActivity is a Listener. You can use it to implement the action to trigger when an action is performed on your Spinner view. For that you need to do it inside the "#Override" method of onItemSelected.
If you don't like to use the previous methode because of the Override methode you should implement directly the action to trigger at on click events on your spinner view in your MainActivity by doing this:
public class MainActivity extends AppCompatActivity {
SpinnerActivity spinnerActivity = new SpinnerActivity();
Spinner spinnerProvince;
String selectedSpinnerProvince = spinnerActivity.inSpinnerSelectedProvince;
// String selectedSpinnerProvince =
SpinnerActivity.inSpinnerSelectedProvince;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerProvince = findViewById(R.id.spinnerProvince);
populateSpinnerProvinces();
//spinnerProvince.setOnItemSelectedListener(spinnerActivity);
spinnerProvince.setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.spinnerProvince) {
inSpinnerSelectedProvince = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
} else {// code here}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void populateSpinnerProvinces() {
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.province));
provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProvince.setAdapter(provincesAdapter);
}
}
I have a Fragment that contains a RecyclerView. I am trying to implement a filter on the RecyclerView. The filter UI opens a new Fragment Dialog where the user will input a value. Once the user hits the Search Button in the Fragment Dialog, the value should be returned to the RecyclerView Fragment and the existing data in the view should be cleared. I want to re-populate the RecyclerView with the new set of data that I will obtain from the server. My problem is that, I have a method called resetAdapterDetails() in the RecyclerView Fragment which works as expected if called from the RecyclerView Fragment itself. But, when I try to call the same method from the Fragment Dialog, I get an exception:
transactionList.clear(); --> is trying to clear a list which is null
Though the data is still visible in the RecyclerView.
The RecyclerView Fragment:
public class TransactionHistoryFragment extends Fragment implements SearchView.OnQueryTextListener, DateRangePickerFragment.OnDateRangeSelectedListener{
private RecyclerView recyclerview;
private TransactionHistoryAdapter adapter;
private List<Transaction> transactionList;
public TransactionHistoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_transaction_history, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
getTransactionHistory("");
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.transactions_history_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.filter_date:
FragmentManager fmDate = getActivity().getFragmentManager();
DateRangePickerFragment dialogFragmentDate = DateRangePickerFragment.newInstance(this, true);
dialogFragmentDate.show(fmDate, "Sample Fragment");
return true;
case R.id.filter_mobile:
FragmentManager fmMobile = getActivity().getFragmentManager();
SearchMobileFragment dialogFragmentMobile = new SearchMobileFragment ();
dialogFragmentMobile.show(fmMobile, "Sample Fragment");
//resetAdapterDetails();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onQueryTextChange(String newText) {
final List<Transaction> filteredModelList = filter(transactionList, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
//for filtering the list
private List<Transaction> filter(List<Transaction> models, String query) {
query = query.toLowerCase();final List<Transaction> filteredModelList = new ArrayList<>();
for (Transaction model : models) {
final String text = model.getTxnStatus().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//for populating the list
private void getTransactionHistory(String agentId){
GetTransactionHistoryTask task = new GetTransactionHistoryTask("agent1", "password");
task.getTransactionsByAgent("OU23","OU230000000123456789").subscribe(transactionHistoryResponse -> {
if(transactionHistoryResponse != null && transactionHistoryResponse.getTransactions() != null && transactionHistoryResponse.getTransactions().size() > 0 && transactionHistoryResponse.getErrors().size() == 0){
transactionList = transactionHistoryResponse.getTransactions();
adapter = new TransactionHistoryAdapter(transactionList);
recyclerview.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerview.setAdapter(adapter);
onClickListnerRecyclerView();
}
else{
}
}, e -> e.printStackTrace());
}
private void onClickListnerRecyclerView() {
recyclerview.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
try {
final Transaction transactionModel= (Transaction) adapter.getObjectAt(position);
Intent i = new Intent(getActivity(), TransactionDetailsActivity.class);
i.putExtra("transaction_object",transactionModel);
startActivity(i);
}
catch (Exception e){
Log.e("List issue", e.toString());
}
}
})
);
}
#Override
public void onDateRangeSelected(int startDay, int startMonth, int startYear, int endDay, int endMonth, int endYear) {
}
public void fetchDateRange(String startDate, String endDate) {
Log.e("DateRange",startDate + "\n" + endDate);
}
public void fetchMobileNumber(String mobileNumber) {
Log.e("Mobile",mobileNumber);
resetAdapterDetails();
}
public boolean resetAdapterDetails(){
try {
transactionList.clear();
adapter.notifyDataSetChanged();
recyclerview.setAdapter(adapter);
} catch (Exception e) {
Log.e("Reset Error", ""+e.getMessage());
}
return true;
}
}
The Dialog Fragment:
public class SearchMobileFragment extends DialogFragment {
EditText mMobileNumberEditText;
Button search_button;
public SearchMobileFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search_mobile, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMobileNumberEditText = (EditText) view.findViewById(R.id.mobile_number_editText);
search_button = (Button) view.findViewById(R.id.search_button);
search_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
TransactionHistoryFragment obj = new TransactionHistoryFragment();
obj.fetchMobileNumber(mMobileNumberEditText.getText().toString());
}
});
}
}
The fetchMobileNumber() method in the TransactionHistoryFragment (RecyclerView Fragment) is called through the fetchMobileNumber() method which is called from the SearchMobileFragment (Dialog Fragment).
Where am I going wrong? Why the transactionList.clear(); is throwing the null pointer exception?
You are getting the issue because you are creating new TransactionHistoryFragment instance search_button click in SearchMobileFragment. Which makes it's all variables null and initialize it again and here your transactionList becomes null.
You can achieve the same thing easily with different way also. As the place of SearchMobileFragment as a DialogFragment you can make it as Activity and start it as startActivityForResult from your TransactionHistoryFragment and implement onActivityResult callback to doing the fiteration.
But right now in your case you can manage it in different ways also:
First way:
As you are doing in your DialogFragment
search_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
/*TransactionHistoryFragment obj = new TransactionHistoryFragment();
obj.fetchMobileNumber(mMobileNumberEditText.getText().toString());*/
}
});
Don't do the call for fetchMobileNumber here, in onResume of your TransactionHistoryFragment you should make a call for this. On the click of search_button save the filter data to SharedPreferences and use that in onResume of the TransactionHistoryFragment for filtering and after that clear this saved data from SharedPreferences onPause of this fragment.
You should remove
transactionList.clear();
of code from resetAdapterDetails() in TransactionHistoryFragment, because after search filter you will get updated transactionList which is already passed to adapter then forcefully no need to clear it. Or have a check before clearing it like:
if(transactionList!=null){
transactionList.clear();
}
Second way: Using BroadcastReceiver you can achieve the same thing.
Register a receiver in your TransactionHistoryFragment and sendBroadcast from SearchMobileFragment. In onReceive of the TransactionHistoryFragment do the filtration process.
I had resolved the above issue in a different way. In the Dialog Fragment I have implemented a View.OnClickListener and have created an Interface to initialize the same from the RecyclerView Fragment. I am posting the complete source codes below; the SearchMobileFragment now looks like:
public class SearchMobileFragment extends DialogFragment implements View.OnClickListener{
private OnMobileNumberSelectedListener onMobileNumberSelectedListener;
EditText mMobileNumberEditText;
Button mSearchButton;
public SearchMobileFragment() {
// Required empty public constructor
}
public static SearchMobileFragment newInstance(OnMobileNumberSelectedListener callback) {
SearchMobileFragment searchMobileFragment = new SearchMobileFragment();
searchMobileFragment.initialize(callback);
return searchMobileFragment;
}
public void initialize(OnMobileNumberSelectedListener callback) {
onMobileNumberSelectedListener = callback;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_search_mobile, container, false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
mMobileNumberEditText = (EditText) root.findViewById(R.id.mobile_number_editText);
mSearchButton = (Button) root.findViewById(R.id.search_button);
mSearchButton.setOnClickListener(this);
return root;
}
#Override
public void onStart() {
super.onStart();
if (getDialog() == null)
return;
getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}
public void setOnMobileNumberSelectedListener(OnMobileNumberSelectedListener callback) {
this.onMobileNumberSelectedListener = callback;
}
#Override
public void onClick(View v) {
dismiss();
onMobileNumberSelectedListener.onMobileNumberSelected(mMobileNumberEditText.getText().toString());
}
public interface OnMobileNumberSelectedListener {
void onMobileNumberSelected(String mobileNumber);
}
}
The RecyclerView Fragment modifications:
public class TransactionHistoryFragment extends Fragment implements SearchView.OnQueryTextListener,
DateRangePickerFragment.OnDateRangeSelectedListener, SearchMobileFragment.OnMobileNumberSelectedListener{
private RecyclerView recyclerview;
private TransactionHistoryAdapter adapter;
private List<Transaction> transactionList;
SearchView search;
public static final String TIMERANGEPICKER_TAG = "timerangepicker";
public TransactionHistoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_transaction_history, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
getTransactionHistory();
}
#Override
public void onResume() {
Log.e("onResumeTHF","invoked");
super.onResume();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.transactions_history_menu, menu);
search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.filter_date:
FragmentManager fmDate = getActivity().getFragmentManager();
DateRangePickerFragment dialogFragmentDate = DateRangePickerFragment.newInstance(this, true);
dialogFragmentDate.show(fmDate, "Sample Fragment");
return true;
case R.id.filter_mobile:
FragmentManager fmMobile = getActivity().getFragmentManager();
SearchMobileFragment dialogFragmentMobile = SearchMobileFragment.newInstance(this);
dialogFragmentMobile.show(fmMobile, "Sample Fragment");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onQueryTextChange(String newText) {
Log.e("newText",newText);
final List<Transaction> filteredModelList = filter(transactionList, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public void onMobileNumberSelected(String mobileNumber) {
Log.e("mobileNumber",mobileNumber);
resetAdapterDetails();
}
public boolean resetAdapterDetails(){
try {
transactionList.clear();
adapter.notifyDataSetChanged();
recyclerview.setAdapter(adapter);
} catch (Exception e) {
Log.e("Reset Error", ""+e.getMessage());
}
return true;
}
}
Happy coding!
The null pointer exception is because when you create a new TransactionHistoryFragment using new onViewCreated is not called and hence transactionList is never initialized. You can create a setter for the list or pass it as a constructor to the fragment to fix this
I get this error - Cannot resolve method 'onListItemClick(android.widget.ListView,android.view.View,int,long)'
I have tried using the onClickListener method but that does not work.
Please suggest.
Here is the code-
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
ListView listview;
String[] pdflist;
File[] imagelist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
File images = Environment.getExternalStorageDirectory();
imagelist = images.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return ((name.endsWith(".pdf")));
}
});
pdflist = new String[imagelist.length];
for (int i = 0; i < imagelist.length; i++) {
pdflist[i] = imagelist[i].getName();
}
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, pdflist));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String path = imagelist[(int) id].getAbsolutePath();
openPdfIntent(path);
}
private void openPdfIntent(String path) {
try {
final Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Use this instead:
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
Replace this line from
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
to
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener, OnItemClickListener {
and add following line in onCreate() method:
listview = (ListView) findViewById(R.id.listView1);
listview.setOnItemClickListener(this);
How to get item where i click in list-view?
Here is my code:
public class MainClass extends Activity {
ArrayList <String> listItems = new ArrayList<String>();
ArrayAdapter <String> adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listItems.add("Item 1");
listItems.add("Item 2");
listItems.add("Item 3");
adapter.notifyDataSetChanged();
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
but it force closes everytime.
change:
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});
to:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), listView.getItemAtPosition(arg2).toString(), Toast.LENGTH_LONG).show();
}
});
You need to use a onItemClickListener if you want to interact with the items in the list. This has a position argument in the method which you can then use to retrieve the value at that position.
try :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent,
View view, int pos, long id) {
String item=(String)((TextView) view).getText();
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});