I have a problem with my alarm manager.

I want execute my code every 2 minutes so i made an alarm like this :

AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 120000, pendingIntent);

But when i test this, my pendingIntent is executed every minutes.

If i start the application at 15:05:30 the first start of my pending intent is at : 15:06:00 and after every minutes.

I want to start when i start the application and after every 2 minutes.

Thx for your answers :)

I am extending spinner to add some functionality, I am trying to make the spinner a dropdown rather than dialog. So i am changing the spinner mode to drop down.

When I use this constructor, i get an exception

<mypackage.mypackage.MultiSelectionSpinner
                    android:id="@+id/my_spinner"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:spinnerMode="dropdown"
                    android:layout_weight="1"
                    android:padding="10dp" />


mySpinner = (MultiSelectionSpinner) findViewById(R.id.my_spinner);

public class MultiSelectionSpinner extends Spinner{
    public MultiSelectionSpinner(Context context, AttributeSet attrs,int defStyle,int mode) {
        super(context, attrs,defStyle,mode);
        simple_adapter = new CustomerMultiSelectionSpinnerAdapter(context,
                R.layout.customer_spinner_adapter_view, new ArrayList<String>() );
        ...
    }

Caused by: android.view.InflateException: Binary XML file line #101: Error inflating class mypackage.mypackage.MultiSelectionSpinner at android.view.LayoutInflater.createView(LayoutInflater.java:603) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696) at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method) at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631) at android.view.LayoutInflater.inflate(Native Method) at android.view.LayoutInflater.inflate(LayoutInflater.java:397) at android.view.LayoutInflater.inflate(LayoutInflater.java:353) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:320) at android.app.Activity.setContentView(Activity.java:1895) at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:217) at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:110) at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:77) at mypackage.mypackage.MainActivity.onCreate(MainActivity.java:63) (which is basically the declaration mySpinner = (MultiSelectionSpinner) findViewById(R.id.my_spinner);) android.app.Activity.performCreate(Activity.java:5133) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2293) ... 12 more Caused by: java.lang.NoSuchMethodException: [class android.content.Context, interface android.util.AttributeSet] at java.lang.Class.getConstructorOrMethod(Class.java:423) at java.lang.Class.getConstructor(Class.java:397) at android.view.LayoutInflater.createView(LayoutInflater.java:568) ... 33 more

This however, works well, except the spinner is in dialog mode

public MultiSelectionSpinner(Context context, AttributeSet attrs) {
    super(context, attrs);
    simple_adapter = new CustomerMultiSelectionSpinnerAdapter(context,
            R.layout.customer_spinner_adapter_view, new ArrayList<String>() );
    super.setAdapter(simple_adapter);
}

I want set volume during sip audio call. So I try with with this following code but doesn't work.

Any idea ? Thanks for your response!

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        final int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        final int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if(volume + 1 <= maxVolume) {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume + 1, 0);
        }
        return true;
    } else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        final int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        final int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if(volume - 1 > 0) {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume - 1, 0);
        }
        return true;
    } else {
        return super.onKeyDown(keyCode, event);
    }
}

I'm new to developing android apps. And already overchallenged with my first project. My app should be able to save a list of EditText fields to a text file by clicking a "save"-Button. But I got no success to write a file to my SD-card.

My code: (function in MainActivity.java called by the button)

public void saveData(View view){
        try{
        File sdcard = Environment.getExternalStorageDirectory();
        // to this path add a new directory path
        File dir = new File(sdcard.getAbsolutePath() + "/myapp/");
        // create this directory if not already created
        dir.mkdir();

        // create the file in which we will write the contents

        File file = new File(dir, "datei.txt");


        FileOutputStream os = new FileOutputStream(file);
        String data = "some string";
        os.write(data.getBytes());
        os.flush();
        os.close();
        }
        catch (IOException e){
            Log.e("com.sarbot.FitLogAlpha", "Cant find Data.");
        }
    }

With Google I found another way:

public void saveData3(View view){
    FileWriter fWriter;
    File sdCardFile = new File(Environment.getExternalStorageDirectory() + "/datafile.txt");
    Log.d("TAG", sdCardFile.getPath()); //<-- check the log to make sure the path is correct.
    try{
         fWriter = new FileWriter(sdCardFile, true);
         fWriter.write("CONTENT CONTENT UND SO");
         fWriter.flush();
         fWriter.close();
     }catch(Exception e){
              e.printStackTrace();
     }
}

In my manifest.xml I set the permissions:

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

And the function from developer guide returns me True -> SD-card is writable.

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

In the res/layout/activity_main.xml are some TextViews and EditText and a save button with android:onClick="saveData" argument. The function is called. The SD-card is writable. And no IO errors. But after pressing the button (without error) there is still no new file on my SD-card. I already tried to create the file manually and just append but nothing changed. I tried some other function with BufferedWriter too .. but no success.

I'm running my Sony Xperia E with USB-Debug mode. Unmount and mounted the SD-card on my PC but cant find the file. Maybe it is only visible for the phone? It doesn't exist? I don't know what to do because I get no errors. I need the content of this file on my computer for calculations.

I am trying to change ActionBar title color. I tried different ways to do it. But I could not solve this problem. I have created my own actionbar theme in values/styles.xml and values-14/styles.xml

values/styles.xml

<style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light">   
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="background">@color/grey_actionbar_background</item>
    <item name="icon">@drawable/ic_launcher</item>
    <item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>
</style>

<style name="MyActionBarTabText" parent="@style/Widget.AppCompat.Light.ActionBar.TabText">
    <item name="android:textColor">@color/grey_text</item>
</style>

values-v14/styles.xml

<style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@color/grey_actionbar_background</item>
    <item name="background">@color/grey_actionbar_background</item>
    <item name="android:icon">@drawable/ic_launcher</item>
    <item name="icon">@drawable/ic_launcher</item>
    <item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>
    <item name="android:actionBarTabTextStyle">@style/MyActionBarTabText</item>
</style>

<style name="MyActionBarTabText" parent="@style/Widget.AppCompat.Light.ActionBar.TabText">
    <item name="android:textColor">@color/grey_text</item>
</style>

grey_text color is #58585A. But when I am running on 4.3 device, ActionBar title color is F3F3F3.

I am wondering why this is happening. How to solve this problem?

enter image description here

I am working Wifi Base application in which i have to connect two or more device which are on same Wifi Network and find the position of device. i have connected two device using JMDSN Library orver Wifi, now my goal is to find the position device with respect to another device.

I have option to find Lat-Long and find distance between two devices but it's not reliable.

Another option is to find location using sensors but i do not have any idea how to find location using sensors and is it full fell my requirements.

Please suggest me right way to achieve this.

Any help will be highly appreciated.

I want to get a screenshot in a scrollable view (ViewPager), but I´m only getting a image from what is in the screen.

I have a Viewpager with two childrens

android.support.v4.view.PagerTitleStrip NoSaveStateFrameLayout

I´m using this code to get the screenshot

private Bitmap screenShot(View view) {

    Bitmap capture = null;

    view.setDrawingCacheEnabled(true);
    capture = Bitmap.createBitmap(view.getDrawingCache());
    view.setDrawingCacheEnabled(false);

    return capture;
}

I need to capture the hole content.

so i'm using angular and the cordova Google analytics plugin

And the logs say i'm connected but the view in google analytics doesn't show any users connected to my app. does anyone see what i'm missing?

This is how i setup the connection:

        var auth = JSON.parse(window.localStorage['auth'])
        var userID = auth.userID;

        $cordovaGoogleAnalytics.debugMode();
        $cordovaGoogleAnalytics.startTrackerWithId('UA-55148678-1');
        $cordovaGoogleAnalytics.setUserId(userID);
        $cordovaGoogleAnalytics.trackView('We Alert Map');

And these are the logs:

09-25 14:24:18.712: W/ContextImpl(31566): Failed to ensure directory: /storage/ext_sd/Android/data/nl.studionewmedia.wealert/files
09-25 14:24:18.712: W/ContextImpl(31566): Failed to ensure directory: /storage/ext_sd/Android/data/nl.studionewmedia.wealert/files
09-25 14:24:18.712: W/ContextImpl(31566): Failed to ensure directory: /storage/ext_sd/Android/data/nl.studionewmedia.wealert/cache
09-25 14:24:23.012: W/CordovaPlugin(31566): Attempted to send a second callback for ID: UniversalAnalytics712371046
09-25 14:24:23.012: W/CordovaPlugin(31566): Result was: "Invalid action"
09-25 14:24:23.022: V/GAV3(31566): Thread[JavaBridge,5,main]: Dispatch period set with null handler. Dispatch will run once initialization is complete.
09-25 14:24:23.022: W/CordovaPlugin(31566): Attempted to send a second callback for ID: UniversalAnalytics712371048
09-25 14:24:23.022: W/CordovaPlugin(31566): Result was: "Invalid action"
09-25 14:24:28.032: V/GAV3(31566): Thread[GAThread,5,main]: connecting to Analytics service
09-25 14:24:28.062: V/GAV3(31566): Thread[GAThread,5,main]: connect: bindService returned true for Intent { act=com.google.android.gms.analytics.service.START cmp=com.google.android.gms/.analytics.service.AnalyticsService (has extras) }
09-25 14:24:28.062: V/GAV3(31566): Thread[main,5,main]: service connected, binder: android.os.BinderProxy@41c5e138
09-25 14:24:28.072: V/GAV3(31566): Thread[main,5,main]: bound to service
09-25 14:24:28.072: V/GAV3(31566): Thread[GAThread,5,main]: Loaded clientId
09-25 14:24:28.072: V/GAV3(31566): Thread[main,5,main]: Connected to service
09-25 14:24:28.072: I/GAV3(31566): Thread[GAThread,5,main]: No campaign data found.
09-25 14:24:28.072: V/GAV3(31566): Thread[GAThread,5,main]: putHit called
09-25 14:24:28.072: V/GAV3(31566): Thread[GAThread,5,main]: Sending hit to service   PATH: https:  PARAMS: uid=2,  v=1,  ul=nl-nl,  t=appview,  ht=1411647863039,  sr=1080x1776,  an=WeAlert,  tid=UA-55148678-1,  aid=nl.studionewmedia.wealert,  cid=349fa948-5bb3-4562-824e-3001b02cf401,  av=0.0.1,  _u=.KnoKoK-AL,  cd=We Alert Map,  
09-25 14:25:01.652: V/GAV3(31566): Thread[GAThread,5,main]: putHit called
09-25 14:25:01.652: V/GAV3(31566): Thread[GAThread,5,main]: Sending hit to service   PATH: https:  PARAMS: uid=2,  v=1,  ul=nl-nl,  t=appview,  ht=1411647901665,  sr=1080x1776,  an=WeAlert,  tid=UA-55148678-1,  aid=nl.studionewmedia.wealert,  cid=349fa948-5bb3-4562-824e-3001b02cf401,  av=0.0.1,  _u=.r3oK-AL,  cd=Volgend,  

It's also wrapped in the

ngCordova extensions of the plugin.

When the method is running I would like to throw an exception (while testing). I could do few things:

  1. stub(mock.someMethod("some arg")).toThrow(new RuntimeException());
  2. when(mock.someMethod("some arg")).thenThrow(new RuntimeException())
  3. doThrow.....

Usually I create a spy object to call spied method. Using stubbing I can throw an exception. This exception is always monitored in log. More importantly is that the test does not crash because the method where the exception was thrown could catch it and return specific value. However, in the code bellow exception is not thrown (nothing is monitored in the log && return value is true but should be false).

Issues: In this case the exception is not thrown:

    DeviceInfoHolder deviceInfoHolder = new DeviceInfoHolder();

    /*Create Dummy*/

    DeviceInfoHolder mockDeviceInfoHolder = mock (DeviceInfoHolder.class);

    DeviceInfoHolderPopulator deviceInfoHolderPopulator  = new DeviceInfoHolderPopulator(); 

    /*Set Dummy */
    deviceInfoHolderPopulator.setDeviceInfoHolder(mockDeviceInfoHolder);

    /*Create spy */
    DeviceInfoHolderPopulator spyDeviceInfoHolderPopulator = spy(deviceInfoHolderPopulator);

    /*Just exception*/
    IllegalArgumentException toThrow = new IllegalArgumentException();

    /*Stubbing here*/
    stub(spyDeviceInfoHolderPopulator.populateDeviceInfoHolder()).toThrow(toThrow);

    /*!!!!!!Should be thrown an exception but it is not!!!!!!*/
    boolean returned = spyDeviceInfoHolderPopulator.populateDeviceInfoHolder();
    Log.v(tag,"Returned : "+returned);

When you open application in android, first page come's up is Loading.. (Plane text with white color) Now, (Loading..) it has to fill up with red color one by one(as in games you might have seen), and finally main page(Home page) will be opened.

So, what i need is how to change color of (Loading..) plane white text to red.

Others have asked this question but none of the solutions work for me. Whenever I try to debug my app on any of my devices I keep getting this error:

....
Installing c.yx.dtmts
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/c.yx.dtmts"
pkg: /data/local/tmp/c.yx.dtmts
Failure [INSTALL_FAILED_UID_CHANGED]

I know that it is because there is a package on the device with the same name. I rooted one device and deleted the /data/data/{packagename} file. That didn't work. I did a whole factory reset on another device and it still gives me the error. I have a feeling it is something with Android Studio because this happens on every device regardless if the app was installed or not beforehand.

I have a table layout with n number of rows and columns. I have added a buttons as table cells with some background resources. I just want to expand the table cell on click(placing two fingers and expanding particular cell). Just similar to images in the gallery of smartphone. is that possible?

I'm trying to create a database using sqllite

           try {
                _conn = new SQLiteConnection(_dbPath); 
                _conn.CreateTable<Product>();                    
            }
            catch (Exception ex) {
                throw ex;
            }

it is supposed to create database at _dbPath if it doesn't exist.

_dbPath value is /storage/emulated/0/Phone Catalog/PhoneCatalogDatabase.db3 which is the default location when opening File Manager in Emulator(http://i.imgur.com/fYOT46x.png)

I get exception saying: Could not open database file: /storage/emulated/0/Phone Catalog/PhoneCatalogDatabase.db3 (CannotOpen)

any ideas why I get the message? maybe there is a permission issue or something.

P.S. here is Products class if you need to see it

[Table("Products")]
public class Product {
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Manufacturer { get; set; }
    public int Price { get; set; }
}

Am displaying barchart for my reports using AChartEngine library. I have spinner in that user can able to choose filters. So I cleared dataset and renderer inside the OnItemSelectedListener and then I recreate BarChart using filter new values, when i run this application 1st time barchart is draw/created successfully then when i click filter from spinner the barchart is disabled. Whats wrong with my code ? This same functionality working for PieChart.

This is my onCreate code

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.bar_active_warming);

    database=this.openOrCreateDatabase("DATABASE_NAME", MODE_PRIVATE, null);

    spinner();  

    qry1="SELECT * FROM TableName where Filter='Yes'";
    qry2="SELECT * FROM TableName where Filter='No'";

    createbarchart(); // here we creating bar chart

    onitemselect(); // spinner item select
}

Now createbarchart code

@SuppressWarnings("deprecation")
private void createbarchart() 
{
    getmfcount(); // using query we get values from SQLite this part is working fine

    yesc = new int[] { yescount };
    noc = new int[] { nocount };

    seriesy = new CategorySeries("Yes");
    for(int i=0; i < yesc.length; i++){
        seriesy.add("Bar"+(i+1),yesc[i]);
    }

    seriesn = new CategorySeries("No");
    for(int i=0; i < noc.length; i++){
        seriesn.add("Bar"+(i+1),noc[i]);
    }

    dataSet = new XYMultipleSeriesDataset();  
    dataSet.addSeries(seriesy.toXYSeries());                           
    dataSet.addSeries(seriesn.toXYSeries());   

    //customization of the chart

    renderery = new XYSeriesRenderer();     
    renderery.setColor(Color.BLUE);
    renderery.setDisplayChartValues(true);
    renderery.setLineWidth(20);

    renderern = new XYSeriesRenderer();     
    renderern.setColor(Color.GREEN);
    renderern.setDisplayChartValues(true);
    renderern.setLineWidth(30);

    mRenderer = new XYMultipleSeriesRenderer();   
    mRenderer.addSeriesRenderer(renderery);
    mRenderer.addSeriesRenderer(renderern);

    mRenderer.setChartTitle("Active Warming");
    mRenderer.setYTitle("No of Reports");
    mRenderer.setZoomButtonsVisible(true);    
    mRenderer.setShowLegend(true);
    mRenderer.setShowGridX(true);   // this will show the grid in  graph
    mRenderer.setBarSpacing(.5);   // adding spacing between the line or stacks
    mRenderer.setApplyBackgroundColor(false);
    mRenderer.setMarginsColor(Color.rgb(229,250,251));
    mRenderer.setLabelsColor(Color.BLACK);
    mRenderer.setAxesColor(Color.BLACK);
    mRenderer.setXAxisMin(0);
    mRenderer.setYAxisMin(0); 
    mRenderer.setXAxisMax(2);   
    mRenderer.setXLabels(0);
    mRenderer.setBarWidth(18);
    mRenderer.setPanEnabled(true, true);    // will fix the chart position

    layout=(LinearLayout)findViewById(R.id.barchartaw);
    mChartView=ChartFactory.getBarChartView(getApplicationContext(), dataSet, mRenderer, org.achartengine.chart.BarChart.Type.DEFAULT);
    layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));   
}

this is my onitemselect code

private void onitemselect() {

    Spinner s=(Spinner)findViewById(R.id.spinnerbaw);
    s.setOnItemSelectedListener(new OnItemSelectedListener() {

        @SuppressLint("SimpleDateFormat")
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            String selectedItem = parent.getItemAtPosition(position).toString();
            if(selectedItem.equals("Last Week"))
            {
                // do your stuff
                Toast.makeText(getApplicationContext(), "last Week is Selected", Toast.LENGTH_SHORT).show();

                yescount = 0; nocount = 0;  // clear value frm temp and add new one
                dataSet.clear(); // clear dataset 
                mRenderer.removeAllRenderers();  // clear all renders and create new

                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_MONTH, -7); // sub 7 days
                Date date = cal.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String pastweek = sdf.format(date);
                Log.d("past date (-7) ", pastweek);

                Calendar cal1 = Calendar.getInstance();
                Date date1 = cal1.getTime();
                String currentdate = sdf.format(date1);
                Log.d("current date", currentdate);

                qry1="SELECT * FROM TableName where filter='Yes' AND Date >= '"+ pastweek +"' AND Date <= '"+currentdate+"'";
                qry2="SELECT * FROM TableName where filter='No' AND Date >= '"+ pastweek +"' AND Date <= '"+currentdate+"'";

                createbarchart();
            }
            else if(selectedItem.equals("Last Month"))
            {
                 // other query to filter another values
                 createbarchart();
            }       
}

This is my complete code even values also come exactly what i expected using different queries but the thing is new barchart is disables when we click from spinner.

Can any one able to help me ? Thanks in advance.

This is how I have organized my data:

  • I've created an Application class in my Android project
  • In the Application Class I have an ArrayList Of Objects
  • In the other Activities I call some methods of Application Class that return to me a portion of the aforementioned list

Now the scenario that puzzles me: In a certain Activity If a button is pressed

  1. I check if there is an internet connection
  2. If there isn't one I start an Intent to open Settings for the user to enable mobile networks or WiFi

when It returns though it seem that the application is destroyed because onCreate is called again but at that time the arrayList in my Application class is this time null. So my questions are

  • why is my activity destroyed and not just paused ?
  • If it is destroyed why my app won't start itself from the beginning but it starts only from the Activity that started Activity Action.Settings?
  • If only the latest Activity is Destroyed and not the whole app, how come the data in Application are lost?

this Is how I've declared the ArrayList of objects in my Application class

        private static ArrayList<PointOfInterest> pois;

In my application, I keep yes and no button in listview as an item. setOnClickListener is defined in Adapter class. I have a problem with this. After I scroll the listview, I see the changed button in another row. How can I resolve my issue ?

public class QuizAdapter extends BaseAdapter {

    private static final String FONTH_PATH_1 = "fonts/Brandon_reg.otf";
    private static final String FONTH_PATH_2 = "fonts/Brandon_bld.otf";

    private ArrayList<Question> questionList = new ArrayList<Question>();
    private LayoutInflater inflater;

    private Context context;

    public QuizAdapter(Context context) {
        super();
        this.inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.context = context;
    }

    public void addListItem(final Question item) {
        questionList.add(item);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return questionList.size();
    }

    @Override
    public Question getItem(int position) {
        // TODO Auto-generated method stub
        return questionList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;


        Question currentQuestion = getItem(position);

        Typeface font1 = Typeface.createFromAsset(context.getAssets(),
                FONTH_PATH_1);
        Typeface font2 = Typeface.createFromAsset(context.getAssets(),
                FONTH_PATH_2);

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

            holder.questionCounterTextView = (TextView) convertView
                    .findViewById(R.id.questionCounterTextView);
            holder.questionCounterTextView.setTypeface(font2);

            holder.questionTextView = (TextView) convertView
                    .findViewById(R.id.questionTextView);
            holder.questionTextView.setTypeface(font1);

            holder.yesButton = (Button) convertView
                    .findViewById(R.id.yesButton);
            holder.yesButton.setTypeface(font2);

            holder.noButton = (Button) convertView.findViewById(R.id.noButton);
            holder.noButton.setTypeface(font2);

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


        }

        holder.yesButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                holder.yesButton.setBackgroundColor(R.color.Gray);
            }
        });

        holder.questionCounterTextView.setText(Integer.toString(position + 1));

        holder.questionTextView.setText(currentQuestion.getQuestionMessage());

        return convertView;
    }

    public static class ViewHolder {
        public TextView questionCounterTextView, questionTextView;
        public Button yesButton, noButton;
    }

}

xml file

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/White"
    android:orientation="vertical"
    tools:context="...." >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp" >

        <ImageView
            android:id="@+id/flagImageView"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_alignParentLeft="true"
            android:src="@drawable/flag" />

        <TextView
            android:id="@+id/questionCounterTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/flagImageView"
            android:layout_alignLeft="@+id/flagImageView"
            android:layout_alignRight="@+id/flagImageView"
            android:layout_alignTop="@+id/flagImageView"
            android:layout_marginLeft="10dp"
            android:text="1"
            android:gravity="center|left"
            android:textColor="@color/White" 
            android:textSize="@dimen/question_counter_text_size"/>

        <TextView
            android:id="@+id/questionTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@+id/flagImageView"
            android:text="@string/loremIpsum2"
            android:textColor="@color/Blue"
            android:textSize="@dimen/text_size" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/quizLinearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:orientation="horizontal"
        android:weightSum="640" >

        <Space
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="30" />

        <Button
            android:id="@+id/yesButton"
            style="@style/button_type"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="275"
            android:background="@color/QuizGreen"
            android:text="@string/yes"
            android:textColor="@color/White"
            android:textSize="@dimen/question_button_text_size" />

        <Space
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="30" />

        <Button
            android:id="@+id/noButton"
            style="@style/button_type"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="275"
            android:background="@color/QuizOrange"
            android:text="@string/no"
            android:textColor="@color/White"
            android:textSize="@dimen/question_button_text_size" />

        <Space
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="30" />
    </LinearLayout>

</LinearLayout>

Getting Image Over Using Web Service and Ksoap2

I'm using a .net web service for upload an image when a person select one pic in a gallery in the smartphone.

To implement this I'm using ksoap2.

In my service I'm sending in a string as the parameter, my code below:

File myFile = new File(imagepath);
Log.d(TAG, "myFile: " + myFile);
Request.addProperty("bytes", myFile);

Unfortunately, my vector show up as being empty and I keep get getting a parsing error in LogCat:

09-25 14:29:58.490: TAG(10919): 
myFile: /storage/emulated/0/DCIM/Camera/20140923_084731.jpg

09-25 14:29:58.530: W/System.err(10919): 
java.lang.RuntimeException: Cannot serialize: /storage/emulated/0/DCIM/Camera/20140923_084731.jpg

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.serialization.SoapSerializationEnvelope.writeElement(SoapSerializationEnvelope.java:708)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.serialization.SoapSerializationEnvelope.writeProperty(SoapSerializationEnvelope.java:692)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.serialization.SoapSerializationEnvelope.writeObjectBody(SoapSerializationEnvelope.java:661)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.serialization.SoapSerializationEnvelope.writeObjectBody(SoapSerializationEnvelope.java:645)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.serialization.SoapSerializationEnvelope.writeElement(SoapSerializationEnvelope.java:702)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.serialization.SoapSerializationEnvelope.writeBody(SoapSerializationEnvelope.java:618)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.SoapEnvelope.write(SoapEnvelope.java:198)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.transport.Transport.createRequestData(Transport.java:111)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:119)

09-25 14:29:58.530: W/System.err(10919):         
at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:95)

09-25 14:29:58.530: W/System.err(10919):         
at com.up.upload.MainActivity$2.run(MainActivity.java:237)

09-25 14:29:58.530: W/System.err(10919):         
at java.lang.Thread.run(Thread.java:841)

I was wondering if someone can help me with an issue, what do you suggest?

Thanks in advance.

I am working on a AlertDialog which should display a list of size 2 with image and text. But i am unable to get it working.

I followed this link
Icons in a List dialog
When I am putting getActivity() it's not recognizing so on the suggestion from the post i put getApplicationContext();

public MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complaint);
        cameraButton = (ImageView) findViewById(R.id.cmp_camera);
        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                final String[] items = new String[]{"From Gallery", "From Camera"};
                final Integer[] icons = new Integer[]{R.drawable.ic_launcher, R.drawable.ic_drawer};
                ListAdapter adapter = new CameraPickAdapter(getApplicationContext(), items, icons);

                new AlertDialog.Builder(getApplicationContext()).setTitle("Select Image")
                        .setAdapter(adapter, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int item) {
                                Toast.makeText(getApplicationContext(), "Item Selected: " + item, Toast.LENGTH_SHORT).show();
                            }
                        }).show();
            }
        });
    }
}

the code below is the Adapter class

CameraPickAdapter

public class CameraPickAdapter extends ArrayAdapter<String> {

    private List<Integer> images;

    public CameraPickAdapter(Context context, List<String> items, List<Integer> images) {
        super(context, android.R.layout.select_dialog_item, items);
        this.images = images;
    }

    public CameraPickAdapter(Context context, String[] items, Integer[] images) {
        super(context, android.R.layout.select_dialog_item, items);
        this.images = Arrays.asList(images);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = (TextView) view.findViewById(android.R.id.text1);
        textView.setCompoundDrawablesWithIntrinsicBounds(images.get(position), 0, 0, 0);
        textView.setCompoundDrawablePadding(
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getContext().getResources().getDisplayMetrics()));
        return view;
    }
}

I dont know why I am not getting. I thought this would be simple but i am finding it a hard nut to crack

I am a newbie want help me in uploading a video from my android phone. I have already done a lot of search on google but it was not fruitful. I want to upload to a .net web service which will be based on a soap service. Any input in this regard will be helpful. most of the people are saying to use multipart but this is my limitation that I have to use soap. Video length could be short like half a minute one.

I am giving below the code what I have tried till now.

public class MainActivity extends Activity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

private Uri fileUri; // file url to store image/video

private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    videoPreview = (VideoView) findViewById(R.id.videoPreview);
    btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
    btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);

    /*
     * Capture image button click event
     */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            captureImage();
        }
    });

    /*
     * Record video button click event
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            recordVideo();
        }
    });

    // Checking camera availability
    if (!isDeviceSupportCamera()) {
        Toast.makeText(getApplicationContext(),
                "Sorry! Your device doesn't support camera",
                Toast.LENGTH_LONG).show();
        // will close the app if the device does't have camera
        finish();
    }
}

/**
 * Checking device has camera hardware or not
 * */
private boolean isDeviceSupportCamera() {
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

/*
 * Capturing Camera Image will lauch camera app requrest image capture
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

/*
 * Here we store the file url as it will be null after returning from camera
 * app
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on scren orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}

/*
 * Recording video
 */
private void recordVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

    // set video quality
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
                                                        // name

    // start the video capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}

/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // successfully captured the image
            // display it in image view
            previewCapturedImage();
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // video successfully recorded
            // preview the recorded video
            previewVideo();

        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled recording
            Toast.makeText(getApplicationContext(),
                    "User cancelled video recording", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to record video
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

/*
 * Display image from a path to ImageView
 */
private void previewCapturedImage() {
    try {
        // hide video preview
        videoPreview.setVisibility(View.GONE);

        imgPreview.setVisibility(View.VISIBLE);

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        imgPreview.setImageBitmap(bitmap);
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

/*
 * Previewing recorded video
 */
private void previewVideo() {
    try {
        // hide image preview
        imgPreview.setVisibility(View.GONE);

        videoPreview.setVisibility(View.VISIBLE);
        videoPreview.setVideoPath(fileUri.getPath());

        Log.i("Vid File", fileUri.getPath());

        // start playing
        videoPreview.start();

        UpVidClass upVidClass = new UpVidClass();
        upVidClass.execute(fileUri.getPath());

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

/**
 * ------------ Helper Methods ----------------------
 * */

/*
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/*
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


private class UpVidClass extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        String path = params[0];

        try {
            uploadVideo(path);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }


    @SuppressWarnings("deprecation")
    private void uploadVideo(String videoPath) throws ParseException,
            IOException {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://ccrbest.com/cse/log/");

        FileBody filebodyVideo = new FileBody(new File(videoPath));
        StringBody title = new StringBody("Filename: vid"); // + videoPath);
        StringBody description = new StringBody(
                "This is a description of the video");

        @SuppressWarnings("deprecation")
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("videoFile", filebodyVideo);
        reqEntity.addPart("title", title);
        reqEntity.addPart("description", description);
        httppost.setEntity(reqEntity);

        // DEBUG
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        // DEBUG
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        } // end if

        if (resEntity != null) {
            resEntity.consumeContent();
        } // end if

        httpclient.getConnectionManager().shutdown();

        Toast.makeText(MainActivity.this, "Upload Done", Toast.LENGTH_SHORT).show();

    } // end of uploadVideo( )

    }
}

I'm trying to customize the behavior of my Gradle build to be Android-Wear friendly.

I am bundling manually my wear apk in my handled apk (because i didnt managed to do it automagically).

This means that if I want to build a new version of the handled apk, i have to manually build my wear apk, copy/past the generated wear-apk insinde my res/raw of the handled project then build the new handled apk.

I want all this to be automatized.

So, what I need to do is :

  1. Launch app:assembleRelease from cmd line
  2. Gradle first do a wear:assembleRelease
  3. At the end, Gradle take the apk from wear/output/apk/wear-apk.apk and copy it in app/src/main/res/raw
  4. Then Gradle can procede to do app:assembleRelease

I dont find how to launch a task (wear:assembleRelease) from another task.

Any help is welcome !

I'm having the following issue.

Suppose I have my own image view class (to make it easy I've trimmed all the code and just included only the code that is causing the issue). That class inherits from UIView and overrides drawRect. Here is how my drawRect looks (the code is in Xamarin, but it's easy to understand)

public override void Draw(RectangleF rect)
    {
        base.Draw(rect);
        CGContext context = UIGraphics.GetCurrentContext();
        if (Image != null)
        {
            var imageRect = getAspectFillRect(rect, Image.Size);
            context.DrawImage(imageRect, Image.CGImage);
        }
        else
        {
            this.BackgroundColor.SetFill();
            context.FillRect(this.Bounds);
        }
    }

This code simply draws the image set to Image property in a way which simulates UIImageView's aspect fill option by calculating the rect which will display the image in aspect fill mode using this line of code getAspectFillRect(rect, Image.Size);

I also have UICollectionView with custom layout and custom cells. Each UICollectionViewCell UI is defined in an xib file, there I have all the necessary constraints set and I there I also have my custom view for displaying images. For that view in interface builder I've set content mode to "Aspect Fill". The custom UICollectionViewLayout is made in a way that cell expands (you'll see the example shortly). So the image inside the cell should also scale, and as I've set "Aspect Fill" option, it shouldn't call drawRect of my custom view, rather it should just scale already drawn content. But that is not the case!

LOOK HERE to see the video which demonstrates what happens. You may see that the image inside is not growing together with the cell. The problem is that before ever the cell expanding animation begins drawRect of my custom UIView is called with the rect which will eventually be established after the animation. So I get a jerky animation. In my custom layout code I just call LayoutIfNeeded after updating the constraints of the cell. I don't call setNeedsDisplay, so I don't get why my drawRect is called.

For experiment I replaced my custom image view with UIImageView, I set it's content mode to "Aspect Fill", and LOOK HERE what happened. YEAH! It worked. So I suppose the issue is not in the custom UICollectionView layout, rather in my custom image drawing class.

What I should take into account?? How I should handle this case? Any Ideas? Thanks!