mardi 4 août 2015

implementing onitemclicklistener with GridView

I have a grid view with custom adapter that contains an image and a TextView holder. The objective is to change color matrix of ImageView with onclick and then use an itemclicklistener to perform another action

here is the clicklistener in adapter

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if(convertView == null){
        vi = inflater.inflate(R.layout.pages_grid,  null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();

        final NetworkImageView page_pic = (NetworkImageView) vi.findViewById(R.id.grid_icon);
        TextView page_name = (TextView) vi.findViewById(R.id.page_selected);
        final RelativeLayout rl = (RelativeLayout) vi.findViewById(R.id.selected_bar);
        LinearLayout container = (LinearLayout) vi.findViewById(R.id.page_container);
         ColorMatrix matrix = new ColorMatrix();
            matrix.setSaturation(0);

            final ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
            page_pic.setColorFilter(filter);    
        HashMap<String, String> pages = getItem(position);

        page_pic.setImageUrl("http://ift.tt/wljqS4" + pages.get("page_id") + "/picture", imageLoader);
        page_name.setText(pages.get("page_name"));
        container.setOnClickListener(new OnClickListener() {
            private boolean isSelected = false;
            @Override
            public void onClick(View v) {
                if(isSelected == false){
                    page_pic.setColorFilter(null);
                    rl.setBackgroundColor(context.getResources().getColor(R.color.cyan));
                    isSelected = true;
                }else{
                    page_pic.setColorFilter(filter);
                    rl.setBackgroundColor(Color.parseColor("#f0CCCCCC"));
                    isSelected = false;
                }

            }
        });
    }
    return vi;
}

and here is the on itemclicklistener

gv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {


            String page_id = data.get(position).get("page_id");
            if(pages.contains(page_id))
                {
                pages.remove(page_id);
                }else{              
            pages.add(page_id);
                }
            Toast.makeText(getApplicationContext(),  "" + pages.toString(), Toast.LENGTH_SHORT).show();

        }
    });

when I click the color matrix is applied but toast is not shown and when I comment the clicklistener in adapter the toast is shown. but I want the 2 click actions to be triggered when I click the item

save images in sd card from server in Android

I want to download images from server and save into sd card in Emulator.First i have to get json string of images and passing to the download server url for download and save into sd card. I m getting error of nullPointer exception at the run time.Please someone help me how to do this.

Here is my Code

public void getAllImagePath_List() {
        String strUrl_GetAll_Activity = "http://xxx/xxx/xxx.svc/xxx/xx/"+str_UserId+"/xx/"+xxx+"/xxx/"+xxx;
        Log.e("strUrl_GetAll_Activity ", " = " + strUrl_GetAll_Activity);
        InputStream inputStream = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse httpResponse = httpclient.execute(new HttpGet(strUrl_GetAll_Activity));
            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null)
                strResult = convertInputStreamToString(inputStream);
            else
                strResult = "Did not work!";

            String jsonStr = strResult;

            try {

                JSONObject jsonObj = new JSONObject(jsonStr);
                String jsonResult = jsonObj.toString().trim();
                Log.e("jsonResult ", " = " + jsonResult);

                JSONObject getAllActivity_List = jsonObj.getJSONObject("Get_ALL_ActivityListResult");
                Log.e("getAllActivity_List ", " = " + getAllActivity_List.toString());

                String strSync = getAllActivity_List.getString("Sync_Time");
                Log.e("strSync ", " = " + strSync.toString());

                JSONArray jarr = getAllActivity_List.getJSONArray("ActivityObjectList");
                Log.e("jarr ", " = " + jarr.toString());

                SQLiteDatabase mDb = dbhelper.getWritableDatabase();
                int imageNum = 0;
                BufferedOutputStream bos;
                 imagesArray = new String[jarr.length()];
                for (int j = 0; j < jarr.length(); j++)
                {
                    JSONObject jobjVessels = jarr.getJSONObject(j);

                    str_imgList_imageaudioPath = jobjVessels.getString("imageaudioPath");
                    Log.e("", "" + str_imgList_imageaudioPath);


                    String str_ImageUrl = "http://xxx/xxx/xxx.svc/DownloadFile/FileName/"+str_imgList_imageaudioPath;
                    downloadUrl(str_ImageUrl);

                    Log.e("Downloaded Completed","!!!!!");

                }

            }

            catch (JSONException je)
            {
                je.printStackTrace();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private Bitmap downloadUrl(String strUrl) throws IOException{
        Bitmap bitmap=null;
        InputStream iStream = null;
        try{
            URL url = new URL(strUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            bitmap = BitmapFactory.decodeStream(iStream);
            Log.e("bitmap while  url", "downloading " + bitmap.toString());



            saveBitmap(bitmap);
        }catch(Exception e){
            Log.e("Exception while  url", "downloading " + e.toString());
        }finally{
            iStream.close();
        }

        return bitmap;
    }


    public void saveBitmap(Bitmap bm)
    {
        try
        {
            String mBaseFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/json_imglist";
            String mFilePath = mBaseFolderPath + "abcd.jpg";

            FileOutputStream stream = new FileOutputStream(mFilePath);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            stream.flush();
            stream.close();
        }
        catch(Exception e)
        {
            Log.e("Could not save", e.toString());
        }
    }

Thanks to appreciate.

Ionic android build failed after added AdMob Pro

I just started to use ionic framework to build android apps. So I've run:

ionic start App blank
ionic platform add android
ionic build android
ionic run android

So far so good, I can test my app in my android phone with no problem. Now I want to add admob to my app. I decided to use the AdMobPro, so I did this:

ionic plugin add cordova-plugin-admobpro

The plugin added successfully. Without having implemented the admobpro code in my app.js, I tried to run ionic build android again just to make sure everything is ok, I got this error:

Running: /home/vagrant/app/android-quotes/platforms/android/gradlew cdvBuildDebug -b /home/vagrant/app/android-quotes/platforms/android/build.gradle -
Dorg.gradle.daemon=true

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_debugCompile'.
   > Could not find any version that matches com.google.android.gms:play-services-ads:+.
     Searched in the following locations:
         http://ift.tt/1fhRit3
         http://ift.tt/1MMeoCs
     Required by:
         :android:unspecified

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 11.603 secs

/home/vagrant/app/android-quotes/platforms/android/cordova/node_modules/q/q.js:126
                    throw e;
                          ^
Error code 1 for command: /home/vagrant/app/android-quotes/platforms/android/gradlew with args: cdvBuildDebug,-b,/home/vagrant/app/android-quotes/plat
forms/android/build.gradle,-Dorg.gradle.daemon=true
ERROR building one of the platforms: Error: /home/vagrant/app/android-quotes/platforms/android/cordova/build: Command failed with exit code 1
You may not have the required environment or OS to build this project
Error: /home/vagrant/app/android-quotes/platforms/android/cordova/build: Command failed with exit code 1
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:134:23)
    at ChildProcess.emit (events.js:110:17)
    at maybeClose (child_process.js:1015:16)
    at Process.ChildProcess._handle.onexit (child_process.js:1087:5)

Anyone has this error before?

Can't correctly release PowerManager.WakeLock

I'm using PowerManager.WakeLock for Sensor.TYPE_LIGHT in Activity. It works well but when i'm closing/went to other Activity SensorEventListener keep turn on/off screen if get sensor changes.

Code sample

    SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    Sensor mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");

SensorEventListener interface method

@Override
public void onSensorChanged(SensorEvent event) {
    float[] lux = event.values;

    if (lux[0] <= 200) {
        mWakeLock.acquire();
    } else {
        if (mWakeLock.isHeld()) {
            mWakeLock.release();
        }
    }
}

SensorManager listener

 @Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mLightSensor, SensorManager.SENSOR_DELAY_FASTEST);

}

@Override
protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this, mLightSensor);

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mWakeLock.isHeld()) {
        mWakeLock.release();
    }

}

So how to correctly release and disable WakeLock. Thanks in advance.

Transparent Listview over google Map android

In my application I need to create a transparent listview over google map. I am using toggle button to open and close listview. When listview is visible it should be transparent so that google map should be visible/semi-visible.

For this part there are three layouts. 1. custom_cluster_mapview.xml 2. bottomlayout.xml 3. map_list_view_row

  1. custom_cluster_mapview.xml

    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:ads="http://ift.tt/GEGVYd"
    xmlns:materialdesign="http://ift.tt/1ImoBTp"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".map.MapView" >
    
    <LinearLayout
        android:id="@+id/myLinearLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <LinearLayout
            android:id="@+id/mapLayout"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" >
    
            <fragment
                android:id="@+id/mycustomemap"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                class="com.google.android.gms.maps.SupportMapFragment" />
        </LinearLayout>
    
        <include layout="@layout/bottomlayout" />
    
    
    
    
    </LinearLayout>
    
    </RelativeLayout>
    
    
  2. bottomlayout.xml

       <LinearLayout
        xmlns:android="http://ift.tt/nIICcg"
    
        android:id="@+id/outerLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:weightSum="2"
        android:orientation="vertical"
        >
    
    
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                >
            <ToggleButton
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:background="@drawable/up_arrow"
                android:textOff=""
                android:textOn=""
                android:id="@+id/toggleButtonListView"
                android:layout_gravity="center_horizontal" />
            </LinearLayout>
    
        <LinearLayout
            android:id="@+id/mapListViewSlider"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:layout_weight="1.95"
            android:orientation="vertical">
    
    
            <CheckBox
                android:id="@+id/sort_distance"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Sort By Distance"/>
            <ListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:dividerHeight="5dp"
                android:divider="@color/red"
                android:id="@+id/map_listview"/>
            </LinearLayout>
    
    </LinearLayout>
    
    

3. map_list_view_row.xml

    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="10dp"
    android:paddingBottom="12dp">


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="10dp"
        android:weightSum="4"
        android:id="@+id/linearLayout">
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <TextView
                android:id="@+id/map_list_view_tv1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:text="@string/label_name" />

            <TextView
                android:id="@+id/map_list_view_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/map_list_view_tv1"
                android:text="abcde"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <TextView
                android:id="@+id/map_list_view_tv2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/label_category" />
            <TextView
                android:id="@+id/map_list_view_category"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/map_list_view_tv2"
                android:text="abcde" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <TextView
                android:id="@+id/map_list_view_tv3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/label_location" />
            <TextView
                android:id="@+id/map_list_view_location"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/map_list_view_tv3"
                android:text="abcde" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <TextView
                android:id="@+id/map_list_view_tv4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_marginBottom="10dp"
                android:text="@string/label_distance" />

            <TextView
                android:id="@+id/map_list_view_distance"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/map_list_view_tv4"
                android:text="abcde" />

        </RelativeLayout>
    </LinearLayout>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/map_list_view_imageView"
        android:background="@drawable/med"
        android:layout_marginTop="4dp"
        android:layout_marginRight="16dp"
        android:layout_alignParentRight="true"/>

</RelativeLayout>

Following is the picture when map is loaded http://ift.tt/1MJHjKT

At bottom of the screen there is up arrow button. I want to make background of that transparent. So that only arrow is visible without any background. When I click on the arrow listView is shown. Like below

http://ift.tt/1Imozuw

How to make listView transparent so that the google map is visible/semi-visible.

Thanks in advance.

Android studio - cant find my app on device after building

I'm using android studio 1.3 , I'm running/debugging my app on my Nexus 5 - works great but after exiting the app - I cant find my app on the device.. so actually every time I want to run it I need to connect my device to the studio and run...

It happened suddenly , in the past I ran the program and it did! Stay on the device Tried on different devices.

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "app.meantneat.com.meetneat"
        minSdkVersion 17
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()

    maven {
        url 'http://ift.tt/1CLc08h'
    }
}

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.google.android.gms:play-services:7.3.0'
    compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
    //compile 'com.getbase:floatingactionbutton:1.9.0'
    //compile 'com.parse.bolts:bolts-android:1.+'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.melnykov:floatingactionbutton:1.3.0'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    compile 'me.villani.lorenzo.android:android-cropimage:1.1.0'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'




    //compile fileTree(dir: 'libs', include: 'Parse-*.jar')
    //compile 'com.google.android.gms:play-services:7.3.0'
}

Any help would be greatly appreciated.Thanks, Dan

Getting a NPE with AppCompatActivity that I wasn't getting with ABS

In my onCreateOptionsMenu() I'm getting a View v that is ending up null. I can put a null check around it, but it won't actually solve the issue since I need to use that view further on in the method. The code causing v to be null is below:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);


        /** Create an option menu from res/menu/items.xml */
        getMenuInflater().inflate(R.menu.dee, menu);
        View v = (View) menu.findItem(R.id.search_menu_item).getActionView();

Any reason why seemingly changing the Activity to use AppCompat instead of ABS is causing a null pointer?

Android Blur View (Blur background behind the view)

I am trying to make the bottom part of an Image blur for the view on top it like in the image.

I tried blurring it using Rendenscript but I am not able to blur only the part behind the view. :(

I have seen many libraries but almost all of them blur the entire image, but not a part of it.

Also, an important part is that I am using this inside a ViewPager and hence needs to be fast and dynamic something like this in IOS which redraws itself the moment image behind it changes.

Any help is appreciated. Thanks for stopping by!

My xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/image"
        android:src="@drawable/broadstairs"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:layout_centerInParent="true"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:text="Hello World"
        android:gravity="center"
        android:layout_alignParentBottom="true"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        android:textSize="36sp"/>
</RelativeLayout>

My code:

BlurBuilder.java

public class BlurBuilder {
    private static final float BITMAP_SCALE = 0.1f;
    private static final float BLUR_RADIUS = 7.5f;

    public static Bitmap blur(Context context, Bitmap image) {
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);

        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

        RenderScript rs = RenderScript.create(context);
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);

        return outputBitmap;
    }

    @SuppressLint("NewApi")
    public static void blur(final Context context, final Bitmap bitmap, final View view) {

        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... params) {
                Paint paint = new Paint();
                paint.setFilterBitmap(true);
                Bitmap cropImage = Bitmap.createBitmap(bitmap, 0, bitmap.getHeight() - view.getHeight(), bitmap.getWidth(), view.getHeight());

                return BlurBuilder.blur(context, cropImage);
            }


            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                if (bitmap != null) {
                    int sdk = android.os.Build.VERSION.SDK_INT;
                    if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        view.setBackgroundDrawable(new BitmapDrawable(context.getResources(), bitmap));
                    } else {
                        view.setBackground(new BitmapDrawable(context.getResources(), bitmap));
                    }

                }

            }
        }.execute();


    }

}

In my MainActivity's onCreate I do:

BlurBuilder.blur(BitmapActivity.this, ((BitmapDrawable) mView.getDrawable()).getBitmap(), mDummyView);

Below is the result:

enter image description here

Android: MediaRecorder start failed

I run my video recorder app on 30 type of phones are fine except for Samsung GT-I9082i. My app display the camera info. on a OpenGL view but not surface view. If I use surface view to dispaly the camera info. on GT-I9082i, all are OK. Because I must to render more efffects use opengl,I cann't use Surface view.

if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
        } else {
            mMediaRecorder.reset();
        }

mMediaRecorder.setCamera(camera);

        // Step 2: Set sources

        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);

        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

// Step 4: Set a CamcorderProfile (requires API Level 8 or higher)

        mMediaRecorder.setProfile(CamcorderProfile.get(cameraIndex, CamcorderProfile.QUALITY_HIGH));

mRecAudioFile = File.createTempFile("Video", ".mp4", mRecVedioPath);

mMediaRecorder.setOutputFile(mRecAudioFile.getAbsolutePath());

        // Step 6: Set the preview output

        mMediaRecorder.setPreviewDisplay(null);

        // Step 7: Set Video Size


        mMediaRecorder.setVideoSize(cameraVideoOptimalSize.width, cameraVideoOptimalSize.height);

// Step 8: Prepare configured MediaRecorder

        try {
            mMediaRecorder.prepare();
            mMediaRecorder.start();

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

Android how to use Toolbar in ListActivity?

I have activity as

 public class NoteListActivity extends ListActivity{
 }

I don't have following method available any more:-

    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

How to use ListActivity and android.support.v7.widget.Toolbar ?

Git - Android Studio no longer lets me commit changes and push to GitHub

As of a couple of hours ago, Android Studio no longer lets me commit my changes. When the Commit dialog pops up, it shows the files that have changed and lets me enter a commit message. However, when i click Commit (or Commit and Push), the progress dialog comes up, goes to about 10% - 20% and then just disappears without actually committing anything. If i try again (without restarting the IDE first), nothing seems to happen at all when i click Commit/Commit and Push.

Sadly, Google searches have so far not been very helpful to me, so if any of you could help me out, i would really appreciate it.

I have heard, however, that git might sometimes clash with Windows on changing the capitalization of file names. I do remember renaming my Utilities package to utilities and Adapters package to adapters. Could this be causing my problem and if so, how can i fix this?

Thanks in advance.

How to disable notification bar with overlay or another method for android application

I want to disable notification bar in android. When we slide our finger up to down, I want to disable notification bar.

How to format time from Android's TimePicker?

Hi I am currently using a TimePickerDialog to set the time and display it into a text view. However, I am having problems with the formating. This is my code

    TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        if ((hourOfDay >= 1) && (hourOfDay <= 11.59)) {
            hours = hourOfDay;
            am_pm = "AM";
        } else if (hourOfDay >= 12) {
            hours = hourOfDay - 12;
            am_pm = "PM";
        } else if (hourOfDay == 0) {
            hours = 12;
            am_pm = "AM";
        }

        tvScheduleTime.setText(hours + " : " + minute + " " + am_pm);

    }
};

This method works in retrieving AM and PM but the numbering is weird, like 6:08 AM becomes 6:8 AM. How can I make it so that it creates the text HH-MM AM/PM?

android.support.design.widget.coordinatorlayout not found in eclipse

I am using eclips and when i am running my project i got the following error .

08-04 17:12:25.596: E/AndroidRuntime(4175): FATAL EXCEPTION: main
08-04 17:12:25.596: E/AndroidRuntime(4175): java.lang.RuntimeException: Unable to start activity ComponentInfo{me.declangao.wordpressreader/me.declangao.wordpressreader.app.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.os.Looper.loop(Looper.java:137)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.ActivityThread.main(ActivityThread.java:5103)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at java.lang.reflect.Method.invoke(Method.java:525)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at dalvik.system.NativeStart.main(Native Method)
08-04 17:12:25.596: E/AndroidRuntime(4175): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.view.LayoutInflater.createView(LayoutInflater.java:620)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at me.declangao.wordpressreader.app.PostFragment.onCreateView(PostFragment.java:72)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.Activity.performStart(Activity.java:5143)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
08-04 17:12:25.596: E/AndroidRuntime(4175):     ... 11 more
08-04 17:12:25.596: E/AndroidRuntime(4175): Caused by: java.lang.reflect.InvocationTargetException
08-04 17:12:25.596: E/AndroidRuntime(4175):     at java.lang.reflect.Constructor.constructNative(Native Method)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.view.LayoutInflater.createView(LayoutInflater.java:594)
08-04 17:12:25.596: E/AndroidRuntime(4175):     ... 24 more
08-04 17:12:25.596: E/AndroidRuntime(4175): Caused by: java.lang.NoClassDefFoundError: android.support.design.R$styleable
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:168)
08-04 17:12:25.596: E/AndroidRuntime(4175):     at android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:162)

How to save android canvas as svg?

Is there any possible way to save the android canvas as svg. I know how to save it as png/jpeg. Im currently saving it as jpeg. Here is the code that I use now for saving.

            canvas.setDrawingCacheEnabled(true);
            canvas.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
            Bitmap bitmap = canvas.getDrawingCache();
            String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(path+"/image.jpg");
            FileOutputStream ostream;
            try {
                file.createNewFile();
                ostream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
                ostream.flush();
                ostream.close();
                Toast.makeText(getApplicationContext(), "image saved", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
            }

I want this to be saved as svg?

How to send data from android to google app engine web app made in java

I am new to google app engine and android.Made an application in android which takes value from user and post it to servlet. I used httpClient to post data from android to servlet,hosted locally and sending data from emulator . I receive null value from servlet side.I googled a lot in this context but not getting solution for the issue.Any help appreciated.Thnx

Yandex Marker's Current Latlong values in Android

I 'm not able to get the Yandex default Marker's current Latlong values in Android. What I'm really interested is to capture the current latlong values from the android mobile and yandex map marker's position is exactly what I need. Has anyone used yandex maps to get the current user location? Can you please help.

Update 1

While researching on this latlong issue with Google and Yandex, I came across a link for "GPS Fix" app from http://ift.tt/1eQ0Avl. After installing this App on the Android device and performing "Start Fixing", the latlong values now provided by Yandex SDK in my custom App is now closer to that of marker's. But still some points show over the buildings beside road (I can adjust that for now). I believe "GPS fix" app does somekind of flushing the GPS cache??? not sure if there is such a thing. I 'm still waiting for a clean solution that works without support from other app.

Thanks, Hemant

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

How to keep running the task even if the app is already closed?

Currently, i have built a service to do httpRequest to my php server every 15 seconds. The code works well but the problem is when i close the app the httpRequest is stop working and does not send data anymore. what i want to do is when i close the app, the httpRequest still running. what should i change in my code?

here is the code i have been working on...

public class NotificationService extends Service {

public String response;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "on start command", Toast.LENGTH_SHORT).show();
    new MyAsyncTask().execute("muhammad sappe");
    return START_NOT_STICKY;
}

private class MyAsyncTask extends AsyncTask<String, String, String>{

  @Override
  protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    postData(params[0]);
    return null;
  }

  @Override
  protected void onPostExecute(String result) {
      new Handler().postDelayed(new Runnable() {
            public void run() {
                new MyAsyncTask().execute("muhammad sappe");
            }
        }, 15000);
    super.onPostExecute(result);
  }

}

public void postData(String MyName){
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://mydomain/getData.php");
    try {   
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("action", MyName));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = httpclient.execute(httppost, responseHandler);
    }catch(ClientProtocolException e){
        // TODO Auto-generated catch block
    }catch(IOException e) {
        // TODO Auto-generated catch block
    }
}

public void onDestroy() {
    super.onDestroy();
}
}

ListView first Item overlaid

My ListView displays in first Item something else as the rest of the ListView

The Problem is, that it replaces the first item instead of taking a own position.

Example how it has to be:

A (diferent to the others)

B

B

B

How it is:

A (B Overlaid by A)

B

B

As you can see, one B is missing because it is overlaid by A.

Here is the Code. I wrote my own CustomAdapter:

@Override
public int getCount() {
    if (taskItems.size() + 1 >= 0)
        return taskItems.size();
    return 0;
}

@Override
public Object getItem(int position) {
    return position;
}

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

public static class ViewHolder {
    public TextView taskTitleTextView;
    public TextView taskObjectTextView;
    public TextView taskLocationTextView;
    public ImageView taskImageImageView;

}

public static class ViewHolderProjects {
    public TextView projectTitelTextView;
    public TextView projectInfoTextView;
    public TextView projectDeadline;
    public ImageView projectImageImageView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    ViewHolderProjects holderProjects;
    if (position == 0) {
        if (convertView == null) {
            vi = inflater.inflate(R.layout.list_item_projects, null);
            holderProjects = new ViewHolderProjects();

            holderProjects.projectTitelTextView = (TextView) vi.findViewById(R.id.projectTitle);
            holderProjects.projectInfoTextView = (TextView) vi.findViewById(R.id.projectInfo);
            holderProjects.projectImageImageView = (ImageView) vi.findViewById(R.id.projectImage);
            holderProjects.projectDeadline = (TextView) vi.findViewById(R.id.projectdeadline);

            vi.setTag(holderProjects);
        } else {
            holderProjects = (ViewHolderProjects) vi.getTag();
        }
        if (projectMap.size() <= 0) {
            holderProjects.projectInfoTextView.setText("Keine Infos");
            holderProjects.projectTitelTextView.setText("Kein Titel");
        } else {
            if (projectMap.get(position).containsKey("project_company_image")) {
                if (projectMap.get(position).get("project_company_image").getBytes().length == 0) {
                    holderProjects.projectTitelTextView.setText(jobMap.get(position).get("job_subject"));
                    holderProjects.projectDeadline.setText(jobMap.get(position).get("job_deadline"));
                    return vi;
                }
                Bitmap bm = Bitmap.createBitmap(base64EncodeDecode.decodeBase64(projectMap.get(position).get("project_company_image")));
                holderProjects.projectTitelTextView.setText(jobMap.get(position).get("job_subject"));
                holderProjects.projectDeadline.setText(jobMap.get(position).get("job_deadline"));
                holderProjects.projectImageImageView.setImageBitmap(bm);
            }
        }
    } else {

        ViewHolder holder;
        if (convertView == null) {
            vi = inflater.inflate(R.layout.list_item_tasks, null);

            holder = new ViewHolder();
            holder.taskTitleTextView = (TextView) vi.findViewById(R.id.taskTitle);
            holder.taskObjectTextView = (TextView) vi.findViewById(R.id.taskObject);
            holder.taskLocationTextView = (TextView) vi.findViewById(R.id.taskLocation);
            holder.taskImageImageView = (ImageView) vi.findViewById(R.id.taskImage);

            vi.setTag(holder);
        } else {
            holder = (ViewHolder) vi.getTag();
        }

        if (taskItems.size() <= 0) {
            holder.taskTitleTextView.setText("Kein Titel");
            holder.taskObjectTextView.setText("Kein Objekt");
            holder.taskLocationTextView.setText("Kein Standort");
        } else {
            if (taskItems.get(position).containsKey("object_image")) {
                if (taskItems.get(position).get("object_image").getBytes().length == 0) {
                    holder.taskTitleTextView.setText(taskItems.get(position).get("task_headline"));
                    holder.taskObjectTextView.setText(taskItems.get(position).get("object_name"));
                    holder.taskLocationTextView.setText(taskItems.get(position).get("object_location"));

                    return vi;
                }
            }
            Bitmap bm = Bitmap.createBitmap(base64EncodeDecode.decodeBase64(taskItems.get(position).get("object_image")));
            holder.taskTitleTextView.setText(taskItems.get(position).get("task_headline"));
            holder.taskObjectTextView.setText(taskItems.get(position).get("object_name"));
            holder.taskLocationTextView.setText(taskItems.get(position).get("object_location"));
            holder.taskImageImageView.setImageBitmap(bm);
        }
    }
    return vi;

}

how to change colour of action bar tabs on click for a few seconds only in android

I am using action bar tabs(not tabhost) . I want to change colour of my selected tab for a second (like whtsapp). I have used this code but its not working and this code is also hiding my tabs text.

public void onTabSelected(Tab tab, FragmentTransaction ft)
{
   TextView v=new TextView(TabActivity.this);
   Log.d("TextView", v.toString());
   v.setBackgroundColor(Color.GREEN);  
   tab.setCustomView(v);
}

Optimizing Memory in Android when managing Fragment Transactions

I'm using Fragments in my app where all of them share one base activity, so activity is not destroyed till app closes. When I navigate from one fragment to another, I have used the following code:

 Fragment myFragment=new MyFragment();
 FragmentManager fragmentManager = getFragmentManager();
 fragmentManager.beginTransaction().addToBackStack("MyFragment")
 .replace(R.id.content_frame, myFragment,"AirtimeFragment").commit();

When using it I have to create a new Object for each fragment which is not good for memory consumption.

So I want to create one global method which manages all fragment in which it checks whether the fragment already exists, then no need to recreate it just uses the existing fragment object, so I can reduce memory consumption?

TextInputLayout error after enter value into edittext

How can i hide a TextInputLayout error after input one text in EditText. Is it possible?

how can i achieve this or I am doing something wrong here.!!

enter image description here

code

    layoutEdtPhone =(TextInputLayout)rootView.findViewById(R.id.layoutEdtPhone);
    layoutEdtPhone.setErrorEnabled(true);
    layoutEdtPhone.setError(getString(R.string.ui_no_phone_toast));
    layoutEdtPassword =   (TextInputLayout)rootView.findViewById(R.id.layoutEdtPassword);
    layoutEdtPassword.setErrorEnabled(true);
    layoutEdtPassword.setError(getString(R.string.ui_no_password_toast));

    edtPhone=(EditText)rootView.findViewById(R.id.edtPhone);
    edtPassword=(EditText)rootView.findViewById(R.id.edtPassword);

xml

            <EditText
                android:id="@+id/edtPhone"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="100dp"
                android:background="@drawable/edt_background_selector"
                android:drawableLeft="@drawable/phone_icon"
                android:drawableStart="@drawable/phone_icon"
                android:hint="@string/phone"
                android:inputType="phone"
                android:padding="5dip"
                android:singleLine="true"
                android:textSize="14sp" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/layoutEdtPassword"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <EditText
                android:id="@+id/edtPassword"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:background="@drawable/edt_background_selector"
                android:drawableLeft="@drawable/password_icon"
                android:drawableStart="@drawable/password_icon"
                android:hint="@string/password"
                android:inputType="textPassword"
                android:padding="5dip"
                android:singleLine="true"
                android:textSize="14sp" />
        </android.support.design.widget.TextInputLayout>

When i run my Fragment project, eclipse shows errors. I don't know how to fix it

Here is the instruction i tried to follow carefully:

http://ift.tt/1k5dyDx

here are the first errors appear in Logcat:

E/MoreInfoHPW_ViewGroup(21404): Parent view is not a TextView

E/AndroidRuntime(21404): FATAL EXCEPTION: main

E/AndroidRuntime(21404): Process: com.example.fragmentstest, PID: 21404

E/AndroidRuntime(21404): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragmentstest/com.example.fragmentstest.MainActivity}: android.view.InflateException: Binary XML file line #20: Error inflating class fragment

here are my MainActivity and activity_main codes:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void selectFrag(View view){
    Fragment fr;
    if (view == findViewById(R.id.button2)){
        fr = new FragmentTwo();
    } else {
        fr = new FragmentOne();
    }
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_place, fr);
    fragmentTransaction.commit();


}  




<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Fragment No.1"
    android:onClick="selectFrag" />

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Fragment No.2" 
    android:onClick="selectFrag"/>

<fragment 
    android:name="com.example.fragmentstest.FragmentOne"
    android:id="@+id/fragment_place"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>"

</LinearLayout>

Show heads-up notification in cordova android

Anyone knows how to do heads-up notifications in cordova android?

I'm making an app where it is critical that a user sees a notification. I'm using the phonegap-build pushPlugin.

The server is a nodejs where i have tried:

var androidPayload = {
    data: {
        title: title,
        message: msg,
        notId:title,
        priority: 2
    }
};

or have i made something wrong?

After removing the item from the ListView, ListView is not updated

After removing the item from the lvSimple (ListView) I can not update the contents of LisView. The data from the database are removed. Items of ListView too. But i need to "flip through" fragments to see this. It's part of my code.

public class PageFragment extends Fragment {

public boolean onContextItemSelected(MenuItem item) {
    if (item.getItemId() == CM_DELETE_ID) {
        AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        myDB.deleteRow(acmi.id);
        populateListView();
        return true;
    }
    return super.onContextItemSelected(item);
}

public void populateListView() {
    String[] fromFieldNames = new String[]{DBAdapter.KEY_DATE, DBAdapter.KEY_AREA, DBAdapter.KEY_PASSENGER};
    int[] toViewsID = new int[]{R.id.tvItemDate, R.id.tvItemArea, R.id.tvItemPassenger};
    SimpleCursorAdapter myC;
    myC = new SimpleCursorAdapter(view.getContext(), R.layout.item, c, fromFieldNames, toViewsID, 0);
    myC.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if (columnIndex == 1) {
                String createDate = cursor.getString(columnIndex);
                textView = (TextView) view;
                textView.setText(dateFormat(createDate));
                return true;
            }
            return false;
        }
    });
    lvSimple.setAdapter(myC);
    myC.notifyDataSetChanged();
    lvSimple.invalidateViews();
}
}

WebView loadUrl(url) is opening in default browser [duplicate]

This question already has an answer here:

im trying to make app based on WebView of mobile page. The thing is that page loads in default user's browser instead of app. Here is my code, any thoughts about what am i doing wrong?

package pl.beat_down.bdmobile;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.app.Activity;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://beat-down.pl/m";
WebView view = (WebView) this.findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) { 
int id = item.getItemId();

if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}    

CardView inside TableLayout

i have 2 cardviews inside a table layout. CODE:

                <TableLayout android:id="@+id/TableLayout01" android:stretchColumns="*"
                    android:layout_height="fill_parent" android:layout_width="fill_parent"
                    android:layout_centerInParent="true"
                    android:layout_below="@+id/card_view3"
                    android:layout_marginTop="7dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp">
                <TableRow android:id="@+id/TableRow01" android:layout_width="fill_parent"
                    android:layout_height="wrap_content" android:layout_weight="1">

                    <android.support.v7.widget.CardView
                        android:layout_margin="5dp" android:layout_weight="1"
                        android:layout_height="180dp" android:layout_width="fill_parent"
                        android:background="#ffdbff3d">


       </android.support.v7.widget.CardView>

     <android.support.v7.widget.CardView
          android:layout_margin="5dp" android:layout_weight="1"
               android:layout_height="180dp" android:layout_width="fill_parent"
       android:background="#ffdbff3d">


       </android.support.v7.widget.CardView>

     </TableRow>
      </TableLayout>

there is a picture inside cv1 and the problem is that when i set picture(in cv1) width to fill_parent the picture takes all the row and wont fill just the cv1 and even when i dont set fill parent its doing its job!

and i even cant set a background for my cv and i dont know why.

i hope u can solve it.

CheckBox in android gridview not working on first click

am doing an android application, in that am loading check boxes in grid view from JSON web services . Up to this it is working perfectly. when i click the check box for the first time it is not triggering the event. but the second time it is working properly. Please help me if anybody knows

My java Code:

@SuppressWarnings("deprecation")
    public void showFolderPopUPforEdit() {

        int count = 0;
        String folderID = null;
        String selectedfolderID = null;

        LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        editpopupView = layoutInflater.inflate(R.layout.edit_folders, null);
        editpopupWindow = new PopupWindow(editpopupView,
                LayoutParams.MATCH_PARENT, 1060);
        editpopupWindow.showAtLocation(editpopupView, Gravity.BOTTOM, 0, 0);

        try {
            leadna_leadsFolderjsonaray = leadna_leadFoldersjson
                    .getJSONArray("folderList");
            for (int i = 0; i < leadna_leadsFolderjsonaray.length(); i++) {
                cb = new CheckBox(this);
                cb.setChecked(false);
                cb.setFocusable(false);
                cb.setFocusableInTouchMode(false);              
                cb.setBackground(getResources()
                        .getDrawable(R.drawable.uncheck1));
                cb.setButtonDrawable(android.R.color.transparent);
                JSONObject c = leadna_leadsFolderjsonaray.getJSONObject(i);
                folderID = c.getString("category_id");
                for (int j = 0; j < leadna_leadsSelectedFolderjsonaray.length(); j++) {
                    JSONObject arr2 = leadna_leadsSelectedFolderjsonaray
                            .getJSONObject(j);
                    selectedfolderID = arr2.getString("attach_category");
                    if (folderID.equalsIgnoreCase(selectedfolderID)) {
                        cb.setChecked(true);
                        cb.setBackground(getResources().getDrawable(
                                R.drawable.check_btn));
                        cb.setFocusable(false);
                        cb.setFocusableInTouchMode(false);  
                        cb.setButtonDrawable(android.R.color.transparent);
                        break;
                    }
                }
                cb.setText(c.getString("category_name"));
                cb.setTextColor(Color.BLACK);
                cb.setTextSize((float) 14);
                cb.setTag(c.getString("category_id"));
                cb.setLayoutParams(new GridView.LayoutParams(346, 90));
                cb.setPadding(54, 0, 0, 0);
                cb.setOnClickListener(this);
                cb.setId(i);
                cb.requestFocus();
                meditButtons.add(cb);
            }

            GridView gridView = (GridView) editpopupView
                    .findViewById(R.id.gridEditView1);          
            gridView.setAdapter(new CustomAdapter(this, meditButtons));


        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Button btnSaveFolders = (Button) editpopupView
                .findViewById(R.id.btnAddActivity);
        btnSaveFolders.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        Button btnDismiss = (Button) editpopupView.findViewById(R.id.button6);
        btnDismiss.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                editpopupWindow.dismiss();
            }
        });
    }   


    @Override
    public void onClick(View v) {
        CheckBox selection = (CheckBox)v;
        //selection.setCompoundDrawablesWithIntrinsicBounds(R.drawable.clickfolders,0, 0, 0);       
        selection.requestFocus();       
        if (selection.isChecked() == true) {
            selection.setBackground(getResources().getDrawable(
                    R.drawable.uncheck1));
            //selection.setButtonDrawable(android.R.color.transparent);
        } else {
            selection.setBackground(getResources().getDrawable(
                    R.drawable.check_btn));
            //selection.setButtonDrawable(android.R.color.transparent);
        }
        //Toast.makeText(getBaseContext(),  selection.getTag()+ " was pressed!", Toast.LENGTH_SHORT).show();
    }

My Layout XML :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_black_transparent_90"    
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="26dp"
        android:layout_marginTop="18dp"
        android:text="@string/FOLDERS"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/darker_gray" />

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView1"
        android:layout_marginRight="39dp"
        android:visibility="gone" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="22dp"
            android:layout_height="22dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:src="@drawable/ic_red_edit" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/imageView1"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@+id/imageView1"
            android:text="EDIT"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/darker_gray"
            android:textSize="16dp" />
    </RelativeLayout>

    <GridView
        android:id="@+id/gridEditView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/ddd"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:background="@android:color/transparent"        
        android:horizontalSpacing="1dp"
        android:numColumns="2"
        android:verticalSpacing="1dp" >
    </GridView>

    <RelativeLayout
        android:id="@+id/ddd"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" >

        <Button
            android:id="@+id/button6"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="4dp"
            android:layout_marginLeft="4dp"
            android:layout_marginTop="4dp"
            android:background="@drawable/ic_red_cancel_47"
            android:gravity="center"
            android:visibility="visible" />

        <Button
            android:id="@+id/btnAddActivity"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="4dp"
            android:layout_marginTop="4dp"
            android:background="@drawable/ic_red_ok_47" />
    </RelativeLayout>

</RelativeLayout>

Cordova PhoneGap upgrade to 5.1.1 from 2.2.0

I have Cordova application which is version 2.2.0. Now I want to upgrade, I have done upgrade part, after upgrading, application images are not display, it came blank screen. even splash screen also not came. Here is my code

Seem problem in my BaseScreen.js. I have given alert & check HomeScreen.js before execute basescreen part, the alert is working. but Basescreen also alert came,

HomeScreen.js

var HomeScreen = BaseScreen
    .extend({
        templateContent : "<ul id='homeBtnsList'>\
        alert("-----HI-Home in---");
                     <li id='playGame'><img src='interface/play-icon@2x.png'><div class='gloss'></div><span>" + language.HOME_PLAY_GAME + "</span></li>\
                     <li id='viewScore'><img src='interface/scoreboard-icon@2x.png'><div class='gloss'></div><span>" + language.HOME_VIEW_SCORE + "</span></li>\
                     <li id='viewRules'><img src='interface/instruction-icon@2x.png'><div class='gloss'></div><span>" + language.HOME_VIEW_RULES + "</span></li>\
                </ul>\
                <div class='copyright'>Copyright &copy; Pearson</div>\
                <div class='about'></div>\
                <div id='footer'>\
                    ",
        headerClass : "head homehead",
        screenClass : "",

        initialize : function() {
            _.bindAll(this, "handleRenderComplete", "handleItemClick", "initScroll", "closeAboutUs", "aboutUsAction");
            BaseScreen.prototype.initialize(this);
            this.bind(AppEvent.RENDER_COMPLETE, this.handleRenderComplete);
            _.extend(this, Backbone.Events);
        },

        render : function() {
            this.element = this.el;
            var divString = BaseScreen.prototype.render(this);
            return divString;
        },

        show : function() {
            this.setScreenReady();
        },

        handleRenderComplete : function() {
            $("#homeBtnsList li", this.obj).bind(AppEvent.CLICK, this.handleItemClick);
            $("div.about", this.obj).bind(AppEvent.CLICK, this.aboutUsAction);

            if(isIOS()) {
                ShareKitPlugin.prototype.logoutFromTwitter();
                ShareKitPlugin.prototype.logoutFromFacebook();
                _.delay(navigator.splashscreen.hide,1000);
            }

        },

        setScreenReady : function() {
            var obj = {
                screenId : this.model.toString()
            };
            this.trigger(AppEvent.SCREEN_READY, obj);
        },

        handleItemClick : function(e) {
            // alert(e.target.nodeName + " : " +
            // e.target.parentNode.nodeName);
            var tar = e.target;
            if (e.target.nodeName.toLowerCase() != "li") {
                tar = e.target.parentNode;
                // return;
            }
            // alert(tar.nodeName + " : " + tar.parentNode.nodeName);
            et = tar;

            e.preventDefault();

            var obj = {};

            id = $(et).attr('id') ? $(et).attr('id') : $(et).find('li')
                    .attr('id');

            switch (id) {
            case "playGame":
                obj.screenId = AppConst.GROUP_SCREEN;
                this.trigger(AppEvent.GOTO_SCREEN, obj);
                return;
            case "viewScore":
                obj.screenId = AppConst.SCORE_HOME_SCREEN;
                this.trigger(AppEvent.GOTO_SCREEN, obj);
                return;
            case "viewRules":
                obj.screenId = AppConst.INSTRUCTION_SCREEN;
                this.trigger(AppEvent.GOTO_SCREEN, obj);
                return;
            default:
                return;
            }
            ;

        },


    initScroll: function(obj){
        utils.log("SCROLL ACTIVE")
        this.iScroll = new iScroll($("#helpContent").get(0), {desktopCompatibility:true});
    },

    aboutUsAction: function(){

        var obj = {};
        obj.screenId = AppConst.ABOUTUS_SCREEN;
        this.trigger(AppEvent.GOTO_SCREEN, obj);

    },

    closeAboutUs: function(){

        $("#helpWrapper #helpContent").html("");
        $('#helpWrapper').hide();
        this.iScroll.destroy();

    },

    destroy : function() {
            utils.log("destroy ", this.model.get('myId'));
            //$("#homeBtnsList li", this.obj).unbind();
            $("div.about", this.obj).unbind();
            this.unbind();
            BaseScreen.prototype.destroy(this);
        }
    })

This is my BaseScreen.js

    var BaseScreen = Backbone.View.extend
({
    templateStart:"<div id='<%=myId%>' class='screen <%=screenClass%>'>\
                        <!--header-->\
                        <div id='header' class='head <%=headerClass%>'>\
                            <!--LEFT BTN-->\
                            <div class='header-left-btn <%=leftBtnClass%>'>\
                                    <span><%=leftLabel%></span>\
                                </div>\
                            <!--TITLE-->\
                            <h1><%=title%></h1>\
                            <!--RIGHT BTN-->\
                            <div class='header-right-btn <%=rightBtnClass%>'>\
                            <%=rightLabel%>\
                                </div>\
                            </div>\
                        <div class='content'>",
    templateContent:"",
    templateClose:"</div></div>",
    element:null,

    render:function(extendedObject)
    {
        var curObj = extendedObject || this;
        //console.log('screen Element: ' + curObj.el.get(0).id)
        var baseScreenModel = {};

        if(curObj.model){
            baseScreenModel = curObj.model.toJSON();
        }

        var thatId = baseScreenModel.myId;
        var template = _.template(curObj.templateStart + curObj.templateContent + curObj.templateClose);
        var data = _.extend(baseScreenModel, {
            screenClass: curObj.screenClass,
            headerClass: curObj.headerClass
        });

        // curObj.element.append(template(baseScreenModel));
        curObj.element.append(template(baseScreenModel));

        // //console.log(template(baseScreenModel))
        // //console.log(" >>>> " + thatId)
        //var screen = curObj.element.find("#" + thatId);

        var screen = $("#" + thatId);
        ////console.log("appended node " + screen.length);

        if(screen.length <= 0){
            ////console.log("length is zero")
            //console.log("delay .....");
            _.delay(BaseScreen.prototype.render, 1000, curObj);
            return curObj.element;;
        }

        ////console.log("appended node == " + screen.html());

        var sClass = curObj.screenClass || "";
        var hClass = curObj.headerClass || "";

        //screen.find(".screen").addClass(sClass);
        //screen.find("#header").addClass(hClass);

        $(screen).addClass(sClass);
        $("#header", $(screen)).addClass(hClass);



        // screen.find("#leftElement").bind(AppEvent.CLICK, curObj.handleButtonClick);
        // screen.find("#rightElement").bind(AppEvent.CLICK, curObj.handleButtonClick);
        $("#leftElement", $(screen)).bind(AppEvent.CLICK, function(e){
            ////console.log("#leftElement ", e.target);
            that.trigger(AppEvent.HEADER_ITEM_CLICKED, AppConst.HEADER_LEFT_ELEMENT);
        });
        $("#rightElement", $(screen)).bind(AppEvent.CLICK, function(e){that.trigger(AppEvent.HEADER_ITEM_CLICKED, e.target.id);});
        curObj.trigger(AppEvent.RENDER_COMPLETE);
        return curObj.element;      
    },

    initialize:function(extendedObject)     //only called when extending BaseScreen
    {
        var curObj = extendedObject||this;
        //_.bindAll(curObj, "handleButtonClick");
        _.extend(curObj, Backbone.Events);
    },

    handleButtonClick:function(e)
    {
        this.trigger("buttonClick", e.target.id);
    },

    destroy:function(extendedObject) {
        var that = extendedObject||this;
        var thatId = that.model.get('myId');
        var screen = that.element.find("#" + thatId);
        screen.find("#leftElement").unbind();
        screen.find("#rightElement").unbind();      
        //debug.log("destroy base screen for " + thatId);
        screen.remove();
    },

    handleHeaderLeftClicked:function() {
        //console.log("left clicked", this);        
        if(DEVICE_TYPE == DEVICE_ANDROID || DEVICE_TYPE == DEVICE_ANDROID_TAB || DEVICE_TYPE == DEVICE_PC) {
            Functions.prototype.exit();
           }
    }

})

index.html:

    <!DOCTYPE html>
<html manifest="appcache.manifest">
    <head>
        <meta name="apple-mobile-web-app-capable" content="yes" >
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" >
        <title>My Application</title>

        <link href="css/global.css" media="all" rel="stylesheet" type="text/css">


        <script src="com/external/underscore.js" ></script>
        <script src="com/external/iscroll.js" ></script>

        <script src="com/external/zepto.js" ></script>
        <script src="com/external/ajax.js" ></script>
        <script src="com/external/touch.js" ></script>
        <script src="com/external/event.js" ></script>
        <script src="com/external/effects.js" ></script>
        <script src="com/external/detect.js" ></script>
        <script src="com/external/jsOAuth-1.3.1.js" ></script>
        <script src="com/external/json2.js" ></script>
        <script src="com/external/jsPatch.js" ></script>
        <script src="com/external/backbone.js" ></script>

        <script src="com/imfinity/comp/webkitdragdrop.js" ></script>
        <script src="com/imfinity/utils/jsExtended.js" ></script>
        <script src="com/imfinity/utils/stopwatch.js" ></script>

        <script src="com/imfinity/screen/BaseScreenVO.js" ></script>
        <script src="com/imfinity/screen/BaseScreen.js" ></script>


        <script src="com/sns/init.js"></script>

        <script src="com/sns/jsonParser.js" ></script>
        <script src="com/sns/utilities.js" ></script>
        <script src="com/sns/language.js" ></script>
        <script src="com/sns/AppConst.js" ></script>
        <script src="com/sns/services.js" ></script>
        <script src="com/sns/db.js" ></script>
        <script src="com/sns/AppEvent.js" ></script>
        <script src="com/sns/controller/main.js" ></script>

        <script src="com/sns/model/HomeScreenVO.js" ></script>
        <script src="com/sns/view/HomeScreen.js" ></script>

        <script src="com/sns/view/helpScreenView.js" ></script>
        <script src="com/sns/model/helpScreenVO.js" ></script>

        <script src="com/sns/view/aboutScreenView.js" ></script>
        <script src="com/sns/model/aboutScreenVO.js" ></script>

        <script src="com/sns/model/scoreHomeScreenVO.js" ></script>
        <script src="com/sns/view/scoreHomeScreenView.js" ></script>


        <script src="com/sns/view/resultsScreenView.js" ></script>
        <script src="com/sns/model/resultScreenVO.js" ></script>

        <script src="com/sns/view/activity/reorderingView.js" ></script>
        <script src="com/sns/view/activity/tapNplaceView.js" ></script>



        <!--script src="com/sns/sns-minified.js"></script-->


    </head>
    <body onload="onLoad()"  style="overflow: hidden;">
        <div class='insOverlay'>
            <div id='instructionsWrapper'><img/>
            </div>
        </div>
        <div id="overlay">
            <div id="preloader"></div>
            <div id="genericHUD" >
                <div id='HUDcontent'><img src='interface/load.png'>
                </div>
            </div>
        </div>
        <div id="toast" class="Overlay_toast" style="display: none;">
            <div class="toast_message"></div>
        </div>

        <div id='helpWrapper' class="overlay darkShade" style="display: none;">
            <div class="helpWindow">
                <span id='helpClose' class="close-pop-up"></span>
                <h1>Help</h1>
                <div id='helpContent' class="helpContent"></div>
            </div>
        </div>

        <div id="banner" class="overlay darkShade"></div>

        <div class="modalOverlay" style="display: none;">
            <div class="modalWindow">
                <span class="close-pop-up"></span>
                <h1 class="whiteHeading">Share</h1>
                <p id='email' class="share-btn share-with-friend">

                </p>
                <p id='twitter' class="share-btn share-on-twitter">

                </p>
                <p id='facebook' class="share-btn share-on-facebook">

                </p>
            </div>
        </div>

        <div class="editTextOverlay">
            <div class='editTextPopup'>
                <div class="editTextHeader">
                    <span id="leftBtn" class="editTextButton">Cancel</span>
                    <span id="rightBtn"  class="editTextButton"></span>
                </div>
                <textarea rows="4" autocomplete="off" spellcheck="false" style="outline: none;" maxlength="140"></textarea>
            </div>
        </div>

        <div class="normalOverlay" id="confirmBox">
            <div class='normalTextPopup'>
            <h2>Confirm</h2>
                <div id="confirmMsg">
                    message
                </div>
                <div>
                    <span id="leftBtn" class="normalTextButton"></span>
                    <span id="rightBtn"  class="normalTextButton"></span>
                </div>

            </div>
        </div>

        <div id="wrap" >
            <div id="screens" >
                <div id='questionPlayer' class='screen'></div>
            </div>

        </div>
    </body>
</html>

cofig : res/xml/config.xml

    <?xml version='1.0' encoding='utf-8'?>
<cordova>
    <access origin="http://127.0.0.1*" />
    <access origin=".*" />
    <log level="DEBUG" />
    <preference name="useBrowserHistory" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="SplashScreen" value="splash" />
    <preference name="SplashScreenDelay" value="10000" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <plugins>
        <plugin name="App" value="org.apache.cordova.App" />
        <plugin name="Geolocation" value="org.apache.cordova.GeoBroker" />
        <plugin name="Device" value="org.apache.cordova.Device" />
        <plugin name="Accelerometer" value="org.apache.cordova.AccelListener" />
        <plugin name="Compass" value="org.apache.cordova.CompassListener" />
        <plugin name="Media" value="org.apache.cordova.AudioHandler" />
        <plugin name="Camera" value="org.apache.cordova.CameraLauncher" />
        <plugin name="Contacts" value="org.apache.cordova.ContactManager" />
        <plugin name="File" value="org.apache.cordova.FileUtils" />
        <plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager" />
        <plugin name="Notification" value="org.apache.cordova.Notification" />
        <plugin name="Storage" value="org.apache.cordova.Storage" />
        <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer" />
        <plugin name="Capture" value="org.apache.cordova.Capture" />
        <plugin name="Battery" value="org.apache.cordova.BatteryListener" />
        <plugin name="SplashScreen" value="org.apache.cordova.SplashScreen" />
        <plugin name="Echo" value="org.apache.cordova.Echo" />
        <plugin name="Globalization" value="org.apache.cordova.Globalization" />
        <plugin name="SQLitePlugin" value="com.phonegap.plugins.SQLitePlugin" />
        <plugin name="FlurryPlugin" value="com.phonegap.plugins.Flurry" />
        <plugin name="AndroidUtilsPlugin" value="com.phonegap.plugins.AndroidUtilsPlugin" />
        <plugin name="ChildBrowserPlugin" value="com.phonegap.plugins.ChildBrowserPlugin" />
    </plugins>
    <feature name="File">
        <param name="android-package" value="org.apache.cordova.file.FileUtils" />
        <param name="onload" value="true" />
    </feature>
</cordova>

Please let me know what is an issue. After upgrading only , I am facing this isssue, could you please guide me about this.

What is the best approach for autostarting an Android app on a dedicated device?

I am new to Android programming, and am working on an app that will provide an interface to an appliance. The Android device the app will run on will be attached to the appliance and used only for controlling the appliance. The app I am working on will be the only app ever run on the dedicated Android device.

One of the requested features is to have the app start automatically when the Android device starts up. I have implemented this feature by detecting the ACTION_BOOT_COMPLETED intent, as described in this thread. I have, however, seen an alternative approach recommended of making the app the home screen, as described in this thread.

I realize that implementing the autostart feature by detecting ACTION_BOOT_COMPLETED, as I have done, may well not be the best approach to take for Android apps in general. But, as mentioned, in my case the app I am developing will be the only app ever used on the device. Given that, is the approach I am taking reasonable? Or is there a better way to implement the autostart feature?

Note that one consideration is ease of configuring the Android device. For the approach I am taking, there will be one manual step required, of launching the app the first time. But it looks like there would also be a manual step required if I took the alternative approach of making the app the home screen, so in that regard there would be no advantage to taking that approach.

Thank you for your help!

EDIT: I have tried setting the app as the home screen by modifying AndroidManifest.xml as Holmes suggested below. Here is what I've found so far in my comparison of the two approaches: (1) The code is much simpler using the home screen approach, requiring only a minor tweak to AndroidManifest.xml rather than more substantial changes and an additional BroadcastReceiver class. (2) The setup procedure is slightly more complicated using the home screen approach since you have to do more than just open the app, but not substantially more complicated. (3) The home screen approach does a better job of confining the user to the single app since he can't use the default home screen to launch other apps. Based on these results, I will probably use the home screen approach.

Android nullpointer Screenslider (view pager)

I have downloaded the demo screen slider from android (http://ift.tt/1AtG7DO). I've tried to put this in my own project but i get this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{http://ift.tt/1N74MTn}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
        at android.app.ActivityThread.access$900(ActivityThread.java:169)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5479)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.pws.test.demo.D_D_RondleidingMenu.SetupUitgebreideRondleidingButton(D_D_RondleidingMenu.java:24)
        at com.pws.test.demo.D_D_RondleidingMenu.onCreate(D_D_RondleidingMenu.java:17)
        at android.app.Activity.performCreate(Activity.java:5451)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
            at android.app.ActivityThread.access$900(ActivityThread.java:169)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5479)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

This is my code:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
/**
 * Demonstrates a "screen-slide" animation using a {@link ViewPager}. Because {@link ViewPager}
 * automatically plays such an animation when calling {@link ViewPager#setCurrentItem(int)}, there
 * isn't any animation-specific code in this sample.
 *
 * <p>This sample shows a "next" button that advances the user to the next step in a wizard,
 * animating the current screen out (to the left) and the next screen in (from the right). The
 * reverse animation is played when the user presses the "previous" button.</p>
 *
 * @see
 */
public class E_D_Uitgebreid extends FragmentActivity {
    /**
     * The number of pages (wizard steps) to show in this demo.
     */
    private static final int NUM_PAGES = 3;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

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

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When changing pages, reset the action bar actions since they are dependent
                // on which page is currently active. An alternative approach is to have each
                // fragment expose actions itself (rather than the activity exposing actions),
                // but for simplicity, the activity provides the actions in this sample.
                invalidateOptionsMenu();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_e__d__uitgebreid, menu);

        menu.findItem(R.id.action_previous).setEnabled(mPager.getCurrentItem() > 0);

        // Add either a "next" or "finish" button to the action bar, depending on which page
        // is currently selected.
        MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
                (mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
                        ? R.string.action_finish
                        : R.string.action_next);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // Navigate "up" the demo structure to the launchpad activity.
                // See http://ift.tt/HxQCh0 for more.
                NavUtils.navigateUpTo(this, new Intent(this, D_D_RondleidingMenu.class));
                return true;

            case R.id.action_previous:
                // Go to the previous step in the wizard. If there is no previous step,
                // setCurrentItem will do nothing.
                mPager.setCurrentItem(mPager.getCurrentItem() - 1);
                return true;

            case R.id.action_next:
                // Advance to the next step in the wizard. If there is no next step, setCurrentItem
                // will do nothing.
                mPager.setCurrentItem(mPager.getCurrentItem() + 1);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }


    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return E_D_Uitgebreid_Fragment.create(position);
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
}

And the fragment:

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * A fragment representing a single step in a wizard. The fragment shows a dummy title indicating
 * the page number, along with some dummy text.
 *
 * <p>This class is used by the  and {@link
 * } samples.</p>
 */

public class E_D_Uitgebreid_Fragment extends Fragment {
    /**
     * The argument key for the page number this fragment represents.
     */
    public static final String ARG_PAGE = "page";

    /**
     * The fragment's page number, which is set to the argument value for {@link #ARG_PAGE}.
     */
    private int mPageNumber;

    /**
     * Factory method for this fragment class. Constructs a new fragment for the given page number.
     */
    public static E_D_Uitgebreid_Fragment create(int pageNumber) {
       E_D_Uitgebreid_Fragment fragment = new E_D_Uitgebreid_Fragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, pageNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public E_D_Uitgebreid_Fragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageNumber = getArguments().getInt(ARG_PAGE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout containing a title and body text.
        ViewGroup rootView = (ViewGroup) inflater
                .inflate(R.layout.activity_e__d__uitgebreid__fragment, container, false);

        // Set the title view to show the page number.
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                Articles.paginatitel[mPageNumber]);

        ((TextView) rootView.findViewById(android.R.id.text2)).setText(
                Articles.paginainhoud[mPageNumber]);

        ((ImageView) rootView.findViewById(android.R.id.background)).setImageResource(Articles.afbeelding[mPageNumber]);

        return rootView;
    }




    /**
     * Returns the page number represented by this fragment object.
     */
    public int getPageNumber() {
        return mPageNumber;
    }
}

I've already changed this, but this didn't work:

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
    }

and this:

@Override
    public android.support.v4.app.Fragment getItem(int position) {
        return E_D_Uitgebreid_Fragment.create(position);
    }

Application should not display in recent app list after finish the activity if app was not displaying recent app list previously

Step 1- Application is not exist in recent app list (App has been removed from recent app list).
Step 2- As soon as I got notification open IncomingCall activity, User accept the call.
Step 3- User click on disconnect button finish the IncomingCall activity.

Problem- Application showing in recent app list even app was not in recent app list previously.

Manifest entry

<activity
android:name=".activities.IncomingCall"
android:excludeFromRecents="true"
android:launchMode="singleTop"
android:screenOrientation="portrait" >
</activity>

In the activity using

public void onClick(View v) {
switch (v.getId()) {
case R.id.onCallDisconnectButton:
phoneCallBaseClass.disconnect();
IncomingCall.this.finish();
break;
  }
}

And also I have tried below link but it will work when app already exist in background

Remove app from recent apps programmatically

OR Is there any other way to show incoming call view So that it will not persist in history.

Thanks

What is the best / clean way to use Database in Android?

Is there a clean way to use Database in Android ? Like using Annotations, Dependency Injection ... ?

What do you people use for this ?

setProgressBarIndeterminateVisibility(true) doesn't work

I wish to use a progressbar while an asynctask is working but just doesn't appear, I've got the following code:

protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_score);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actualizartablaF();
}

private void actualizarTablaF(){
    setProgressBarIndeterminate(true);
    setProgressBarIndeterminateVisibility(true);
    SharedPreferences sp = getSharedPreferences("Preferences", Activity.MODE_PRIVATE);
    String param = "?name="+sp.getString("Name","Josema");
    new ScoresAsyncTask().execute(param);
}

And, in the postExecute of my asyncTask I've got this:

protected void onPostExecute(HighScoreList highScoreList) {
        scoreActivity.this.setProgressBarIndeterminate(false);
        scoreActivity.this.setProgressBarIndeterminateVisibility(false);
}

It just doesn't show any progress indicator and I can't find the mistake. Thank you.

Writing files internally

Within my app I am trying to write a file, which I can then internally read from.

Would anyone have an example of how to write files to the installation folders of app?

how to upload the video android to file zilla server

How to upload the video android to Ftp server.i have try to code of more time but does not work for me..please help me...My problem is file not found exception in client upload function how to clear this error..Please help me..

    public class MainActivity extends Activity {

    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;
    String sourceFileUri;
    Button myButton;
    SurfaceHolder surfaceHolder;
    boolean recording;
    /********* work only for Dedicated IP ***********/
    static final String FTP_HOST = "upload.com";

    /********* FTP USERNAME ***********/
    static final String FTP_USER = "users";

    /********* FTP PASSWORD ***********/
    static final String FTP_PASS = "12345";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recording = false;

        setContentView(R.layout.activity_main);

        // Get Camera for preview
        myCamera = getCameraInstance();
        myCamera.setDisplayOrientation(90);
        if (myCamera == null) {
            Toast.makeText(MainActivity.this, "Fail to get Camera",
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        RelativeLayout myCameraPreview = (RelativeLayout) findViewById(R.id.relative);
        myCameraPreview.addView(myCameraSurfaceView);

        myButton = (Button) findViewById(R.id.btn_capture);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    Button.OnClickListener myButtonOnClickListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (recording) {

                // stop recording and release camera
                mediaRecorder.stop(); // stop the recording
                Log.e("mediastop", "" + mediaRecorder);

                Toast.makeText(MainActivity.this, "Video captured!",
                        Toast.LENGTH_LONG).show();


                doFileUpload();
            //  Log.e("fileupload", "" + f);
                releaseMediaRecorder(); // release the MediaRecorder object

                recording = false;

                // Exit after saved
                // finish();
            } else {

                // Release Camera before MediaRecorder start
                releaseCamera();

                if (!prepareMediaRecorder()) {
                    Toast.makeText(MainActivity.this,
                            "Fail in prepareMediaRecorder()!\n - Ended -",
                            Toast.LENGTH_LONG).show();
                    finish();
                }

                mediaRecorder.start();
                Toast.makeText(MainActivity.this, "Start Recording..",
                        Toast.LENGTH_LONG).show();

                recording = true;
                // myButton.setText("STOP");
            }
        }
    };

    private Camera getCameraInstance() {
        // TODO Auto-generated method stub
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private File getOutputMediaFile() {
        // To be safe, you can check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getPath().toString()+ "/gg/");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("CameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath()  /*File.separator
                */+ "VID_" + timeStamp + ".mp4");
        Log.e("mediafile", "" + mediaFile);
        return mediaFile;
    }

    private boolean prepareMediaRecorder() {
        myCamera = getCameraInstance();
        myCamera.setDisplayOrientation(90);
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile
                .get(CamcorderProfile.QUALITY_HIGH));
        mediaRecorder.setOrientationHint(90);
        mediaRecorder.setOutputFile(getOutputMediaFile().getPath());
        Log.e("mediarecorder", "" + mediaRecorder);
        mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
        mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
        /*
         * try {
         * 
         * doFileUpload();
         * 
         * } catch (ParseException e) { // TODO Auto-generated catch block
         * e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated
         * catch block e.printStackTrace(); }
         */
        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder()
                .getSurface());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    public void doFileUpload() {
        if (android.os.Build.VERSION.SDK_INT > 16) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
    //  File f = new File(""+getOutputMediaFile().getPath());
        //Log.e("f", "" + f);

        Uri uri = Uri.parse(""+getOutputMediaFile().getPath());
        Log.e("uri",""+uri);
        File filename = new File(uri.getPath());
        Log.e("filename",""+filename);
        // File fis=fileName;
        // Log.e("fis",""+fis);
        FTPClient client = new FTPClient();

        try {

            client.connect(FTP_HOST,21);
            Log.e("clientconnect", "" + client);
            client.login(FTP_USER, FTP_PASS);
            Log.e("clientlogin", "" + client);
            client.setType(FTPClient.TYPE_BINARY);
            Log.e("clienttype", "" + client);
            client.changeDirectory("/gg/");
            Log.i("", "$$$$$$$$$$$$$$$$$" + ("/gg/"));
        //  int reply = client.getReplyCode();

            client.setPassive(true);
            Log.e("clientpassive", "" + client);
            client.noop();
            //client.setAutoNoopTimeout( 30000);
            Log.e("clientnoop", "" + client);
            client.upload(filename,new MyTransferListener());
            Log.e("filenameupload", "" + filename);
            Log.e("clientupload", "" + client);
            // Log.e("file",""+fileName);
            Toast.makeText(getBaseContext(), " transferred ..." + client,
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                client.disconnect(true);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }

    public class MyTransferListener implements FTPDataTransferListener {

        public void started() {

            // btn.setVisibility(View.GONE);
            // Transfer started
            Toast.makeText(getBaseContext(), " Upload Started ...",
                    Toast.LENGTH_SHORT).show();
            // System.out.println(" Upload Started ...");
        }

        public void transferred(int length) {

            // Yet other length bytes has been transferred since the last time
            // this
            // method was called
            Toast.makeText(getBaseContext(), " transferred ..." + length,
                    Toast.LENGTH_SHORT).show();
            // System.out.println(" transferred ..." + length);
        }

        public void completed() {

            // btn.setVisibility(View.VISIBLE);
            // Transfer completed

            Toast.makeText(getBaseContext(), " completed ...",
                    Toast.LENGTH_SHORT).show();
            // System.out.println(" completed ..." );
        }

        public void aborted() {

            // btn.setVisibility(View.VISIBLE);
            // Transfer aborted
            Toast.makeText(getBaseContext(),
                    " transfer aborted , please try again...",
                    Toast.LENGTH_SHORT).show();
            // System.out.println(" aborted ..." );
        }

        public void failed() {

            // btn.setVisibility(View.VISIBLE);
            // Transfer failed
            System.out.println(" failed ...");
        }
        // Jibble.
    }


    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder(); // if you are using MediaRecorder, release it
                                // first
        releaseCamera(); // release the camera immediately on pause event
    }

    private void releaseMediaRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.reset(); // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
            myCamera.lock(); // lock camera for later use
        }
    }

    private void releaseCamera() {
        if (myCamera != null) {
            myCamera.release(); // release the camera for other applications
            myCamera = null;
        }
    }

    public class MyCameraSurfaceView extends SurfaceView implements
            SurfaceHolder.Callback {

        private SurfaceHolder mHolder;
        private Camera mCamera;

        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;
            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format,
                int weight, int height) {
            // If your preview can change or rotate, take care of those events
            // here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (mHolder.getSurface() == null) {
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e) {
                // ignore: tried to stop a non-existent preview
            }

            // make any resize, rotate or reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e) {
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            // The Surface has been created, now tell the camera where to draw
            // the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub

        }
    }
}