Categories
discuss

Boot-strapping Spring Data JPA without XML

What is the Java @Configuration equivalent to:

<repositories base-package="com.acme.repositories" />

in Spring Data JPA? I am trying to get rid of XML configuration in favour to @Configuration classes, however reading through JpaRepositoryConfigDefinitionParser sources is fruitless.

The closest what I can get is:

@Bean
public RepositoryFactorySupport repositoryFactory() {
    return new JpaRepositoryFactory(entityManagerFactory().createEntityManager())
}

@Bean
public BookDao bookDao() {
    return repositoryFactory().getRepository(BookDao.class)
}

However the <repositories/> tag is much more functional: it automatically creates DAO for all interfaces extending CrudRepository found on CLASSPATH. Also it seems like my solution does not apply transactions to DAOs as opposed to default Spring Data JPA behaviour.

Answer

Spring Data JPA introduced @EnableJpaRepositories. See the reference documentation for details.

Categories
discuss

android: onClick responds only to second click in listview

I found a similar question about scrolling listview and button click but it did not help me. My issue is:

I have a listview with custom rows. I have two different states of listview; the switch between the states is a button at the bottom of the screen. The second state has delete buttons in every row. When I click on delete button in a specific row, that row is removed from database and listview is updated. Everything works great except I need to click the delete button twice in order for it to work. Below is my code for handling the clicks. flag==1 is the second state of the listview.

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    View main = parent.getChildAt(position);
    TextView delete = (TextView)main.findViewById(R.id.delete_button);

    if(flag==0){
        switchToItemsView(id);
    }
    if(flag==1){
        delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDbHelper.deleteList(id);
                        updateListView();
                    }});
    }
}

I tried to set parent view’s focusableInTouchMode attribute to false as suggested in another post but it did not help.

If you can help me solve this I will be grateful,

Thank you in advance.

Answer

After spending hours I figured out how to do it:

I moved my click listener from my main activity class to my custom ListAdapter class and modified it a little like below;

deleteButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int rowid = Integer.parseInt(rowIds.get(position));
        mDb.deleteList(rowid);
        lists.remove(position);
        notifyDataSetChanged();
    }
});

Now it works great. When I click delete button it removes the list both from the ArrayList (the one used in ListAdapter) and from database.

Categories
discuss

Camera exception in Android

I get the following exception when trying to tun Camera intent:

10-31 20:49:43.297: ERROR/DatabaseUtils(194): Writing exception to parcel
10-31 20:49:43.297: ERROR/DatabaseUtils(194): java.lang.UnsupportedOperationException: Unknown URI: content://media/external/images/media
10-31 20:49:43.297: ERROR/DatabaseUtils(194):     at com.android.providers.media.MediaProvider.insertInternal(MediaProvider.java:1696)
10-31 20:49:43.297: ERROR/DatabaseUtils(194):     at com.android.providers.media.MediaProvider.insert(MediaProvider.java:1638)
10-31 20:49:43.297: ERROR/DatabaseUtils(194):     at android.content.ContentProvider$Transport.insert(ContentProvider.java:174)
10-31 20:49:43.297: ERROR/DatabaseUtils(194):     at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:146)
10-31 20:49:43.297: ERROR/DatabaseUtils(194):     at android.os.Binder.execTransact(Binder.java:288)
10-31 20:49:43.297: ERROR/DatabaseUtils(194):     at dalvik.system.NativeStart.run(Native Method)
10-31 20:49:43.297: DEBUG/AndroidRuntime(583): Shutting down VM
10-31 20:49:43.308: WARN/dalvikvm(583): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
10-31 20:49:43.337: ERROR/AndroidRuntime(583): FATAL EXCEPTION: main
10-31 20:49:43.337: ERROR/AndroidRuntime(583): java.lang.UnsupportedOperationException: Unknown URI: content://media/external/images/media
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:146)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.content.ContentProviderProxy.insert(ContentProviderNative.java:408)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.content.ContentResolver.insert(ContentResolver.java:587)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at org.BJ.Food4All.utils.CameraUtil.TakePicture(CameraUtil.java:46)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at org.BJ.Food4All.Activities.NewRecipe.Instructions.onContextItemSelected(Instructions.java:132)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.app.Activity.onMenuItemSelected(Activity.java:2199)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback.onMenuItemSelected(PhoneWindow.java:2744)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:137)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:874)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.widget.AdapterView.performItemClick(AdapterView.java:284)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.widget.ListView.performItemClick(ListView.java:3382)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.os.Handler.handleCallback(Handler.java:587)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.os.Looper.loop(Looper.java:123)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at android.app.ActivityThread.main(ActivityThread.java:4627)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at java.lang.reflect.Method.invokeNative(Native Method)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at java.lang.reflect.Method.invoke(Method.java:521)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-31 20:49:43.337: ERROR/AndroidRuntime(583):     at dalvik.system.NativeStart.main(Native Method)

code is:

public void TakePicture() 
{
    mFileName                   = "LetFindANewName.jpg"; // TODO - update name
    ContentValues contentValues = new ContentValues();

    contentValues.put( MediaStore.Images.Media.TITLE,       mFileName );
    contentValues.put( MediaStore.Images.Media.DESCRIPTION, "Image capture by camera" ); // TODO- update description for recipe name description

    mImageUri = mParentActivity.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                        contentValues );

    //create new Camera Intent
    Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
    intent.putExtra( MediaStore.EXTRA_OUTPUT,           mImageUri );
    intent.putExtra( MediaStore.EXTRA_VIDEO_QUALITY,    1 );

    try
    {
        mParentActivity.startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
    }
    catch( Exception e )
    {
        Toast.makeText( mParentActivity.getApplicationContext(),
                        "Error while starting Camera!",
                        Toast.LENGTH_LONG ).show();

        Log.e( mTAG, "Failed to start camera" );
        Log.e( mTAG, e.getMessage(), e );
    }
}

Answer

I bet you forgot to insert the SD card

Categories
discuss

Throwing generic Exception discouraged?

Why is it discouraged to throw a generic (java.lang.Exception) exception, when it is usually sufficient to handle most conditional failures within a method? I understand that if a method could throw multiple types of exceptions then throwing specific subclasses of an exception might clarify the handling a bit, but in a general fail/succeed case I think Exception serves more than adequate.

Answer

The problem is that Exception is also the superclass of RuntimeException, which encompasses some stuff that shouldn’t be caught as it indicates a problem with the programming rather than an exceptional condition that arises from context. You don’t want to catch a BufferOverflowException or UnsupportedOperationException under normal circumstances. Besides, throwing separate Exception types gives the calling code control over how to handle each one. Boilerplate is reduced in Java 7 with the new multi-catch feature.

Categories
discuss

Assigning Fragments to tabs in the ActionBar with different orientations

I have 3 fragments and an activity. I want to enable tabs on the ActionBar and assign a Fragment to each of the 3 tabs. How do I hook that up correctly?

ORIGINAL POST

I have an app that I’m developing using the Google I/O app as a guide. I’ve implemented tabs into the ActionBar. They seem to be working until the tablet’s orientation changes. For example, all 3 tabs have a Fragment. I can switch between them just fine, but when I change the orientation, whatever the Fragment I was last viewing stays visible, but clicking the tabs no longer changes the view… like they have become disconnected. As expected, going back to the original orientation does not “fix” it.

I’ve looked into saving and restoring state, but I’m not seeing how those would help.

EDIT

module level:

Fragment mFragmentA = (Fragment) new AFragmentTab();
Fragment mFragmentB = (Fragment) new BFragmentTab();
Fragment mFragmentC = (Fragment) new CFragmentTab();

I have something like this in the activity’s onCreate:

ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);

ActionBar.Tab tabA = actionBar.newTab().setText("text a");
ActionBar.Tab tabB = actionBar.newTab().setText("text b");
ActionBar.Tab tabC = actionBar.newTab().setText("text c");

tabA.setTabListener(this);
tabB.setTabListener(this);
tabC.setTabListener(this);

actionBar.addTab(tabA);
actionBar.addTab(tabB);
actionBar.addTab(tabC);

and a TabListener like this:

EDIT this is removed

class MyTabListener implements ActionBar.TabListener {
    private Fragment mFragment;

    // Called to create an instance of the listener when adding a new tab
    public MyTabListener(Fragment fragment) {
        mFragment = fragment;
    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(R.id.fragment_content, mFragment, null);
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(mFragment);
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // do nothing
    }
}

EDIT

I’ve moved the TabListener. Instead of it being a separate class, I implement the TabListener on the Activity. Then on the Selected and Unselected methods I have something like:

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    switch (tab.getPosition()) {
    case 0:
        ft.add(R.id.fragment_content, mFragmentA, null);
        break;
    case 1:
        ft.add(R.id.fragment_content, mFragmentB, null);
        break;
    case 2:
        ft.add(R.id.fragment_content, mFragmentC, null);
        break;
    }
}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    switch (tab.getPosition()) {
    case 0:
        ft.remove(mFragmentA);
        break;
    case 1:
        ft.remove(mFragmentB);
        break;
    case 2:
        ft.remove(mFragmentC);
        break;
    }
}

It’s still doing the same thing. I really don’t know what’s happening.

Answer

It looks like my answer can be found here: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.html

/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.apis.app;

import com.example.android.apis.R;


import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Toast;

/**
 * This demonstrates the use of action bar tabs and how they interact
 * with other action bar features.
 */
public class FragmentTabs extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        bar.addTab(bar.newTab()
                .setText("Simple")
                .setTabListener(new TabListener<FragmentStack.CountingFragment>(
                        this, "simple", FragmentStack.CountingFragment.class)));
        bar.addTab(bar.newTab()
                .setText("Contacts")
                .setTabListener(new TabListener<LoaderCursor.CursorLoaderListFragment>(
                        this, "contacts", LoaderCursor.CursorLoaderListFragment.class)));
        bar.addTab(bar.newTab()
                .setText("Apps")
                .setTabListener(new TabListener<LoaderCustom.AppListFragment>(
                        this, "apps", LoaderCustom.AppListFragment.class)));
        bar.addTab(bar.newTab()
                .setText("Throttle")
                .setTabListener(new TabListener<LoaderThrottle.ThrottledLoaderListFragment>(
                        this, "throttle", LoaderThrottle.ThrottledLoaderListFragment.class)));

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
        private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;
        private final Bundle mArgs;
        private Fragment mFragment;

        public TabListener(Activity activity, String tag, Class<T> clz) {
            this(activity, tag, clz, null);
        }

        public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
            mArgs = args;

            // Check to see if we already have a fragment for this tab, probably
            // from a previously saved state.  If so, deactivate it, because our
            // initial state is that a tab isn't shown.
            mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
            if (mFragment != null && !mFragment.isDetached()) {
                FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
                ft.hide(mFragment);
                ft.commit();
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                ft.show(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.hide(mFragment);
            }
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
        }
    }
}
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..