I stuck with the project trying to make Page Slider between two activities.
All I know that each activity independently works, but when I try to set up PageAdapter for sliding putting:
Also, I write activity in Manifest, initialize all variables from XML in Java, but the problem starts exactly at the moment when I set up onClickListener for my buttons.
LayoutInflater inflater = LayoutInflater.from(this);
List pages = new ArrayList();
View page = inflater.inflate(R.layout.photo, null);
pages.add(page);
page = inflater.inflate(R.layout.cameragrid, null);
pages.add(page);
CameraPagerAdapter pagerAdapter = new CameraPagerAdapter(pages);
ViewPager viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0); //view being shown firstly
setContentView(viewPager);
instead of *setContentView(R.layout.photo);* it's doesn't launch.
What did I missed? Thanks for advance.
First Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
makeAdditionalPageSlide(); //>>> problems started here
initialize();
InputStream is = getResources().openRawResource(R.drawable.dinam);
bmp = BitmapFactory.decodeStream(is);
}
public void makeAdditionalPageSlide(){
LayoutInflater inflater = LayoutInflater.from(this);
List<View> pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.photo, null);
pages.add(page);
page = inflater.inflate(R.layout.cameragrid, null);
pages.add(page);
CameraPagerAdapter pagerAdapter = new CameraPagerAdapter(pages);
ViewPager viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0); //view being shown firstly
setContentView(viewPager);
}
private void initialize() {
// TODO Auto-generated method stub
iv = (ImageView) findViewById (R.id.ivReturnedPic);
ib = (ImageButton) findViewById (R.id.ibTakePic);
b = (Button) findViewById(R.id.bSetWall);
b.setOnClickListener(this);
ib.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.ibTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
PageAdapter:
public class CameraPagerAdapter extends PagerAdapter {
List<View> pages = null;
public CameraPagerAdapter(List<View> pages){
this.pages = pages;
}
#Override
public Object instantiateItem(View collection, int position){
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((View) view);
}
#Override
public int getCount(){
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object){
return view.equals(object);
}
#Override
public void finishUpdate(View arg0){
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState(){
return null;
}
#Override
public void startUpdate(View arg0){
}
}
the second Activity:
public class CameraGrid extends Activity implements OnItemClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cameragrid);
GridView gv = (GridView) findViewById(R.id.cameragrid);
CameraImageAdapter ia = new CameraImageAdapter(getApplicationContext());
gv.setAdapter(ia);
//gridview.setOnItemClickListener(this);
gv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View iv, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(),CameraImageDetails.class);
i.putExtra("id", position);
startActivity(i);
}
}
My recommendation is to make mainActivity.xml layout with placeholder for ViewPager and setContentView(R.layout.mainActivity)
Things related to content of page view u setup in PageViewAdapter.
Maybe I didn't quite understand logic u tried to do it, but it seems a bit confusing.. :S
Related
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);
}
I have a problem with viewpager. I created 2 fragment inside viewpager, but when I call again then I get view == null.
paper_adater.java
public class Paper_adapter extends FragmentStatePagerAdapter {
Context context;
public Paper_adapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new Web_fragment();
case 1:
return new Table_fragment();
default:
return null;
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
#Override
public float getPageWidth(int position) {
// TODO Auto-generated method stub
return 0.95f;
}
detail_fragment.java
public class DetailFragment extends Fragment implements OnPageChangeListener {
public static final String TAG = "Detail fragment";
WebView webView;
ViewPager viewPaper;
Paper_adapter paper_adapter;
public static int currentPage;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e(TAG, "on create view");
View view = inflater.inflate(R.layout.detail_fragment, null);
viewPaper = (ViewPager) view.findViewById(R.id.pager);
paper_adapter = new Paper_adapter(getChildFragmentManager());
viewPaper.setAdapter(paper_adapter);
viewPaper.setOnPageChangeListener(this);
return view;
}
public void Draw(String data, int position) {
FragmentManager fm = getFragmentManager();
Fragment fr = paper_adapter.getItem(position);
if (fr instanceof Web_fragment && fr != null) {
((Web_fragment) fr).draw(getActivity(),data);
} else if (fr instanceof Table_fragment && fr != null) {
}
}
}
Web_fragment.java
public class Web_fragment extends Fragment {
public static final String URL = "file:///android_asset/chart/index.html";
private final String TAG = "WEB fragment";
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.webview_fragment, null);
this.webView = (WebView) view.findViewById(R.id.webview);
// webView.clearHistory();
// webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.loadUrl(URL);
return view;
}
public void setValue(Context context) {
// webView = (WebView)getView().findViewById(R.id.webview);
// webView.loadUrl("javascript:setValue()");
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
}
public Boolean draw(Context context, String data) {
if (webView == null) {
// webView.loadUrl("javascript:setValue()");
Toast.makeText(context, "webview null", Toast.LENGTH_SHORT)
.show();
} else {
if (data == null) {
webView = (WebView) getView().findViewById(R.id.webview);
webView.loadUrl("javascript:setValue()");
return false;
} else {
Toast.makeText(context, "data web :" + data, Toast.LENGTH_SHORT)
.show();
webView.loadUrl("javascript:setValue()");
return true;
}
}
return false;
}
When I call Draw() from detail_fragment then I get Web_fragment == null
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
i am trying to make a to do list app, which will contain a listView, Button(add) in the main layout. when i click add i want it to go to another activity(AddItem) which will contain a editText and a add button. when i click the add button i want to update the list in my database and when i return to my main activity i want the list to be updated.
Here's what i have so far :
MainActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button) findViewById(R.id.bAdd);
list = (ListView) findViewById(R.id.lvList);
c = helper.getAll(); //the helper is an databasehelper class which contains method get all which returns a cursor of all the entries in the database
adapter = new newAdapter(c);
list.setAdapter(adapter);
}
public void clickAdd(View v) { //when i click the add button in the main activity
Intent intent = new Intent(MainActivity.this, AddItem.class);
startActivityForResult(intent, 1);
}
protected void ActivityForResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1 && resultCode == RESULT_OK){
helper.insert(data.getStringExtra("item")); //insert will insert the string into the database.
}
}
class newAdapter extends CursorAdapter{
public newAdapter(Cursor c){
super(MainActivity.this, c);
}
#Override
public void bindView(View row, Context context, Cursor cursor) {
// TODO Auto-generated method stub
newHolder holder = (newHolder) row.getTag();
holder.populateFrom(cursor, helper);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = getLayoutInflater();
View row = inflator.inflate(R.layout.row, parent, false); //the row is a layout containing only a textView in a linear layout
newHolder holder = new newHolder(row);
row.setTag(holder);
return (row);
}
}
static class newHolder {
private TextView name = null;
private View row = null;
newHolder(View row) {
this.row = row;
name = (TextView) row.findViewById(R.id.title);
}
void populateFrom(Cursor c, DataHelper helper) {
name.setText(helper.getName(c));
}
}
}
AddItem class :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "works");
setContentView(R.layout.add_layout);
et = (EditText) findViewById(R.id.etAdd);
tv = (TextView) findViewById(R.id.tvTopic);
bt = (Button) findViewById(R.id.badd);
}
public void add(View v){
edit = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("item", edit);
setResult(RESULT_OK, intent);
finish();
} }
what should i change to make it work, Thank you.
Try to import the project from here and just observe and make changes accordingly it is very easy and helpful.
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 :)