mardi 4 août 2015

Cache Images with Volley

I'm trying to implement Image Caching into my app. The code i currently have regarding the images is below:

Network call to get images:

public void getImage(String url, final ImageView imageView) {

    System.out.println("Image Url is: " + url);
    ImageRequest requestImage = new ImageRequest(url, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            imageView.setImageBitmap(response);
        }
    }, 0, 0, null, null);

    queue.add(requestImage);
}

How could I implement the caching? I have read a few articles on SO, but am not sure on how to implement it into my app?

Thanks for your help



via Chebli Mohamed

What is the best way to fetch data from site in android?

I want to develop an android app for a site. I have following options:

  1. A Native Android Application
  2. A HTML 5 rendered on the Web view built into a Native app
  3. Throw in some Responsive Design into the front-end of your Web-app with HTML 5 and JavaScript.

I don't have access to the database. The site is given, what I need to do is to fetch data from site and displays it with listview, textView and imageview. Here I think I have a few options too: 1. Use a parser 2. Use rss feed.

I am confused about these two options. Please suggest me any better idea.

P.S. : I know the question is too broad, and can be downvoted.



via Chebli Mohamed

Auto-moving image on drag listener

I set a drag listener to an ImageView in my app, but when I click it, I don't want it to center the image based on where I pressed. It does this:

http://ift.tt/1IjkGXw

Basically, if I press on bottom right of the image, it takes where I press as central point and moves image's center point on that exact location. But I don't want it to do that. If I press on bottom right , it shouldn't auto move itself and I can drag the image from that point. I don't think any code is necessary but just in case:

@Override
public boolean onDrag(View v, DragEvent event) {
    switch (event.getAction()) {
        // Signal for the start of drag and drop operation
        case DragEvent.ACTION_DRAG_STARTED: {
            // do nothing
            break;
        }
        // The drag point has entered the bounding box of the View
        case DragEvent.ACTION_DRAG_ENTERED: {
            // do nothing
            break;
        }
        // The user has moved the drag shadow outside the bounding box of the view
        case DragEvent.ACTION_DRAG_EXITED: {
            // do nothing
            break;
        }
        // Drag shadow has been released, the drag point is within the bounding box of the view
        case DragEvent.ACTION_DROP: {
            // Get the image and its position
            ImageView view = (ImageView) event.getLocalState();
            int position = (int) view.getTag(R.id.piece_position);

            /**
             * If it is dropped on the left pane, remove it from its parent and also
             * remove the bitmap at the position and notify the adapter.
             * Add it to the left pane and set the position.
             */
            if (v == puzzlePane) {
                ViewGroup viewgroup = (ViewGroup) view.getParent();
                viewgroup.removeView(view);

                if (position != -1) {
                    pieces.remove(position);
                    mAdapter.notifyDataSetChanged();
                }

                FrameLayout containView = (FrameLayout) v;
                containView.addView(view);
                view.setVisibility(View.VISIBLE);
                view.setTag(R.id.piece_state, "left");
                view.setTag(R.id.piece_position, -1);
                view.setOnLongClickListener(null);
                view.setOnTouchListener(mAdapter);
            } else {
                view.setVisibility(View.VISIBLE);
                view.setTag(R.id.piece_state, "right");
                view.setOnTouchListener(null);
                view.setOnLongClickListener(mAdapter);
            }

            Log.d(MyDragListener.class.getSimpleName(), view.getTag(R.id.piece_state) + "");

            view.setX(event.getX() - (view.getWidth() / 2));
            view.setY(event.getY() - (view.getHeight() / 2));

            break;
        }
        // The drag and drop operation has concluded
        case DragEvent.ACTION_DRAG_ENDED: {
            // do nothing
            break;
        }
    }
    return true;
}



via Chebli Mohamed

RecyclerView.Adapter get item position of my list

I have created a RecyclerView.Adapter and I want to fill a list.. so my problem now is I don't know how to implement the get position of my list.

below you can see my code:

public class RecyclerViewAdapter extends RecyclerView.Adapter {

List<Result> _contents;

public RecyclerViewAdapter(List<Result> contents) {
    this._contents = contents;
}


@Override
public int getItemCount() {
    return _contents.size();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int position) {
    View view = null;
    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_item_card_small, parent, false);

    Result tempResult = _contents.get(position);

    TextView temp = (TextView) view.findViewById(R.id.text_city_name);
    temp.setText(tempResult.getInfo().getCity().getName());

    return new RecyclerView.ViewHolder(view) {
    };
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

   }
}

so the function onCreateViewHolder doesn't get properly the id is always the same id.. how can I fix this or implement to get the right position of mi list?¿ What it´s happening now is the list has the right number of items but is always the same item, the fist one. I guess it´s something simple but I cant figure out how to implement it.

Thanks!!



via Chebli Mohamed

Android: Hmac SHA512 in java

I have the following code in php:

$binKey = pack("H*", $keyTest);
$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));

How can i achieve the same in android (java).

I have tried few methods available for hmac sha512 but the result of php snippet is different from that of mine.

Thanks in advance



via Chebli Mohamed

notifyDataSetChanged method is not refreshing listview using updated data?

I am using an ArrayAdapter with filterable interface to implement search functionality in a listview.My code for adapter is following:

public class FlightsAdapter extends ArrayAdapter<Flight> implements Filterable {

    List<Flight> flightLists = new ArrayList<Flight>();
    private List<Flight> origFlightList;
    private Context context;
    Flight flight = null;

    public FlightsAdapter(Context context, int textViewResourceId,
            List<Flight> fLists) {
        super(context, textViewResourceId, fLists);
        this.context = context;
        this.flightLists = fLists;
    }

    public void updateFlightList(List<Flight> newData){
        this.flightLists.clear();
        this.flightLists = newData;

    }
public Filter getFilter() {
        return new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final List<Flight> results = new ArrayList<Flight>();
                if (origFlightList == null)
                    origFlightList = flightLists;
                if (constraint != null) {
                    if (origFlightList != null && origFlightList.size() > 0) {
                        for (final Flight f : origFlightList) {
                            if (f.getPlace().toLowerCase()
                                    .contains(constraint.toString()))
                                results.add(f);
                        }
                    }
                    oReturn.values = results;
                    oReturn.count = results.size();
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                flightLists = (ArrayList<Flight>) results.values;
                notifyDataSetChanged();
            }
        };
    }

}

getFilter() and publishResults() methods get triggered properly on searching and flightLists get populated with new data but the listview remain same with no items change, I don't know what I am doing wrong in above code, Please help me figure out this problem



via Chebli Mohamed

Android TV Emulater is Blank. How can I see apps like Google Play Store and others?

I have started new Android TV Emulator. But it shows nothing except settings and search icon. I am unable to open even Google Play to add more apps.

enter image description here

enter image description here



via Chebli Mohamed

When I do not use from a condition I can get the data from php, But when I use from a condition, I Can not get data from php

My php code is correct. But I have a strange problem when I use a condition in my code. My php code sends the "A" string from server to android. In the following code when I do not use a condition in my code in the GetText() method, I can get the A string and display it in the TextView well. But when I use a condition as follows, I can not get and display the A string in the TextView . Please help me. I do not know that where is this problem.

Pass = pass.getText().toString();

// Create data variable for sent values to server

String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(Name, "UTF-8");
    data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(Email, "UTF-8");
    data += "&" + URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(Login, "UTF-8");
    data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(Pass, "UTF-8");

String text = "";
BufferedReader reader = null;

// Send data
try{
   // Defined URL  where to send data
   URL url = new URL("http://ift.tt/1VTwxEV");

   // Send POST data request
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("POST");
   OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
   wr.write(data);
   wr.flush();

   // Get the server response

   reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String line = null;

   // Read Server Response
   while((line = reader.readLine()) != null){
       // Append server response in string
       sb.append(line);
    }

    text = sb.toString();
} catch(Exception ex){

} finally{
    try{
        reader.close();
    } catch(Exception ex){}
}

// Show response on activity
String A = "A";

if(text.equals(A)){
    content.setText(text); //it can not display the text in the TextView
}

}



via Chebli Mohamed

Android: HttpURLConnection redirects - probably cached

I have problem with HTTP calling, when I have multiple redirects and multiple calls. Lets have following code:

con = (HttpURLConnection) (new
URL("http://server/?function=auth/fetch_internal_ip")).openConnection();
HttpURLConnection.setFollowRedirects(false);
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.setConnectTimeout(1000);
con.setReadTimeout(1000);
con.connect(); StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null)
buffer.append(line).append("\r\n");
is.close();
con.disconnect();
is = null;
ip = buffer.toString().trim();

For first using works perfectly, but for any other in the future are not redirects followed. Only reinstall of app or restart phone helps.

Where could be a problem?



via Chebli Mohamed

Android Studio doesn't see Android processes

I apologize for my English.
I can't attach debugger to process, which I run on my device.
I'm selecting Run->Attach debugger to Android process. Then I check Show all processes in Choose process window, but the processes are not there. My device is identified correctly.

I'm also checking DDMS->Devices in Android Device Monitor. Processes are not there, although my device is identified correctly, and pie Chart on System Information tab display "CPU load" information about all device's processes.

I'm trying:

  • Restarting my Mac;
  • Restarting my device (I have Meizu M2 Note, Android 5.1(API 22);
  • Reenabling Settings->Developer Options->USB debugging on the device
  • Restarting adb by running adb kill-server and adb start-server

I use Android Studio 1.2.2.
I read the similar post Can't attach Android Studio's debugger to Android process, but my post a little about other. I can't see processes even in DDMS.

General problem is the following: I can't test In-app Purchasing. If I test it in debug-mode on my Mac, Google Play does not make a purchase. But if I install application as alpha-tester from Google Play, and run it on device, debugger can't see this application.
What I'm doing wrong?



via Chebli Mohamed

Voice recorder application not working

I created a voice recorder application I don't know why it crashes when I click record button.

public class MainActivity extends AppCompatActivity {

private static final String LOG_TAG = "Audio_recorder_basic";
private MediaRecorder recorder = null;
private String path = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void startRec(View view){
    String status = Environment.getExternalStorageState();
    if(status.equals("mounted")){
        path = Environment.getExternalStorageDirectory()+"/Seba/audiorecordtest.3gp";

        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(path);
        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(LOG_TAG, "prepare() failed");

        }
        recorder.start();
    }
    else{
        Toast.makeText(getApplicationContext(), "SD not mounted", Toast.LENGTH_LONG).show();
        Log.e(LOG_TAG, "SD not mounted");
    }


}
public void stopRec(View view){
    recorder.stop();
    recorder.release();
}

The app only has 2 buttons with android:onClick="startRec" android:onClick="stopRec"

It also has 3 permissions (write and record audio).

<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.example.audiorecbas.audio_recorder_basic" >

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

path variable extracted from logcat path = /storage/emulated/0/Seba/audiorecordtest.3gp

This is part of the message from Logcat:

    08-04 13:26:57.923    4216-4216/com.example.audiorecbas.audio_recorder_basic I/ViewRootImpl﹕ ViewRoot's Touch Event : ACTION_UP
08-04 13:26:57.941    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ java.io.IOException: open failed: ENOTDIR (Not a directory)
08-04 13:26:57.943    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.io.File.createNewFile(File.java:946)
08-04 13:26:57.943    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at com.example.audiorecbas.audio_recorder_basic.MainActivity.startRec(MainActivity.java:37)
08-04 13:26:57.943    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-04 13:26:57.943    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-04 13:26:57.944    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.view.View$1.onClick(View.java:3829)
08-04 13:26:57.944    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.view.View.performClick(View.java:4461)
08-04 13:26:57.944    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.view.View$PerformClick.run(View.java:18526)
08-04 13:26:57.944    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
08-04 13:26:57.945    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
08-04 13:26:57.945    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
08-04 13:26:57.945    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5103)
08-04 13:26:57.945    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-04 13:26:57.945    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-04 13:26:57.945    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
08-04 13:26:57.947    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
08-04 13:26:57.947    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
08-04 13:26:57.947    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: ENOTDIR (Not a directory)
08-04 13:26:57.948    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-04 13:26:57.948    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-04 13:26:57.949    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.io.File.createNewFile(File.java:939)
08-04 13:26:57.949    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ ... 15 more
08-04 13:26:57.949    4216-4216/com.example.audiorecbas.audio_recorder_basic E/Audio_recorder_basic﹕ create new file failed
08-04 13:26:57.949    4216-4216/com.example.audiorecbas.audio_recorder_basic E/Audio_recorder_basic﹕ /storage/emulated/0/Seba/audiorecordtest.3gp
08-04 13:26:57.977    4216-4216/com.example.audiorecbas.audio_recorder_basic V/MediaProfiles﹕ getInstance
08-04 13:26:57.977    4216-4216/com.example.audiorecbas.audio_recorder_basic V/MediaProfiles﹕ getLgeCamcorderCapParamByName: LgeCamcorderCap.audiozoomenable
08-04 13:26:57.977    4216-4216/com.example.audiorecbas.audio_recorder_basic E/MediaProfiles﹕ The mLgeCamcorderCap is not created, then return -1
08-04 13:26:57.977    4216-4216/com.example.audiorecbas.audio_recorder_basic D/MediaRecorder﹕ mAudioZoomEnable = -1
08-04 13:26:57.981    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ java.io.FileNotFoundException: /storage/emulated/0/Seba/audiorecordtest.3gp: open failed: ENOTDIR (Not a directory)
08-04 13:26:57.984    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:458)
08-04 13:26:57.985    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
08-04 13:26:57.985    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
08-04 13:26:57.985    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.io.FileOutputStream.<init>(FileOutputStream.java:117)
08-04 13:26:57.985    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.media.MediaRecorder.prepare(MediaRecorder.java:768)
08-04 13:26:57.985    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at com.example.audiorecbas.audio_recorder_basic.MainActivity.startRec(MainActivity.java:51)
08-04 13:26:57.985    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-04 13:26:57.986    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-04 13:26:57.986    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.view.View$1.onClick(View.java:3829)
08-04 13:26:57.986    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.view.View.performClick(View.java:4461)
08-04 13:26:57.986    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.view.View$PerformClick.run(View.java:18526)
08-04 13:26:57.986    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
08-04 13:26:57.987    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
08-04 13:26:57.987    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
08-04 13:26:57.987    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5103)
08-04 13:26:57.987    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-04 13:26:57.987    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-04 13:26:57.987    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
08-04 13:26:57.988    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
08-04 13:26:57.988    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
08-04 13:26:57.988    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: ENOTDIR (Not a directory)
08-04 13:26:57.989    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-04 13:26:57.989    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-04 13:26:57.990    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:442)
08-04 13:26:57.990    4216-4216/com.example.audiorecbas.audio_recorder_basic W/System.err﹕ ... 19 more
08-04 13:26:57.990    4216-4216/com.example.audiorecbas.audio_recorder_basic E/Audio_recorder_basic﹕ prepare() failed
08-04 13:26:57.997    4216-4216/com.example.audiorecbas.audio_recorder_basic E/MediaRecorder﹕ start called in an invalid state: 4
08-04 13:26:58.001    4216-4216/com.example.audiorecbas.audio_recorder_basic D/AndroidRuntime﹕ Shutting down VM
08-04 13:26:58.001    4216-4216/com.example.audiorecbas.audio_recorder_basic W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41d41d58)
08-04 13:26:58.004    4216-4216/com.example.audiorecbas.audio_recorder_basic E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.audiorecbas.audio_recorder_basic, PID: 4216
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:3834)

I use LG L50 for development.



via Chebli Mohamed

Date not printing correct Time Android

I want to print the Time (hours:minutes:seconds) from a date gotten from a String.

I have a string with the next value:

String dateStr = "Tue, 04 Aug 2015 12:09:10 GMT"

I parse it to a Date:

SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
Date d = format.parse(dateStr);

But when I try to get the hours, minutes and seconds, I get a different value:

System.out.println("The current time is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());

Prints: "The current time is: 9:9:10"

Whats wrong? Shouldn't print "The current time is: 12:9:10"?

Thanks :)


More information:

When I create the Date, it automatically sets the Timezone to GMT-03:00 2015, and that's why is printing 3 hours less. How can I set the timezone?



via Chebli Mohamed

Create PreferenceDialog onClick on filter popup?

My goal is to implement the image below.

How to create a PreferenceDialog if the filter icon in my toolbar has been clicked?

I want to set some preferences to filter the entries of my list.

I'm at this point. Is that the right way to implement this?

enter image description here



via Chebli Mohamed

Cordova Android opening in browser

I have an application that I built using Cordova. I'm running into an issue where my login page opens correctly in the app but then when they click "login" the next page opens in Chrome on an Android device. I tested this on an iOS device as well and it works correctly: The second page opens in the app, not Safari. I couldn't find any threads that solve this issue so I was wondering if I'm missing something.

The code I'm using for the login is:

window.location = returnUrl;

Where returnUrl = the new url if the login is successful.

I also tried window.open(returnUrl, '_self'); which didn't work either.

Any help would be appreciated!



via Chebli Mohamed

Android LinearLayout items overlap each other when one changes visibillity properties

I have a view with a LinearLayout which contains a bunch of items to show. In initialization code I add these items into layout.

for(int i = 0; i < n; i++) {
    View view = new SwitchButton(mTexts.get(i));
    mLinearLayout.add(view);
}

On top of this LinearLayout I have a TabLayout with several tabs. Whenever a user switches to another tab I set visibility property to each item in the layout according to to a specific tab.

@Override
public void onTabSelected(Tab tab) {
    if (tab.getPosition() != mLastSelectedTab) {
        for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
            View item = mLinearLayout.getChildAt(i);
            if (isVisibleInTab(tab.getPosition(), i) {
                 item.setVisibility(View.VISIBLE);
            } else {
                 item.setVisibility(View.GONE);
            }
        }
    }
}

But when a user changes tab for a short period of time linear layout items overlap one another. Even if I set

android:animateLayoutChanges="true"

in my layout, overlapping still occurs.



via Chebli Mohamed

i only get google analytics data from devices that run android 5.0 lolipop

I only get google analytics data from devices that run android 5.0 lolipop but not for other android devices which do work well with my app.

I'm using android studio. I compiled the app with play services 7.5.0.

com.google.android.gms:play-services:7.5.0

My min-sdk is API 9.

Everything is working fine except that from android versions below 5.0 (lollipop) i don't receive any data in analytics..

Please help me..



via Chebli Mohamed

FileNotFoundException when calling getContentResolver().openInputStream

I am getting following stacktrace when trying to call openInputStream:

java.io.FileNotFoundException
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:691)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1080)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:921)
at android.content.ContentResolver.openInputStream(ContentResolver.java:646)

But the problem does occur only in special situation. As shown in the following Screenshot, it only fails in the very first "Box"-option (red marker) - everything else is working perfectly fine, Google Drive, internal storage, Box from the bottom selection (marked green).

enter image description here

The code for the ACTION_GET_CONTENT-intent:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, PICKFILE_RESULT_CODE);

This intent returns following URI after selecting a file:

content://com.box.android.documents/document/file%2C33633304153

When I call getContentResolver().openInputStream(uri) in onActivityResult I get the above shown stracktrace.

Any ideas whats going wrong?



via Chebli Mohamed

How to increment and decrements the value of the count inside on click listener in getChildView() of Expandable list view adapter?

I am having two buttons in the child view of expandable list view "minus" and "plus".I just need to increase the count of the variable (say int count=0). if I keep this variable on global of the adapter it will take the same count for all child of the group item. then I kept the variable inside the getChildView() as a local variable,Increment or decrements of the count can be done inside the on click listener of the two buttons minus and plus respectively and obviously changed the variable into final. And we know that final variable values cannot be changed.

I am too confused how to do this,is there any best way to do which I am not aware of here is my code. Expandable list view Adapter class:

get child view method:

 public View getChildView(int groupPosition,  int childPosition,
          boolean isLastChild, View convertView, ViewGroup parent) {

  ExChildModel model=(ExChildModel) getChild(groupPosition, childPosition);

  if (convertView == null) {
      convertView = inf.inflate(R.layout.pro_items, null);
  }

  RelativeLayout rl_main=(RelativeLayout)convertView.findViewById(R.id.rl_main);
  RelativeLayout rl_color=(RelativeLayout)convertView.findViewById(R.id.rl_color);
  LinearLayout ll_text=(LinearLayout)convertView.findViewById(R.id.ll_text);
  LinearLayout ll_add=(LinearLayout)convertView.findViewById(R.id.ll_add);
  TextView tv_subtitle=(TextView)convertView.findViewById(R.id.tv_subtitle);
  TextView tv_sub=(TextView)convertView.findViewById(R.id.tv_sub);
  final TextView tv_cost=(TextView)convertView.findViewById(R.id.tv_cost);
  final TextView tv_number=(TextView)convertView.findViewById(R.id.tv_number);
  ImageView iv_minus=(ImageView)convertView.findViewById(R.id.iv_minus);
  ImageView iv_plus=(ImageView)convertView.findViewById(R.id.iv_plus);

  tv_subtitle.setTypeface(gotham_book);
  tv_sub.setTypeface(gotham_light);
  tv_cost.setTypeface(gotham_book);
  tv_number.setTypeface(gotham_book);

  tv_subtitle.setText(model.getHeader());
  tv_sub.setText(model.getDescription());
  tv_cost.setText(Constants.currency+model.getPrice());


  final int price=Integer.parseInt(model.getPrice());


  iv_minus.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
                    if (count!=0) {
            count--;
            tv_number.setText(String.valueOf(count));
            FragmentMenu.tv_count.setText(String.valueOf(count));
            int total=count*price;
            FragmentMenu.tv_cart_money.setText(Constants.currency+String.valueOf(total));

        }else {
            FragmentMenu.tv_count.setVisibility(View.INVISIBLE);
            FragmentMenu.tv_cart_money.setText(Constants.currency+"0");
        }
    }
});

  iv_plus.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (count>=0&&count!=99) {
            count++;
            tv_number.setText(String.valueOf(count));
            FragmentMenu.tv_count.setVisibility(View.VISIBLE);
            FragmentMenu.tv_count.setText(String.valueOf(count));
            int total=count*price;
            FragmentMenu.tv_cart_money.setText(Constants.currency+String.valueOf(total));
        }
    }
});

  return convertView;
  }



via Chebli Mohamed

How to display total duration and current position of video in MediaController in android?

I am writing Android app, which plays HLS stream. I need to implement MediaController, that can seek video. On seeking my program must calculate timestamp, get new stream URL from server and then refresh MediaPlayer. I implemented interface MediaController.MediaPlayerControl with my own getDuration() and getCurrentPosition(). For now it's only static values. But these methods take effect only with SeekBar, but nothing with labels (always 00:00):

enter image description here

I didn't implement SeekBar functionality yet. Firstly I'd like to understand how to setup labels duration on MediaController. How do it properly?



via Chebli Mohamed

saving programatically generated value of edittext in a static class

I have an edittext field in a tab which is given a unique autogenerated value when the activity is created. I want this value passed to a static class as soon as the value is put in the edittext so that on switching tabs, the value can be called from the static class. My problem is i tried saving the value to the static class using the following code:

 invoiceNo.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            //GlobalApp.data().id = invoiceNo.getText().toString();
        }

        public void beforeTextChanged(CharSequence s, int a, int b, int c){
            GlobalApp.data().id = invoiceNo.getText().toString();
        }

         public void onTextChanged(CharSequence s, int a, int b, int c){
            // GlobalApp.data().id = invoiceNo.getText().toString();
         }
        }

But it kept changing whenever the user returns to the 1st tab (where the value is generated) or it would not be displayed at all. I want it to save the generated value once irrespective of whether user returns to the 1st Tab.

public class clientFragmentTab  extends Fragment  {

ArrayList<String> saleRecord;
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
EditText currDate, invoiceNo , vehicle,territory ;
//Spinner clientName, territory;
View rootView = null;
int invoice_id = 0;
String invoice_no;
public String[] item = new String[] {"Please search..."};
public String territory1;
CustomAutoCompleteView myAutoComplete;
ProductsDbHelper db;

// adapter for auto-complete
ArrayAdapter<String> myAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.client_layout, container, false);



    return rootView;
}

public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    myAutoComplete = (CustomAutoCompleteView) rootView.findViewById(R.id.myautocomplete);

    // add the listener so it will tries to suggest while the user types
    myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this, getActivity()));

    db = new ProductsDbHelper(getActivity());
    // set our adapter
    myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, item);
    myAutoComplete.setAdapter(myAdapter);
    currDate = (EditText) rootView.findViewById(R.id.editText4);
    //clientName = (Spinner) rootView.findViewById(R.id.spinner);
    invoiceNo = (EditText) rootView.findViewById(R.id.editText3);
    vehicle = (EditText) rootView.findViewById(R.id.editText6);
    territory = (EditText) rootView.findViewById(R.id.editText9);invoice_id = UniqueRandomNumbers();


    invoice_no = "invoice_" + invoice_id;

    currDate.setText(formattedDate);
    invoiceNo.setText(invoice_no);




    //List<String> list = new ArrayList<String>();
    //list.add("Select Client");
    //list.add("Item 2");
    //list.add("Item 3");
    //list.add("Item 4");
    //list.add("Item 5");

    //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_dropdown_item , list);
    //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    //clientName.setAdapter(adapter);





   // if(invoiceNo.getText().toString() != ""){

   // }

    invoiceNo.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            //GlobalApp.data().id = invoiceNo.getText().toString();
        }

        public void beforeTextChanged(CharSequence s, int a, int b, int c){
            GlobalApp.data().id = invoiceNo.getText().toString();
        }

         public void onTextChanged(CharSequence s, int a, int b, int c){
            // GlobalApp.data().id = invoiceNo.getText().toString();
         }
        }

        );
}



via Chebli Mohamed

Get online current date and time without using Apis [duplicate]

This question already has an answer here:

Apis usually let you get limited free requests, so I am looking for an alternative to get current Date and Time always I want (online one, not from the System/device), without restrictions and free. Ofcourse, must be trusted and confident responses (is useless to get wrong or outdate responses, or unavailable requests)



via Chebli Mohamed

How to Authenticate with Alexa Voice Service from Android?

I am trying to connect to Alexa Voice Service from and Android app following the directions on this page. http://ift.tt/1Ujv5tz

Bundle options = new Bundle();
String scope_data = "{\"alexa:all\":{\"productID\":\"" + PRODUCT_ID +
                    "\", \"productInstanceAttributes\":           {\"deviceSerialNumber\":\"" + PRODUCT_DSN + "\"}}}";
options.putString(AuthzConstants.BUNDLE_KEY.SCOPE_DATA.val, scope_data);
options.putBoolean(AuthzConstants.BUNDLE_KEY.GET_AUTH_CODE.val, true);
options.putString(AuthzConstants.BUNDLE_KEY.CODE_CHALLENGE.val, CODE_CHALLENGE);
options.putString(AuthzConstants.BUNDLE_KEY.CODE_CHALLENGE_METHOD.val, "S256");
mAuthManager.authorize(APP_SCOPES, options, new AuthorizeListener());

First, I don't know what APP_SCOPES should be. I set it to:

protected static final String[] APP_SCOPE = new String[]{"profile", "postal_code"};

but I get an error from the server

AuthError cat= INTERNAL type=ERROR_SERVER_REPSONSE - com.amazon.identity.auth.device.AuthError: Error=invalid_scope error_description=An unknown scope was requested



via Chebli Mohamed

ArrayList return size() zero

mNewList return size() zero but it contains data that it show in ListView, mListData.getContacts(); returns ArrayList fetched from server via internet but its not a problem as i written before it shows data in ListView.

ArrayList<String> mNewList = new ArrayList<String>();
mNewList = mListData.getContacts();
Log.i("ShowingListSize", ":" +mNewList.size());

adapter = new ArrayAdapter<String>(MainActivity.this, 
android.R.layout.simple_list_item_1, mNewList);
mList.setAdapter(adapter);



via Chebli Mohamed

Android gallery scrolling issue

When image gallery is wider than screen and I scroll it - images is re-loading all the time.

public class ImageAdapter extends BaseAdapter {
.....
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null){
            holder = new ViewHolder();
            convertView = getLayoutInflater().inflate(R.layout.gallery_item, parent, false);
            holder.imageView = (ImageView) convertView.findViewById(R.id.ivGalleryItem);
            convertView.setTag(holder);
        } 
        else 
        {
            holder = (ViewHolder) convertView.getTag();
        } 
         ....
         Ion.with(context)
            .load(holder.imagePath)
            .withBitmap()
            .intoImageView(imageView);  
    }
 }          

I asume Ion is caching image by default but gallery still hide and show it during scrolling.

So, where is my problem an d how to fix?



via Chebli Mohamed

How to remove space between Tokens?

I am using TokenAutoComplete library for my app. I need to remove the space between tokens. How can I achieve this?

Thanks.



via Chebli Mohamed

Proper navigation between activities using navigation drawer and back button?

I have the following situation:

One Main ListActivity. The list consists of POJO objects, each item is a different POJO.

Each POJO contains different groups. For each group I made different Activity.

Lets say POJO1 contains groups A, B and C, when pressed, ActivityA will be opened and the navigation between the rest activities ActivityB and ActivityC is done using NavigationDrawer.

All group activities implement a custom class MyNavigationDrawerClass which is the core of the Navigation Drawer in my app.

Each ActivityA, B, C, etc, has a SettingsActivity which is strictly individual and depends on from where it has been started.

Now the question is: How to navigate from any A, B, C, etc, activity to the Main ListActivity every time the BackButton is pressed?

I will provide an example:

  1. App is started - Main List Activity is showed;
  2. Item is pressed and ActivityA with NavigationDrawer is started;
  3. The NavigationDrawer is opened and ActivityC is opened;
  4. When BackButton is pressed, the user is navigated back to ActivityA, but my desire is to navigate the user to the Main List Activity

What I tried:

  1. To put android:noHistory="true" for every ActivityA, ActivityB and ActivityC in the AndroidManifest. That did not work because when I open the SettingsActivity for example from ActivityA and return, the user in navigated to the Main List Activity, and not to the ActivityA - it's confusing and misleading.
  2. To override onBackPressed in MyNavigationDrawerClass and start the Main List Activity using Intent. That did not work either because there are still previous activities in the stack and when the BackButton is pressed from Main List Activity, the user is navigated to them.

I hope I explained the situation clearly.

Any help will be appreciated.



via Chebli Mohamed

maintaining a Back stack for fragments as well as confirm on exit

I am actually working on fragments instead of activities .So on navigation drawer item click different fragments appear on the screen.Based on my code, if i am moving from Activity A to fragment b,then fragment c,again to b,then if i will click back button,then it will navigate me to the MainActivity A.But here is the problem.when i want to add confirm on exit dialog box on the MainActivity onBackPress(),it appears every time i click the back button regardless of which page is open,But i want it to appear only when there is no fragments left in the back stack.I need some help on that issue.

    Here is my MainActivity code:--

    package archerpenny.impdrawerfragment;


import android.content.DialogInterface;
import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;

import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

import android.view.MenuItem;

import android.view.View;


public class MainActivity extends AppCompatActivity  {
    ActionBarDrawerToggle mDrawerToggle;
    RecyclerView.Adapter mAdapter;
    RecyclerView recyclerView;
    DrawerLayout mDrawerLayout;
    FragmentManager fragmentManager;
    Fragment blankFragment=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAdapter = new NavigationDrawerAdapter(this);
        mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        NavigationDrawerAdapter adapter;

        recyclerView = (RecyclerView)findViewById(R.id.DrawerList);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(llm);
        recyclerView.setAdapter(mAdapter);

        getSupportActionBar().setDisplayShowTitleEnabled(false);

        mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.open,R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        // do whatever

                        if(position==0)
                        {
                            blankFragment=new BlankFragment();

                        }
                        if (position==1)
                        {
                            blankFragment=new BlankFragment2();
                        }
                        if (position==2)
                        {
                            blankFragment=new BlankFragment3();
                        }
                        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                        getSupportFragmentManager().popBackStack();
                        fragmentManager.beginTransaction()
                                .add(R.id.container_body, blankFragment).addToBackStack("fragBack").commit();
                        mDrawerLayout.closeDrawers();
                    }
                })
        );
    }
    @Override
    public void onBackPressed() {
        if(getSupportFragmentManager().findFragmentByTag("fragBack") != null)
        {
            getSupportFragmentManager().popBackStack();
            getSupportFragmentManager().beginTransaction().add(R.id.container_body, blankFragment).addToBackStack("fragBack").commit();
        }
        else {
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Closing Activity")
                    .setMessage("Are you sure you want to close this activity?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }

                    })
                    .setNegativeButton("No", null)
                    .show();



        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}



via Chebli Mohamed

Drawing large set of circles on canvas, fast way

I'm working on a live wallpaper for Android, this involves drawing a lot of circular shapes with the canvas.drawCircle() method. So there is an algorithm that computes the radius of every circle, its color etc. and for each circle I use drawCircle() to draw it. Problem is, it's painfully slow. Question is, any suggestion on how to improve my code? Maybe doing some kind of bulk drawing in one single step instead of calling drawCircle() many times? OpenGL could help?

Thanks a lot

Thanks



via Chebli Mohamed

My QR reader without Google ZXing installed

Basing on this tutorial, I made an app for reading QR codes. However, this app requires com.google.zxing.client.android installed. Is there any way to add this package to my app so that I won't have to install Google reader? I found com.google.zxing package at Maven but id didn't contain necessary components.



via Chebli Mohamed

Android studio Facebook - How to get full friends list

How do I get the full friend list of a person, using Android Studio and Facebook SDK 4.4.+. I have looked for tutorials everywhere but they are all out dated. I just need a simple code without installing any new libraries and I need some more explanation with the code



via Chebli Mohamed

android material design issue

i am trying to solve a issue for last 1 week. i am not sure what is wrong with the code. i am trying to use this library http://ift.tt/1zlyuAU

I can able to compile and run the code

the issue is ,there is big difference in the displayfirst screen shot was take from my working code and second one i downloaded from play store. quality

clearly we can notice the font is completely not matching.

please help me to resolve this.



via Chebli Mohamed

TextView android is not displayed in the view

I am having a problem with an item in the view of my activity. I have the following item:

<TextView android:id="@+id/numero_asiento_alert"
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:text="@string/msg_numero_alert"
                android:textColor="@color/result_minor_text"
                android:textStyle="bold"
                android:layout_marginLeft="25dip"
                android:paddingRight="4dip"
                android:textSize="22sp"/>

In one of the functions of my activity I have the following code:

if(!inscripcion.getAsiento().equals("") && !inscripcion.getAsiento().equals("null")){
    asientoTextView = (TextView) findViewById(R.id.numero_asiento_alert);
    asientoTextView.setVisibility(View.VISIBLE);
    asientoTextView.setText("Asiento: "+inscripcion.getAsiento());
    System.out.println("Asiento "+asientoTextView.toString()+" "+asientoTextView.getText());
}else{
    asientoTextView = (TextView) findViewById(R.id.numero_asiento_alert);
    asientoTextView.setText("");
}

Output :

08-04 10:50:44.537: I/System.out(6750): Asiento android.widget.TextView{418e3140 V.ED.... ......I. 0,0-0,0 #7f090050 app:id/numero_asiento_alert} Asiento: Fila B - Asiento 4

I thought the value was not getting is why I printed that contained my element TextView and effectively if it has the values seteo but the view is not shown, being the'm visibility by setting properly. It happens with this and 2 more elements, whereas in others there is no error.



via Chebli Mohamed

Draw circle countdown with the libgdx

I am prety new on LibGDX,and trying to create a circle which shows the remaning time of the game.For that purpose I find this called RadialSprite,but dont know how to apply it. what I have treid so far like this.

@Override
    public void render(float delta) {
        // TODO Auto-generated method stub

         Texture txturecircle = new Texture(Gdx.files.internal("circle.png"));;

         TextureRegion regions= new TextureRegion(txturecircle);
         RadialSprite rd=new RadialSprite(regions);

        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        batch.begin();

        rd.draw(batch, 100, 10,0);
        batch.end();   
        stage.draw();
        stage.setDebugAll(true);


    }

My update function which create images again depents on the remaning time of the game.

int time = 0;
    @Override
    public void show() {
        // TODO Auto-generated method stub
        com.badlogic.gdx.utils.Timer.schedule(new Task() {

                    @Override
                    public void run() {
                       DrawTimer();

                    }
                }, 1,1);
    }
    private void DrawTimer() {
         Texture txturecircle = new Texture(Gdx.files.internal("circle.png"));;

         TextureRegion regions= new TextureRegion(txturecircle);
         RadialSprite rd=new RadialSprite(regions);
        Log.d("tımer",String.valueOf(time));
        batch.begin();
        time++;
        rd.draw(batch, 90, 110, 36*time);
        batch.end();

    }

**Iam trying to do something like this. enter image description here

any help or direction wellcome



via Chebli Mohamed

Dynamically add ImageButtons

I have to dynamically create ImageButtons for an Array of images after a network call is completed. I currently have it working with the amount of buttons hardcoded, but the amount of buttons will be dynamically added and removed on the server.

The XML Code is below this works as its hardcoded:

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
          xmlns:tools="http://ift.tt/LrGmb4"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="horizontal"
          android:weightSum="1"
          tools:background="@color/black"
android:id="@+id/dotw_list">

<ImageButton
    android:id="@+id/dotw_imageButton_1"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:adjustViewBounds="false"
    android:background="@drawable/layout_bg"
    android:padding="5dp"
    android:scaleType="centerInside"/>

<ImageButton
    android:id="@+id/dotw_imageButton_2"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:adjustViewBounds="false"
    android:background="@drawable/layout_bg"
    android:padding="10dp"
    android:scaleType="centerInside"/>

<ImageButton
    android:id="@+id/dotw_imageButton_3"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:adjustViewBounds="false"
    android:background="@drawable/layout_bg"
    android:padding="10dp"
    android:scaleType="centerInside"/>

<ImageButton
    android:id="@+id/dotw_imageButton_4"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:adjustViewBounds="false"
    android:background="@drawable/layout_bg"
    android:padding="10dp"
    android:scaleType="centerInside"/>

<ImageButton
    android:id="@+id/dotw_imageButton_5"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:adjustViewBounds="false"
    android:background="@drawable/layout_bg"
    android:padding="10dp"
    android:scaleType="centerInside"/>
</LinearLayout>

Below is the code I have used to hard code it but i need this to be dynamically changed when there are more/less items in the Array

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    // Get extra data included in the Intent
    String message = intent.getStringExtra("network_response");
    Log.d("receiver", "Got message: " + message);

    home = data.getHomeItem();


    try {
        for (int i = 0; i < home.dotwItemArray.size(); i++) {
            System.out.println("Size of DOTW Array for the home screen is " + home.dotwItemArray.size());

            DotwItem dotwItem = home.dotwItemArray.get(i);

            if (i == 0) {
                request.getImage(dotwItem.getThumbnailImageUrl(), button_dotw_1);
                System.out.println("dotwItem1 is set");
            }
            if (i == 1) {
                request.getImage(dotwItem.getThumbnailImageUrl(), button_dotw_2);
                System.out.println("dotwItem2 is set");
            }
            if (i == 2) {
                request.getImage(dotwItem.getThumbnailImageUrl(), button_dotw_3);
                System.out.println("dotwItem3 is set");
            }
            if (i == 3) {
                request.getImage(dotwItem.getThumbnailImageUrl(), button_dotw_4);
                System.out.println("dotwItem4 is set");
            }
        }

    } catch (Exception e) {
        System.out.println("Error is: " + e + " - Exception is it: " + e.getStackTrace()[2].getLineNumber());

    }
}
};

The reason I am doing this, is because I dont know the length of the Array that I am getting until the network call is complete. The network call is initiated in the onCreate method and as you can see this is in the onReceive method, this method is initiated once the network call is completed.

I had a look at this link from StackOverflow but Im a little confused as I am trying to set the image based on the network request.

Thanks



via Chebli Mohamed

while running ionic build android iam getting error You may not have the required environment or OS to build this project

I'm developping an angularjs/ionic mobile application.

While running 'ionic build android' on CLI, I'm getting this error:

ERROR building one of the platforms:
Error: C:\Users\Username\FirstProject\platforms\android\cordova\build.bat:
Command failed with exit code 2
You may not have the required environment or OS to build this project

I updated my android SDK Tools to 24.3.3 but I'm getting the same error.



via Chebli Mohamed

scroll view content size

I have a ScrollView and I set a large image of tree on ScrollView and set the 15 ImageView of every branch using RelativeLayout.

My problem is when getting image only 10 then ImageView should only visible 10 and other 5 should be hide. 1 to 10 image view should display bottom of screen one by one and scroll view only scroll up should not down after 10 image view.

Right now for example, if get 8 for 8 ImageViews display in bottom of screen and if get 6 for 6 image view display in bottom and after all 7th 8th is hidden in bottom of screen but its is scrolling. which must be stop.

Here is my code:

    Display display = getWindowManager().getDefaultDisplay();
    final int height = display.getHeight();  //get screen height 
    // Log.e("width , hight od screen",""+height);
    Rect r=locateView(finalViewList.get(finalViewList.size()-1)); // get               image position on scroll view
    final int touchY = (r.bottom);
    lastPos = touchY - height;  //
    scview.scrollTo(0, lastPos); //set scroll view

Scroll is set in bottom starting from 10th ImageView but ScrollView is scrolling down and can show empty 11th image view. Suppose I hide eleven ImageViews then the empty branch is showing, which should not show.



via Chebli Mohamed

Android SDK: exception when using array adapter and listView

This is my activity class

package com.example.list1;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    private ListView listView1;
    private ArrayAdapter<String> listAdapter1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        // Create an object of type ArrayList from an array of strings
        String[] someColors = new String[] { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet", "Black", "White"};
        ArrayList<String> colorArrayList = new ArrayList<String>();
        colorArrayList.addAll( Arrays.asList(someColors) );

        // Use values from colorArraylist as values for each text1 'sbuView' used by the listView
        listAdapter1 = new ArrayAdapter<String>(this, android.R.id.text1, colorArrayList);


        // Tell to the listView to take data and layout from our adapter
        listView1 = (ListView) findViewById(R.id.listView1);        
        listView1.setAdapter( listAdapter1 );

    }
}

And this is my layout file

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.list1.MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" >

    </ListView>   

</RelativeLayout>

When I save, Eclipse give me no problem. When I run the app crash and from logcat I can see an exception that i'm not able to understand/debug

08-04 13:43:34.382: E/AndroidRuntime(888):  
android.content.res.Resources$NotFoundException: File  from xml type layout resource ID #0x1020014

What am I doing wrong?



via Chebli Mohamed

Web notifications only work in Firefox

I have this extremely simple code to test the functionality

Notification.requestPermission();
new Notification("DGD");

I opened this on 2 devices with Firefox, Chrome, Opera and android browser (7 browsers total), it worked on firefox on both devices and none of the other browsers. Refreshed about a million times and cleared all caches and data. Looking at the browser compatibility it should be working on those browsers (latest versions).

Do you spot where the problem is?



via Chebli Mohamed

Is it possible to remove a particular app in chooser while opening a URL?

My own app contains an intent filter which accepts a URL of "https:www.xyz.com"

While opening a particular URL from my own app, for example "https:www.xyz.com/signup", it gives an option of my app also in chooser, but for this particular URL, I want to open it in browser only.

Please suggest me a proper way exclude my own app from default chooser list of android.

Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("https:www.xyz.com/signup"));
                    startActivity(Intent.createChooser(browserIntent, "Open with"));



via Chebli Mohamed

How to prevent websites header and footer in android app

I have a website which is built using WordPress, now I want to make an android app which will use this website. I want the header/footer to be dynamic as follows:

User access     | header displayed?
app             | no
android browser | yes

Any idea or suggestions how to do it? Is there any WordPress, android or JavaScript plugin which I can use?



via Chebli Mohamed

Good strategy to debug this?

Android (4.2.2) application developed in Java on Eclipse, I'm getting a crash but I can't figure out what in my code is causing it . . .

The stack trace doesn't reference any of my own source code . . .

Thread [<1> main] (Suspended (exception RuntimeException))
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2255
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2309 ActivityThread.access$700(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 157
ActivityThread$H.handleMessage(Message) line: 1289
ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 176 ActivityThread.main(String[]) line: 5317
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 511 ZygoteInit$MethodAndArgsCaller.run() line: 1102 ZygoteInit.main(String[]) line: 869 NativeStart.main(String[]) line: not available [native method]

... I launch several activities in my app and all of them are wrapped in a try/catch but if I set breakpoints in the catch blocks they aren't being hit, and if I step over the code that launches the Activities nothing seems amiss. Nor is the system writing anything to Logcat indicating any exceptions (no filters on Logcat, full Verbose output).

Clicking on the above lines just gives me "source not found". Is there a way to see what Activity it's trying to start or what the nature of the exception is?



via Chebli Mohamed

photos/videos updating in android app, looking for the best solution

I'm currently developing an android application, i almost finished but I can not publish it actually because i had a problem. Here is the thing. One of the functionalities of the app is that the users can take photos/videos and upload it so other users can see them. Since i'm using parse as backend, I've started with that but the problem is that the uploading is taking about 4/5minutes which is huge! after asking for solution in parse forum, it seems that there isn't. I'm actually thinking that the cause of the issue is that i'm using it from Morocco(couldn't found any other possible issue). So that's why today i'm looking for another solution, i'm actually thinking about sqlite. But the advantage i had had with Parse is the online maintainability. Since the uploading things from users needed an admin validity to be published, it was quite easy to deal with it! now with sqlite it's quite complex since the database's inserts cannot be inspected and updated outside of the app.. Please let me know what you think about the best way to deal with this, hope that I was clear, my English is not perfect. Thank you !



via Chebli Mohamed

Android move view to a touched position

I'm trying to develop an android application similar to "on color measurement" or "color grab" which are already on google play. I have problem with getting the exact position of a view (which acts like focus square) and move it to the position where the user touches the screen. I have done a lot of searches but all of them ended in onTouchEvent() which I used it but it does not work properly or maybe I have done something wrong. Actually the view moves but it won't be placed exactly where the user touch, it will go below the touched area in y axis with a distance.

here is my code where the mFocusRectangle is the custom view which I want to move to the touched position:

@Override
public boolean onTouchEvent(MotionEvent event) {

    int action = event.getAction();
if (event.getPointerCount() > 1) {
        // handle multi-touch events

    } else {
        // handle single touch events
        if(action==MotionEvent.ACTION_DOWN){

        }
        if (action == MotionEvent.ACTION_UP) {
            int pointerId = event.getPointerId(0);
            int pointerIndex = event.findPointerIndex(pointerId);
            // Get the pointer's current position
            float x = event.getX(pointerIndex);
            float y = event.getY(pointerIndex);
            mFocusRectangle.showStart();
            mFocusRectangle.setX(x);
            mFocusRectangle.setY(y);

        }
    }
    return true;
}

I have also tried MotionEvent.ACTION_DOWN but the result is the same. Thanks in advance.



via Chebli Mohamed

Closing application after pressing back button, not returning to previous activity

problem:

Working scenario: I have a MainMenuActivity and when i start another activity and press Back Button it return to previous activity,but...

Problem scenario: When I start Activity B, from Activity A, and then press Home button and i after few seconds back to application, and then press Back button application is closed/minimalized. But i want after minimalized application can go back to Activity A.

Any idea how to do it?



via Chebli Mohamed

Java passing className + object to generic method

So I'm complete lost in the part of generic method's. In Android java I want a MyDownloadHelper for downloading my JSON data which will be returned next. Got this working in 2 seperate files with different class/object-names. However, I can't get this thing to work dynamicly. This is my current source.

The current situation will let me call the MySQLiteHelper.getRecipients(); in another activity and will me return the correct data. I am also using 2 classes (Pakbon, Recipient) for setting the correct data.

I think I'm pretty close to the solution but i really need a blow in the right direction. Thanks in advantage.

public class MyDownloadHelper {

private static final int timeout = 10000;
private  Class<? extends Object[]> cls;
private static final String API_SERVER = "http://www.***.nl/json/";
private Object[] obj;

public MyDownloadHelper(){
}

protected Recipient[] getRecipients() {
    try {
        //Recipient[] recipients = getInstance(Recipient[].class);
        Recipient[] recipients   = this.download(Recipient[].class, API_SERVER + "getRecipients");
        return recipients;
    } finally {
        return null;
    }
}

protected Pakbon[] getPackingSlips() {
    try {
        Pakbon[] pakbon = this.download(Pakbon[].class, API_SERVER + "getPackingSlips");
        return pakbon;
    } finally {
        return null;
    }
}

private <T> Object[] download(Class<T> a, String url){
    HttpURLConnection c = null;

    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                Gson gson = new Gson();
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));

                Object[] objectData = gson.fromJson(br, a);
                return gson.fromJson(br, cls);

        }
    } catch (IOException ex) {

    } finally{
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }
    }



    return null;

}

}



via Chebli Mohamed

Does versionName have to be increasing?

I had uploaded these versions of my app to Google Play:

VersionCode             VersionName
       1                      1
       2                      2
       3                      3
       …
       15                     15

Now I plan to upload the version with

versionCode: 16
versionName: 1.6.1

Is this versionName allowed? (Or do I have to choose 16.1, so that versionNames are non-decreasing).



via Chebli Mohamed

How to prevent item reordering in StaggeredGridLayoutManager after orientation change?

I know this question sounds similar to others on StackOverflow but this is specifically about what happens after an orientation change.

I have an Activity with a Toolbar and a RecyclerView. I use a StaggeredGridLayoutManager with a vertical orientation and 3 columns to fill the RecyclerView. The item layout is a LinearLayout containing an ImageView and a TextView.

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/grid_item_margin"
android:orientation="vertical">

<ImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop" />

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dp"
    android:paddingTop="2dp" />
</LinearLayout>

The images are loaded from the web. I know the image sizes before the ViewHolders are bound. So I set the image height in onBindViewHolder to prevent item reordering and load the image via Picasso:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ViewGroup.LayoutParams lp = holder.imageView.getLayoutParams();
    lp.height = imageInfos.get(position).imageHeight;
    holder.imageView.setLayoutParams(lp);

    mPicasso.load(url)
        .noFade()
        .into(holder.imageView); // imageView scaleType=centerCrop
}

Let's say I have 50 items in my adapter. I am in portrait mode and scroll down 20 items. Then I change to landscape mode. I create a new StaggeredGridLayoutManager with 4 columns now, so one more than in portrait mode. I recalculate the image heights to fit the new target width and set the saved state on the layout like so:

ArrayList<ImageInfo> imageInfos = savedInstanceState
    .getParcelableArrayList(IMG_INFOS_KEY);
setNewImgTargetDimensions(imageInfos, columns);
mAdapter = new ImageGridAdapter(mPicasso, imageInfos);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(layoutMgr);
Parcelable sglmState = savedInstanceState
    .getParcelable(LAYOUT_MGR_STATE_KEY);
mRecyclerView.getLayoutManager()
    .onRestoreInstanceState(sglmState);

The grid automatically scrolls to the stored position which is desired. Now I scroll up. Because of the new image sizes the "space above the scrolled position" cannot be filled by the images entirely. So items get reordered but most of the time there is still a more or less big gap at the top of the grid (see screenshot links at the bottom). It is worst when I fling to the top. So is there a way to prevent the reordering and the gaps in this case?

portrait mode shows the screen when just loaded for the first time.

landscape mode shows the screen when scrolled up after the orientation change. The image on the left is almost transparent because of a custom fade in animation I guess. I removed that from the sample code to make it smaller.

Edit:

I just realized that all items are aligned at the top of the screen after the orientation change. Though that looks nice, I would prefer if the alignment at the very top of the recycler view was right.



via Chebli Mohamed

Android App using GPS connection stops working

I had trouble to get the speed of my Android device. So i tried to use a sample, wich should work. With the code from http://ift.tt/1ONb631 i should get the speed. But the app always crashes before connecting to GPS. The code is:

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;



public class MainActivity extends Activity {


    Context context;
   protected void onCreate(Bundle savedInstanceState)
    { super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.Geschwindigkeit);

        LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = newLocationListener(){ public void onLocationChanged(Location location) {

            location.getLatitude();

            Toast.makeText(context, "Current speed:" + location.getSpeed(), Toast.LENGTH_SHORT).show(); }

            public void onStatusChanged(String provider, int status, Bundle extras) { }

            public void onProviderEnabled(String provider) { }

            public void onProviderDisabled(String provider) { }
        };

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }
}

The log says the following:

08-04 14:36:51.023  11219-11219/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at android.widget.Toast.<init>(Toast.java:105)
        at android.widget.Toast.makeText(Toast.java:261)
        at test.gpsspeed.MainActivity$1.onLocationChanged(MainActivity.java:34)
        at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:257)
        at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:186)
        at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:202)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5365)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
        at dalvik.system.NativeStart.main(Native Method)

What can i do? Or what Am i doying wrong?



via Chebli Mohamed

Integrating multiple activity in android

I have a login activity and besides that,I have different activity like sharebuttonadapter,Socialauth Dialog,SocialauthError which are part of socialauthcode for logging through Facebook and twitter.But when I run the application I can see only the login page and not the different option through which I can login.

Please advise.

Mainfest File:-

package="com.example.abhisheksharma1.bridgeapps" >

To retrieve the account name (email) as part of sign-in: -->

auto-complete the email text field in the login form with the user's emails

-->

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

android:name=".LoginActivity"

android:label="@string/app_name"

android:windowSoftInputMode="adjustResize|stateHidden" >

android:name="com.google.android.gms.version"

android:value="@integer/google_play_services_version" />

android:name=".DialogListener"

android:label="@string/title_activity_dialog_listener" >

android:name=".PopUpListAdapter"

android:label="@string/title_activity_pop_up_list_adapter" >

android:name=".SocialAuthDialog"

android:label="@string/title_activity_social_auth_dialog" >

android:name=".SocialAuthError"

android:label="@string/title_activity_social_auth_error" >

android:name=".SocialAuthListener"

android:label="@string/title_activity_social_auth_listener" >

android:name=".Util"

android:label="@string/title_activity_util" >

android:name=".SocialButtonAdapter"

android:label="@string/title_activity_social_button_adapter" >

android:name=".SocialAuthAdapter"

android:label="@string/title_activity_social_auth_adapter" >``

android:name=".ShareButtonAdapter"

android:label="@string/title_activity_share_button_adapter" >



via Chebli Mohamed

SDK Manager : Error in opening

8:55:23 - SDK Manager] [SDK Manager] '"F:\ADT-BU~1\sdk\tools\lib\find_java64.exe" -s' is not recognized as an internal or external command, [2015-08-04 18:55:23 - SDK Manager] [SDK Manager] operable program or batch file.

I am getting the error when i click on the SDK Manager button in eclipse for android



via Chebli Mohamed

dimanche 28 juin 2015

using a session to show text for a specific group

This is a part of my session script:

$group='admin';

session_start();
header('Content-type: text/html;charset=UTF-8');
if(!isset($_SESSION['username']) and isset($_COOKIE['username'], $_COOKIE['password']))
{
  $cnn = mysql_query('select password,id,group from users where username="'.mysql_real_escape_string($_COOKIE['username']).'"');
  $dn_cnn = mysql_fetch_array($cnn);
  if(sha1($dn_cnn['password'])==$_COOKIE['password'] and mysql_num_rows($cnn)>0)
  {
    $_SESSION['username'] = $_COOKIE['username'];
    $_SESSION['userid'] = $dn_cnn['id'];
    $_SESSION['group'] = $dn_cnn['group'];
  }
}
?>

I want to show "blablabla" but only if you are in a group:

<?php
if(isset($_SESSION['group']) and $_SESSION['group']==$group)
{
?>
blablabla
 <?php 
 }
 ?>

In my table is a column named as "group". The group of this session is named as "admin" (that's why: $group='admin';) but it doesn't show the "blablabla".

Does someone know what I'm doing wrong?

Get th result depends on the stops names order

I have the following tables below. Is it possible to get the routeand the direction depend on the stops order to avoid the result of the opposite stop? So if I have the following stop's name order as Abc, Def, Ghi the result of my query should just consider alle routes which have this stops order Abc, Def, Ghi as I said to prevent the result of the opposite stop that has arrivale time too.

Tables:

CREATE TABLE IF NOT EXISTS routes (
                    route_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    direction VARCHAR(30) NOT NULL, 
                    route INT(11) NOT NULL )

CREATE TABLE IF NOT EXISTS stops
                    (stop_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, 
                     name varchar(30) NOT NULL, 
                    lat double(10,6) , 
                    longi double(10,6)  


CREATE TABLE IF NOT EXISTS arrivaltimes(arrivaltimes_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    weekday VARCHAR(20) NOT NULL,
                    route INT(11) NOT NULL, 
                    arrivaltime time NOT NULL,
                    stop_id INT, FOREIGN KEY fk_stop_id(stop_id) REFERENCES stops(stop_id), 
                    route_id INT, FOREIGN KEY fk_route_id(route_id) REFERENCES routes(route_id) 

Query:

SELECT r.route, r.direction FROM routes AS r 
            JOIN arrivaltimes AS a ON a.route_id = r.route_id 
            JOIN stops as s on a.stop_id = s.stop_id 
            WHERE a.weekday = ?
            AND arrivaltime between subtime(curtime(), '00:02:00') and addtime(curtime(), '00:02:00')
            AND s.name = ?

Database connectivity issue

I am trying to connect do database to store the data, but its not getting stored and also its not showing any errors..can anyone help me out. the code is not showing error's same time its not getting stored in database too..not sure what the problem is..or what my mistake is

JSP File:

 <form action="Register">
        <table>
            <tr>
                <td>
                    Name: 
                </td>
                <td>
                    <input type="text" name="n1">
                </td>
            </tr>
            <tr>
                 <td colspan="3" height="15px">
                </td>
            </tr>
            <tr>
                <td>
                    Age: 
                </td>
                <td>
                    <input type="text" name="a1">
                </td>
            </tr>
            <tr>
                 <td colspan="3" height="15px">
                </td>
            </tr>
            <tr>
                <td>
                    Mobile Number: 
                </td>

                <td>
                    <input type="text" name="m1">
                </td>
            </tr>
            <tr>
                 <td colspan="3" height="15px">
                </td>
            </tr>
            <tr>
                <td>
                    Email: 
                </td>

                <td>
                    <input type="text" name="e1">
                </td>
            </tr>
            <tr>
                 <td colspan="2" height="15px">
                </td>
            </tr>
            <tr>
                <td>
                    Username: 
                </td>

                <td>
                    <input type="text" name="u1">
                </td>
            </tr>
            <tr>
                 <td colspan="2" height="15px">
                </td>
            </tr>
            <tr>
                <td>
                    Password: 
                </td>

                <td>
                    <input type="password" name="p1">
                </td>
            </tr>
            <tr>
                 <td colspan="3" width="100px"></td>
            </tr>
            <tr>
                <td><input type="submit" name="sub" value="Register"></td>
                <td><input type="reset" value="Reset" class="subm"></td>
            </tr>
        </table>
          </form> 

Register Servlet: Servlet for storing in the database

try (PrintWriter out = response.getWriter()) {
       String name=request.getParameter("n1");
       String age=request.getParameter("a1");
       String mobile=request.getParameter("m1");
       String email=request.getParameter("e1");
       String username=request.getParameter("u1");
       String password=request.getParameter("p1");
       if(request.getParameter("sub")!=null)

{

 try
    {
        Class.forName("com.mysql.jdbc.Driver");  
        Connection  con=DriverManager.getConnection("jdbc:mysql://localhost:3306/soundstage","root","");
        Statement stmt=con.createStatement();   
        stmt.executeUpdate("Insert into REGISTRATION values('"+name+"','"+age+"','"+mobile+"','"+email+"','"+username+"','"+password+"')");


       }
       catch(Exception e)
       {
           System.out.println(e.getMessage());
       }

       finally
   {
        RequestDispatcher rd=request.getRequestDispatcher("/Home.jsp");
        rd.forward(request, response);
   }
   }

Image of database url, name etc..

http://ift.tt/1ecqjOv

Attendance System Calculate Total Time

I am currently working on an attendance system for my robotics team using mySQL and PHP using CodeIgniter as a framework. I have functionality for signing in and signing out but the first 2 times the user signs in, it displays their total time by subtracting the length of the current session from 24 hours. It's hard to explain. The output is like this for the first few times the user signs out:

X has signed out

Time: 00 hours 0 minutes 8 seconds Total Time: 23:59:52

It subtracts 8 seconds from 24 hours for some reason for the first 2 times the user signs out.

Here's the code (It's very messy and I apologize, this is my first big project in php)

    public function clock_in($pin_number)
    {
        // Used to get user id
        $query = $this->db->get_where('users', array('pin_number' => $pin_number));
        $id = $query->row_array()['user_id'];

        // Used to get Id of Active event
        $query2 = $this->db->get_where('events', array('is_active' => 1));
        $event_id = $query2->row_array()['event_id'];

        // Used to get last clock of user
        $query3 = $this->db->get_where('clocks', array('user_id' => $id));
        $clock_array = $query3->result_array();
        $size = count($clock_array);
        if($size == 0)
        {
            $data = array(
                'user_id' => $id,
                'event_id' => $event_id,
                'time_stamp' => date('Y-m-d H:i:s'),
                'clock_in' => TRUE
            );
            $this->db->insert('clocks', $data);
            echo $this->get_name($pin_number);
            echo " Has signed in for the first time <br>";
            echo "Welcome to the Team!";
            return;
        }
        $result = $clock_array[$size-1];
        $data = array(
            'user_id' => $id,
            'event_id' => $event_id,
            'time_stamp' => date('Y-m-d H:i:s'),
            'clock_in' => $this->is_clock_in($id)
        );
        // Has the user previously clocked in?
        if(!$this->is_clock_in($id))
        {
        //If yes, store the time the user clocked
        $time = new DateTime($result['time_stamp']);
        //Store the current time
        $current = new DateTime(date('Y-m-d H:i:s'));
        $difference = $current->diff($time);

        $time_a = strtotime($result['time_stamp']);
        $time_b = strtotime(date('Y-m-d H:i:s'));
        echo $this->get_name($pin_number);
        //echo $difference->format('%i')/60;
        echo " has signed out<br>";
        echo "<br>";
        if(abs($time_b-$time_a)/60/60 > 16)
        {
            echo "You forgot to sign out<br>";
            echo "You will not be credited<br>";
            echo "You have been automatically signed in";
            $data['clock_in'] = TRUE;
            $this->db->insert('clocks', $data);
            return;
        }
        echo "Time: ";
        //Display how long the user has been signed in
        echo $current->diff($time)->format('%H hours %i minutes %s seconds');
        $totalTime = new DateTime("0-0-0 0:0:0");
        if($size == 0)
        {
            $totalTime->add($current->diff($time));
        }
        for($i = 1; $i < $size; ++$i)
        {
            $row = $clock_array[$i];
            $row2 = $clock_array[$i - 1];
            if($row['clock_in'] == FALSE)
            {   
                $time_stamp = new DateTime($row['time_stamp']);
                echo $time_stamp;

                $last_time = new DateTime($row2['time_stamp']);
                echo $last_time;

                $delta;
                if($size == 0)
                {
                    $delta = $last_time->add($time_stamp);
                }
                else
                {
                    $delta = $last_time->diff($time_stamp);
                }

                echo $delta;
                $totalTime->add($delta);
            }
        }    
        $totalTime->add($current->diff($time));
        echo "<br>Total Time: ";
        echo $totalTime->format('H:i:s');

Any help is greatly appreciated. Thanks.

mySQL how to limit query returning all results containing a substring

lets consider an example. I want to search car and i'm getting all the results right.

But the problem is i also get all the results which contains car as a substring e.g my result also return cartoon, care and every word that contains car as a substring in my database.

What i want is to apply a filter/condition so that it won't return words like cartoon and care, rather it should only return words like car and cars.

How can i achieve that? I have tried below solutions and i know what the problem is but i cannot understand how to solve it

$string.='(tbl_data.ad_title like "%'.$_REQUEST['searchtt'].'%"  or tbl_categories.cat_title like "%'.$_REQUEST['searchtt'].'%" ) and ';

$gtdata = mysql_query(
"SELECT tbl_data.id, tbl_data.main_cat, tbl_data.sub_cat, tbl_data.makevalue, tbl_data.ad_title, tbl_data.additional, tbl_data.city_name, tbl_data.city_area, tbl_data.date1,tbl_data.date2,tbl_data.make_featured_active, tbl_data.make_stoplight_active, tbl_data.make_urgent_active 
FROM tbl_data LEFT JOIN tbl_categories ON tbl_data.main_cat=tbl_categories.id 
where ".$string." tbl_data.status='1' and tbl_data.del=0 and tbl_data.exp=0 and tbl_data.sold=0 and tbl_data.userblock='0' ".$orderby." limit ".$limit_start.",".$limit_end.""
);
while($res_gtdata=mysql_fetch_array($gtdata))
{
//all results are stored in this variable
//$res
}

How to use Django ORM to function on a field

This question is a follow-up to this one.

I'm running a Django application on top of a MySQL (actually MariaDB) database.

My Django Model looks like this:

from django.db import models
from django.db.models import Count, Sum

class myModel(models.Model):
    my_string = models.CharField(max_length=32,)
    my_date = models.DateTimeField()

    @staticmethod
    def get_stats():            
        logger.info(myModel.objects.values('my_string').annotate(
                count=Count("my_string"), 
                sum1=Sum('my_date'),
                sum2=Sum(# WHAT GOES HERE?? #),
            )
        )

When I call get_stats, it gives me the count and the sum1. However, for sum2, I want the sum of the following Database expression for each matching row: my_date + 0 (this converts it to a true integer value).

What should I put in the expression above to get that sum returned in sum2?

IllegalArgumentException: Type cannot be null

I am confronting with an issue and it seems that many people encountered it and probably couldn't solve it.

I have the following MYSQL stored procedure

CREATE DEFINER=`root`@`localhost` PROCEDURE `get_resource_types`()
BEGIN
    SELECT *
    FROM resource_types
    WHERE inactive = 0;
END

The entity which maps the resource_types table and the named stored procedure query.

@NamedStoredProcedureQuery(
        name="getResourceTypes",
        procedureName="get_resource_types",
        resultClasses = ResourceType.class,
        parameters = {}
)
@Entity
@Table(name = "resource_types")
public class ResourceType {
    ... fields with annotations used for validation + getters and setters ...
}

And here is my JpaRepository from which I make the call to the stored procedure

@Repository
public interface ResourceTypeRepository extends JpaRepository<ResourceType, Long> {
    @Procedure("ResourceType.getResourceTypes")
    List<ResourceType> getResourceTypes();

}

When I try to run this I get the following stack trace:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Type cannot be null; nested exception is java.lang.IllegalArgumentException: Type cannot be null
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144)
    at com.test.ihbs.controller.ResourceTypeControllerTest.test_getAll(ResourceTypeControllerTest.java:111)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:64)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:106)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Type cannot be null; nested exception is java.lang.IllegalArgumentException: Type cannot be null
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:381)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy87.getResourceTypes(Unknown Source)
    at com.ihbs.service.ResourceTypeService.getAll(ResourceTypeService.java:34)
    at com.ihbs.controller.ResourceTypeController.getAllResourceTypes(ResourceTypeController.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    ... 58 more
Caused by: java.lang.IllegalArgumentException: Type cannot be null
    at org.hibernate.procedure.internal.AbstractParameterRegistrationImpl.setHibernateType(AbstractParameterRegistrationImpl.java:182)
    at org.hibernate.procedure.internal.AbstractParameterRegistrationImpl.<init>(AbstractParameterRegistrationImpl.java:131)
    at org.hibernate.procedure.internal.AbstractParameterRegistrationImpl.<init>(AbstractParameterRegistrationImpl.java:140)
    at org.hibernate.procedure.internal.AbstractParameterRegistrationImpl.<init>(AbstractParameterRegistrationImpl.java:77)
    at org.hibernate.procedure.internal.PositionalParameterRegistration.<init>(PositionalParameterRegistration.java:41)
    at org.hibernate.procedure.internal.ProcedureCallImpl.registerParameter(ProcedureCallImpl.java:275)
    at org.hibernate.jpa.internal.StoredProcedureQueryImpl.registerStoredProcedureParameter(StoredProcedureQueryImpl.java:128)
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.newAdhocStoredProcedureQuery(StoredProcedureJpaQuery.java:147)
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.createStoredProcedure(StoredProcedureJpaQuery.java:110)
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.doCreateQuery(StoredProcedureJpaQuery.java:68)
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.createQuery(StoredProcedureJpaQuery.java:58)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$ProcedureExecution.doExecute(JpaQueryExecution.java:295)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:97)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:88)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:395)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:373)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:486)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 80 more

Any ideas why is this happening and how to fix it?