Affichage des articles dont le libellé est Active questions tagged android - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged android - Stack Overflow. Afficher tous les articles

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