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?