Issue with setting and opening fragments in Android App - java

I am having a issue, as my app is crashing instead of opening the fragments. I have a ListActivity, that takes you to another activity; and in that other activity, there are two fragments. The ListActivity is expecting a result from one of the fragments.
My code was working prior to adding the fragments! However the fragments are no longer showing up and the app closes...does anyone possibly know what my issue could be? And any advice on how to take this issue? I sincerely appreciate all and any help, thank you! My code is below.
The ListActivity.java:
public class LyricList extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lyriclist);
mDbHelper = new LyricsDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor lyricsCursor = mDbHelper.fetchAllLyrics();
startManagingCursor(lyricsCursor);
String[] from = new String[]{LyricsDbAdapter.KEY_TITLE};
int[] to = new int[]{R.id.text1};
SimpleCursorAdapter lyrics =
new SimpleCursorAdapter(this, R.layout.lyrics_row, lyricsCursor, from, to);
setListAdapter(lyrics);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createLyric();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteLyric(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createLyric() {
Intent i = new Intent(this, NextActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, NextActivity.class);
i.putExtra(LyricsDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
}
The other activity class that should be opening via the listActivity:
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab one = actionBar.newTab().setText("Lyric Editor");
Tab two = actionBar.newTab().setText("Loops");
one.setTabListener(new MyTabListener(new LyricEditorFragment()));
two.setTabListener(new MyTabListener(new LoopsFragment()));
actionBar.addTab(one);
actionBar.addTab(two);
}
public class MyTabListener implements TabListener{
Fragment fragment;
public MyTabListener(Fragment f){
fragment = f;
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.replace(R.id.frame1, fragment);
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(fragment);
}
}
}
Not sure if you want to see the fragment class, but here is this just incase:
public class LyricEditorFragment extends Fragment {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new LyricsDbAdapter(getActivity());
mDbHelper.open();
mTitleText = (EditText) getView().findViewById(R.id.title);
mBodyText = (EditText) getView().findViewById(R.id.body);
Button confirmButton = (Button) getView().findViewById(R.id.confirm);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(LyricsDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getActivity().getIntent().getExtras();
mRowId = extras != null ? extras.getLong(LyricsDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor lyric = mDbHelper.fetchLyric(mRowId);
getActivity().startManagingCursor(lyric);
mTitleText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_TITLE)));
mBodyText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_BODY)));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(LyricsDbAdapter.KEY_ROWID, mRowId);
}
#Override
public void onPause() {
super.onPause();
saveState();
}
#Override
public void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createLyric(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateLyric(mRowId, title, body);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_lyriceditor, container, false);
return view;
}
}

The problem is that you are getting a View from the activity which will return null.. you need to create/inflate the view from the onCreateView..
click here and follow the steps on how to create and use a view from fragment..
Click Here

Related

How can I update and delete data in listview on longpress

I have some records in list view, I want to update and delete these records when I long press on particular item of list. Like this structure
DBHelper1 DBHelper2 DBHelper3 DBHelper4 DBHelper5
DBHelper6
package com.example.loginproject.model;
public class Record {
String lead;
String name;
String mobile;
public Record(String lead, String name, String mobile) {
this.lead = lead;
this.name = name;
this.mobile = mobile;
}
public String getLead() {
return lead;
}
public Record(){}
public void setLead(String lead) {
this.lead = lead;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}}
public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Record> arrayList;
public MyAdapter(Context context,ArrayList<Record>arrayList){
this.context=context;
this.arrayList=arrayList;
}
#Override
public int getCount() {
return this.arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView= layoutInflater.inflate(R.layout.custom_list_view,null);
TextView textView1 =(TextView)convertView.findViewById(R.id.textview_leads);
TextView textView2 =(TextView)convertView.findViewById(R.id.textview_names);
TextView textView3 =(TextView)convertView.findViewById(R.id.textview_company);
Record record=arrayList.get(position);
textView1.setText(record.getLead());
textView2.setText(record.getName());
textView3.setText(record.getMobile());
return convertView;
}
}
public class Home extends AppCompatActivity {
TextView Name;
Button refresh,addlead;
DatabaseHelper databaseHelper;
SQLiteOpenHelper sqLiteOpenHelper;
SQLiteDatabase db;
ListView listView;
MyAdapter myAdapter;
ArrayList<Record>arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Name=(TextView)findViewById(R.id.Name);
addlead=(Button)findViewById(R.id.addlead);
refresh=(Button)findViewById(R.id.viewlead);
listView=(ListView)findViewById(R.id.list_view);
sqLiteOpenHelper=new DatabaseHelper(this);
db=sqLiteOpenHelper.getReadableDatabase();
databaseHelper=new DatabaseHelper(this);
arrayList=new ArrayList<>();
loaddatainlist();
registerForContextMenu(listView);
Name.setText(getIntent().getStringExtra(MainActivity.user));
refresh();
add_lead();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.mybutton) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage("Are you really want to Logout ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Logout Successfully",Toast.LENGTH_SHORT).show();
finish();
//startActivity(new Intent(Home.this,MainActivity.class));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
public void add_lead()
{
addlead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Home.this,Registration.class));
}
});
}
private void loaddatainlist()
{
arrayList=databaseHelper.getalldata();
myAdapter=new MyAdapter(this,arrayList);
listView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.listoption,menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.editoption:
{
startActivity(new Intent(Home.this, Update.class));
}
case R.id.deleteoption:
{
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
}
return true;
default:
return super.onContextItemSelected(item);
}
}
public void refresh()
{
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(getIntent());
}
});
}
}
public class Update extends AppCompatActivity {
EditText lead,name,company,mobile,address;
Button update;
DatabaseHelper databaseHelper;
SQLiteDatabase dataBase;
ImageButton getrecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
databaseHelper=new DatabaseHelper(this);
lead=(EditText)findViewById(R.id.lead);
name=(EditText)findViewById(R.id.updatename);
company=(EditText)findViewById(R.id.updatecompany_name);
address=(EditText)findViewById(R.id.updateaddress);
mobile=(EditText)findViewById(R.id.updatemobile);
update=(Button)findViewById(R.id.update_button);
}
}
I displayed all the records which i stored in database but I can not update it.
I am going class by class to make the things easy to understand.
DatabaseHelper class:
I am not sure why you have used below section in onCreate() method:
If there is no specific purpose then you can remove it (you can comment for it's use).
Now in Complete your Record model with all the fields which you have used in Client table. Also make the class serialized if it is not. So the Record class will look like-
public class Record implements Serializable {
..
public Record(String sno, lead, String name, String mobile, String companyName, ...) {
this.sno = sno;
this.lead = lead;
this.name = name;
this.mobile = mobile;
this.companyName = companyName;
.
.
.
}
..
}
Back to db class. Change the update() method to -
public boolean updateClientInfo(Record record) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//Updated code will be like
ContentValues contentValues = new ContentValues();
contentValues.put(Column21, record.getLead());
.
.
.
int count = sqLiteDatabase.update(Table2, contentValues, "SNO = ?", new String[] {record.getSno()});
return count > 0 ? true : false;
}
In getAllData() method to populate Record model list, pupulate all fields such as SNO etc in the updated Record model (as mentioned above with added fields).
Change the code for delete() method to-
public boolean deleteClientInfo(Record record) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//Updated code will be
int count = sqLiteDatabase.update(Table2, "SNO = ?", new String[] {record.getSno()});
return count > 0 ? true : false;
}
Update getalldata() method in DB class to -
I have updated your Home activity class so that it will work perfectly for db refresh. You try to notice the differences basically in the following area-
refresh() -> updated, loaddatainlist() -> removed, createAdapter() -> added, refreshListFromDb() -> added, onCreate() updated, onReume() -> added.
public class Home extends AppCompatActivity {
TextView Name;
Button refresh, addlead;
DatabaseHelper databaseHelper;
SQLiteOpenHelper sqLiteOpenHelper;
SQLiteDatabase db;
ListView listView;
MyAdapter myAdapter;
ArrayList<Record> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Name = (TextView) findViewById(R.id.Name);
addlead = (Button) findViewById(R.id.addlead);
refresh = (Button) findViewById(R.id.viewlead);
listView = (ListView) findViewById(R.id.list_view);
sqLiteOpenHelper = new DatabaseHelper(this);
db = sqLiteOpenHelper.getReadableDatabase();
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
createAdapter();
registerForContextMenu(listView);
Name.setText(getIntent().getStringExtra(MainActivity.user));
refresh();
add_lead();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.mybutton) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you really want to Logout ?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Logout Successfully", Toast.LENGTH_SHORT).show();
finish();
// startActivity(new Intent(Home.this,MainActivity.class));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
public void add_lead() {
addlead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Home.this, Registration.class));
}
});
}
private void createAdapter() {
myAdapter = new MyAdapter(this, arrayList);
listView.setAdapter(myAdapter);
}
private void refreshListFromDb() {
arrayList = databaseHelper.getAllClientData(arrayList);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.listoption, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editoption: {
startActivity(new Intent(Home.this, Update.class));
}
case R.id.deleteoption: {
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
}
return true;
default:
return super.onContextItemSelected(item);
}
}
public void refresh() {
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
refreshListFromDb();
}
});
}
#Override
public void onResume() {
super.onResume();
refreshListFromDb()
}
}
When you are calling Update class after longpress call the Intent as-
Intent intent = new Intent(this, Update.class);
intent.putExtra("parcel_record", recordModel); // record model of the index from array list where longpress is made.
startActivity(intent);
Fetch the record object in Update activity like this-
#Override
protected void onCreate(Bundle savedInstanceState) {
// Using getParcelableExtra(String key) method
Record record = (Record) getIntent().getParcelableExtra("parcel_record");
....
}
Now populate the fields such as name, mobile in update activity by taking from record model such as
editTextMobile.setText(record.getMobile());
Once user click on Update button, update the record model with the edited value from field such as -
record.setMobile(editTextMobile.getText().toString());
....
and call updateClientInfo(record) of DB helper class.
Hope the detail will help you to get your requirement.
Note: It's my suggestion, use a proper name for the variables and methods such as getingData() to getUserRecord() in DB class, insertData() to insertClientInfo() and so on.
try this:-
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos: " + pos);
return true;
}
});
if you want to set onLongClick on an adapter item.then just do this**(in onBindViewHolder method of adapter)**:-
holder.lv.setOnItemLongClickListener(new OnItemLongClickListener() {
//your code here.i.e updating the database
}

Reset RecyclerView adapter from another Fragment

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

onActivityResult not called when I will finish selected image

I want to add an image from device to the app.
I will use solution of David Manpearl at this openImageIntent.
My code looks fine but when I run the app and select the image in the app, but the problem is the onActivityResult when I finish selecting the image. Please see my code and advise me on what I'm doing wrong. Thank for any suggestion.
Update Info: This Fragment is parent of another Fragment it's name "EventFragment" because I have use FragmentTabHost in EventFragment to display EventAdd class fragment and I have MainActivity it's a ActionBarActivity this is a main of activity when application started. When I click EventFragment menu from MainActivity it will go to EventFragment and EventAdd it's here in FragmentTabHost . Let's see the code:
MainActivity:
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
public static String Username;
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent myIntent = getIntent();
Username = myIntent.getStringExtra("username");
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_sectionMain);
break;
case 2:
mTitle = getString(R.string.title_section1);
break;
case 3:
mTitle = getString(R.string.title_section2);
break;
case 4:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static Fragment newInstance(int sectionNumber) {
Fragment fragment = null;
switch(sectionNumber) {
default:
case 1:
fragment = new PlaceholderFragment();
break;
case 2:
fragment = new EventFragment();
break;
case 3:
//Fragment fragment = new MyFragment2();
break;
case 4:
//Fragment fragment = new MyFragment2();
break;
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
}
EventFragment:
public class EventFragment extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
mTabHost = null;
}
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_event);
mTabHost.addTab(mTabHost.newTabSpec("Tab1").setIndicator("รายการแจ้งเหตุ"),
EventListView.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab2").setIndicator("แจ้งเรื่องร้องเรียน"),EventAdd.class,null);
return mTabHost;
}
public EventFragment() {
// TODO Auto-generated constructor stub
}
}
EventAdd Class Fragment:
public class EventAdd extends Fragment {
private ArrayList<HashMap<String, String>> EventTypeList = null;
private Spinner spinnerET;
private List<String> spinnerETArray;
private static final int SELECT_PICTURE_REQUEST_CODE = 0;
private ImageView imageView;
private Bitmap photo;
private Uri outputFileUri;
private Button clearbtn;
private Button AEbtn;
private EditText name;
private EditText detail;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_event_add, container, false);
SetGet sl = new SetGet();
EventTypeList = sl.getArrayListET();
spinnerET=(Spinner) rootView.findViewById(R.id.spinnerType);
name = (EditText) rootView.findViewById(R.id.EditTextName);
detail = (EditText) rootView.findViewById(R.id.editTextdetail);
spinnerETArray = new ArrayList<String>();
imageView = (ImageView)rootView.findViewById(R.id.imageView1);
Button photoButton = (Button) rootView.findViewById(R.id.cam_btn);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImageIntent();
}
});
spinnerETArray.add("==เลือกประเภท==");
for (HashMap<String, String> map : EventTypeList){
for (Entry<String, String> mapEntry : map.entrySet())
{
if(mapEntry.getKey() == "event_type_name"){
spinnerETArray.add(mapEntry.getValue());
}
}
}
Log.d("spinnerETArray:",spinnerETArray.toString());
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this.getContext(),android.R.layout.simple_spinner_item, spinnerETArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerET.setAdapter(adapter);
clearbtn = (Button) rootView.findViewById(R.id.Clearbtn);
clearbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clearInput();
}
});
AEbtn = (Button) rootView.findViewById(R.id.AEbtn);
AEbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Mapint = new Intent(getActivity(), MapMarkPointActivity.class);
Mapint.putExtra("name", name.getText().toString());
Mapint.putExtra("detail", detail.getText().toString());
Mapint.putExtra("photo", photo);
String text = spinnerET.getSelectedItem().toString();
Integer typeId = null;
String CurrentText = "";
for (HashMap<String, String> map : EventTypeList){
for (Entry<String, String> mapEntry : map.entrySet())
{
if(mapEntry.getKey() == "event_type_name"){
CurrentText = mapEntry.getValue();
}else if(mapEntry.getKey() == "event_type_id" && CurrentText == text){
String id = mapEntry.getValue();
typeId = Integer.parseInt(id);
}
}
}
Mapint.putExtra("typeId", typeId);
startActivity(Mapint);
}
});
return rootView;
}
protected void clearInput() {
name.setText("");
detail.setText("");
spinnerET.setSelection(0);
photo = null;
imageView.setImageResource(R.drawable.ic_launcher);
}
private void openImageIntent(){
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getContext().getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
try{
Log.d("startActivityForResult:","startActivityForResult");
getParentFragment().startActivityForResult(chooserIntent, SELECT_PICTURE_REQUEST_CODE);
}catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
Log.d("onActivityResult:","onActivityResult");
if (resultCode == Activity.RESULT_OK) {
Log.d("OK:","ok");
if (requestCode == SELECT_PICTURE_REQUEST_CODE) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
Log.d("รูป:",selectedImageUri.toString());
try {
photo = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
Log.d("รูป:",photo.toString());
imageView.setImageBitmap(photo);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
Log.d("Error:",data.toString());
}
}
public EventAdd() {
super();
// TODO Auto-generated constructor stub
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
In your host activity (MainActivity.java) you need to do:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
}

Problems with onListItemClick (mNotesCursor)

i am using the developer.android Notepad tutorial (http://developer.android.com/training/notepad/notepad-ex2.html)
to create a Noteapp,
but i have problems with the onItemClick and i cant figure out, where the problem lies.
My Code
public class MainActivity extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
public static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private int mNoteNumber = 1;
private NotesDbAdapter mDbHelper;
public static String notesstring;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
ImageButton b = (ImageButton) findViewById(R.id.add);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Intent i = new Intent(MainActivity.this, NoteScreen.class);
//startActivity(i);
createNote();
}
});
}
private void fillData() {
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainactivitymenu, menu);
return result;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case INSERT_ID:
createNote();
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Settings.class);
startActivity(i);
return true;
/*case R.id.action_new:
Intent e = new Intent(MainActivity.this, NoteScreen.class);
startActivity(e);
return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createNote() {
Intent i = new Intent (this, NoteScreen.class);
startActivityForResult(i, ACTIVITY_CREATE);
/*String noteName = "Note " + mNoteNumber++;
mDbHelper.createNote(noteName, "");
fillData();*/
}
And this is the part where the Errors are:
#Override
protected void onListItemClick(ListView list, View v, int position, long id) {
super.onListItemClick(list, v, position, id);
Cursor c = mNotesCurser;
c.moveToPosition(position);
Intent i = new Intent(this, NoteScreen.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.createNote(title, body);
fillData();
break;
case ACTIVITY_EDIT:
Long rowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (rowId != null) {
String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.updateNote(rowId, editTitle, editBody);
}
fillData();
break;
}
}
}
mNotesCurser cannot be resolved to a variable
Any idea how to fix this?
Change
protected void onListItemClick(ListView 1, View v, int position, long id)
to
protected void onListItemClick(ListView list, View v, int position, long id)
and use list variable to communicate with ListView.
Note : never use numbers as a single character for variable name. Java restrict that.
And before start creating apps for android, i recommend to you read at least one book about Java.
Replace your code with :
#Override
protected void onListItemClick(ListView listView, View v, int position, long id) {
super.onListItemClick(listView, v, position, id);
Java doesn't allow to declare variables only with numbers.
A variable's name can be any legal identifier — an unlimited-length
sequence of Unicode letters and digits, beginning with a letter, the
dollar sign "$", or the underscore character "_".

open a menu in ListActivity with onListItemClick

I'm trying to show a menu once the user longclick an entry in my ListActivity but I cant figure it out. Unfourtenatly lists have been always a hard nut for me to crack and I'm still learning.
package android.GUI;
public class Shifts extends ListActivity implements OnClickListener,
SimpleGestureListener {
private Typeface tf = Entry.tf, tf2 = Entry.tf2;
public static int count = 1;
int dbHourTime = 0;
private SimpleGestureFilter detector;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.shifts);
detector = new SimpleGestureFilter(this, this);
DBAdapter DB = new DBAdapter(this);
DB.open();
Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
count = cursor.getPosition();
int g = count;
cursor.moveToNext();
String[] columns = new String[] { DB.KEY_DATE, DB.KEY_HOURS,
DB.KEY_DAY, DB.KEY_ROWID, DB.KEY_START, DB.KEY_END };
int[] to = new int[] { R.id.dateDisp, R.id.shiftDisp, R.id.day,
R.id.rawId, R.id.start, R.id.finish };
ListView ls = getListView();
TextView SF = (TextView) findViewById(R.id.total);
SF.setTypeface(tf);
TextView sum = (TextView)findViewById(R.id.sum);
sum.setTypeface(tf);
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.list_entry, cursor, columns, to);
this.setListAdapter(mAdapter);
}
#Override
protected void onListItemClick(ListView ls, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(ls, v, position, id);
CharSequence text = "Clicked";
final int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_shifts_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.back:
finish();
return true;
case R.id.clear:
DBAdapter DB = new DBAdapter(this);
DB.open();
DB.deleteAll();
startActivity(getIntent());
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Main.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Entry.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_DOWN:
break;
case SimpleGestureFilter.SWIPE_UP:
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
#Override
public void onListItemClick(ListActivity l, View v, int position, long id) {
// TODO Auto-generated method stub
}
}
This needs to be outside of your onCreate():
#Override // the error is with this method decleration
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(ls, v, position, id);
}
You're creating the onListItemClick method inside the onCreate method. Move it outside the onCreate method :)

Categories

Resources