I am trying to get audio input through the headphone jack for my final year project. It would be a great help if someone can share some code on how to capture the data. I have been trying but as I am fairly new to android, I couldn't find any API for headphone jack in MediaRecorder.AudioSource... There are only these sources available: http://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html

Why everyone write variable starts with m? Adapter mApapter? But Android studio suggest Adapter adapter .
what is the good coding practice?which one is very clear to read.
what is use the universal name convention? I saw something like that on php.Adapter pAdapter.

I am developing a music player app in android in which i show albums in grid view.lately i came across this app where album art is shown as animation album art animation.

Could anyone help me with this?

I am selected two three element in List view with check box also last element is selected but all other element are deleted but last element remain as it is. I unable to resolved this issue from past 2 days but I am unable to solved this issue,please help me to solved this issue.Please check my getView.

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

    ViewHolder viewHolder = null;
    if (convertView == null) {
        LayoutInflater inflator = context.getLayoutInflater();
        convertView = inflator.inflate(R.layout.logitem1, null);
        viewHolder = new ViewHolder();
        viewHolder.text = (TextView) convertView.findViewById(R.id.id_skills);
        viewHolder.datetime = (TextView) convertView.findViewById(R.id.id_datetime);
        viewHolder.weather = (TextView) convertView.findViewById(R.id.id_weather);
        viewHolder.duration=(TextView)  convertView.findViewById(R.id.totminutes);
        viewHolder.supervisor=(TextView)  convertView.findViewById(R.id.conditions);
        viewHolder.day_night_icon=(TextView)  convertView.findViewById(R.id.day_night_icon);
        viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.id_chkDelete);
        viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.

                if(SelectedBox.size()-1==0)
                {
                    menu.setVisible(false);
                    addlog.setVisible(true);
                }else
                {
                    addlog.setVisible(false);
                }


                if(isChecked)
                {
                    SelectedBox.add(position);
                    menu.setVisible(true);
                    addlog.setVisible(false);


                }else /*if(!isChecked)*/
                {
                SelectedBox.remove(SelectedBox.indexOf(position));

                }
            }
        });





        convertView.setTag(viewHolder);
        convertView.setTag(R.id.id_skills, viewHolder.text);
        convertView.setTag(R.id.id_chkDelete, viewHolder.checkbox);
        convertView.setTag(R.id.id_datetime,viewHolder.datetime);
        convertView.setTag(R.id.id_weather,viewHolder.weather);
        convertView.setTag(R.id.totminutes,viewHolder.duration);
        convertView.setTag(R.id.conditions,viewHolder.supervisor);
        convertView.setTag(R.id.day_night_icon,viewHolder.day_night_icon);



        } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    viewHolder.checkbox.setTag(position); // This line is important.

    viewHolder.text.setText(list.get(position).getName());
    viewHolder.datetime.setText(list.get(position).getDatetime());
    viewHolder.weather.setText(list.get(position).getWeather());
    viewHolder.checkbox.setChecked(list.get(position).isSelected());
    if(!list.get(position).getDay_minutes().toString().equalsIgnoreCase("0"))
    {
        viewHolder.duration.setText(list.get(position).getDay_minutes());
        viewHolder.day_night_icon.setBackgroundResource(R.drawable.sun);
    }else
    {
        viewHolder.duration.setText(list.get(position).getNight_minutes());
        viewHolder.day_night_icon.setBackgroundResource(R.drawable.moon);

    }
    if(list.get(position).getSupervisor().equals("No supervisor"))
    {
        viewHolder.supervisor.setBackgroundResource(R.drawable.pending);
    }else
    {
        viewHolder.supervisor.setBackgroundResource(R.drawable.approve);
    }
    String fontPath = "fonts/Roboto-Light.ttf";
    Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
    viewHolder.datetime.setTypeface(tf);
    viewHolder.duration.setTypeface(tf);
    viewHolder.text.setTypeface(tf);
    viewHolder.weather.setTypeface(tf);


    menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // TODO Auto-generated method stub

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

            // set title
            alertDialogBuilder.setTitle("Student Driving Practice Log");

            // set dialog message
            alertDialogBuilder
            .setMessage("Are you sure want to Delete Record!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {

                    try
                    {
                        NewNewDataHelper db=new NewNewDataHelper(context);

                        if(!SelectedBox.isEmpty())
                        {
                            for(int i=0;i<SelectedBox.size();i++)
                            {

                            //  resultp=data.get(SelectedBox.get(i));
                                String str[]=list.get(i).getDatetime().split("  ");

                                Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+list.get(i).getName());


                                db.DeleteSingleLog(list.get(i).getName(),str[0],str[1]);

                                /*resultp=data.get(SelectedBox.get(i));

                                String str[]=resultp.get("date_time").split(" ");
                                db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);*/

                                    Toast.makeText(context,"Record Deleted", Toast.LENGTH_LONG).show();


                            }

                            Log.d("LISTSTSTSTST", SelectedBox.toString());


                            Intent intent = new Intent(context,ManagePracticeLogActivity.class);
                            intent.putExtra("s11", "delete");
                            context.startActivity(intent);
                        }
                    }catch(Exception e)
                    {

                    }


                }
            })
            .setNegativeButton("No",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();

                }
            });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();



            return false;
        }
    });
    convertView.setOnClickListener(new OnClickListener() {

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




            String str1 = null;
            String str[]=list.get(position).getDatetime().split("  ");


            Log.d("PARTICULAR SKILLLLL",str[1]);
            str1=str[0]+"~"+list.get(position).getName()+"~"+str[1];
            Log.d("PARTICULAR SKILLLLL", str1);
                Intent intent = new Intent(context,LogEdit.class);
                intent.putExtra("s11","Update Practice");
                intent.putExtra("dataupdate",str1);
                context.startActivity(intent);
        }
    });

    return convertView;
}

I am new at Android programming and I have found online some tutorials and codes I am currently trying to run on my device. One of them happen to be the following code:

-> activity_main.xml

<RelativeLayout 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"
    tools:context=".MainActivity" >
    <fragment
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="com.google.android.gms.maps.SupportMapFragment" />

    </RelativeLayout>

-> DirectionsJSONParser.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;

public class DirectionsJSONParser {

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject){

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = "";
                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                routes.add(path);
            }
        }

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

    return routes;
    }
    /**
    * Method to decode polyline points
    * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
    * */
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

-> MainActivity.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity {

    GoogleMap map;
    ArrayList<LatLng> markerPoints;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initializing
        markerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        map = fm.getMap();

        if(map!=null){

            // Enable MyLocation Button in the Map
            map.setMyLocationEnabled(true);

            // Setting onclick event listener for the map
            map.setOnMapClickListener(new OnMapClickListener() {

                @Override
                public void onMapClick(LatLng point) {

                    // Already two locations
                    if(markerPoints.size()>1){
                        markerPoints.clear();
                        map.clear();
                    }

                    // Adding new item to the ArrayList
                    markerPoints.add(point);

                    // Creating MarkerOptions
                    MarkerOptions options = new MarkerOptions();

                    // Setting the position of the marker
                    options.position(point);

                    /**
                    * For the start location, the color of marker is GREEN and
                    * for the end location, the color of marker is RED.
                    */
                    if(markerPoints.size()==1){
                        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                    }else if(markerPoints.size()==2){
                        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    }

                    // Add new marker to the Google Map Android API V2
                    map.addMarker(options);

                    // Checks, whether start and end locations are captured
                    if(markerPoints.size() >= 2){
                        LatLng origin = markerPoints.get(0);
                        LatLng dest = markerPoints.get(1);

                        // Getting URL to the Google Directions API
                        String url = getDirectionsUrl(origin, dest);

                        DownloadTask downloadTask = new DownloadTask();

                        // Start downloading json data from Google Directions API
                        downloadTask.execute(url);
                    }
                }
            });
        }
    }

    private String getDirectionsUrl(LatLng origin,LatLng dest){

        // Origin of route
        String str_origin = "origin="+origin.latitude+","+origin.longitude;

        // Destination of route
        String str_dest = "destination="+dest.latitude+","+dest.longitude;

        // Sensor enabled
        String sensor = "sensor=false";

        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

        return url;
    }
    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while( ( line = br.readLine()) != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, String>{

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            String data = "";

            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask();

            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

        // Parsing the data in non-ui thread
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try{
                jObject = new JSONObject(jsonData[0]);
                DirectionsJSONParser parser = new DirectionsJSONParser();

                // Starts parsing data
                routes = parser.parse(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }

        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            // Traversing through all the routes
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(2);
                lineOptions.color(Color.RED);
            }

            // Drawing polyline in the Google Map for the i-th route
            map.addPolyline(lineOptions);
        }
    }

    @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;
    }`enter code here`
}

-> AndroidManifest.xml

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <permission
        android:name="com.example.mapnavi.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.mapnavi.permission.MAPS_RECEIVE" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mapnavi.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="MY_API_KEY"/>

    </application>
</manifest>

this code is supposed to be running on Android 2.3.6 or later but despite my efforts, I cannot get it to run on my phone, running Android 4.3 (since my computer is slow and takes ages to open the emulator). There are no errors, the app is successfully installed and just crashes upon trying to be opened.

Could anyone tell me what is wrong or what i am doing wrong? Thank you in advance for your time.

Please am trying to implement a filter on my listview. But whenever the text change, the list disappears.Please Help Here are my codes. The adapter class.

package com.talagbe.schymn;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class HymnsAdapter extends ArrayAdapter<Hymns> {
ArrayList<Hymns> hymnarray;
Context context;
LayoutInflater inflater;
int Resource;


public HymnsAdapter(Context context, int resource, ArrayList<Hymns> objects) {
    super(context, resource, objects);
    // TODO Auto-generated constructor stub

    hymnarray=objects;
    Resource= resource;
    this.context=context;
    inflater= (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
     ViewHolder holder;
     if(convertView==null){

         convertView= inflater.inflate(Resource,null);
         holder= new ViewHolder();
         holder.hymntitle= (TextView) convertView.findViewById(R.id.Hymn_title);
        // holder.hymntext= (TextView) convertView.findViewById(R.id.Channel_name);


         convertView.setTag(holder);

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

     holder.hymntitle.setText(hymnarray.get(position).getTitle());
     //holder.hymntext.setText(hymnarray.get(position).getText());

    return convertView;


}


   static class ViewHolder{

    public TextView hymntitle;
    public TextView hymntext;

}

 }

Here is the other class where am trying to implement the filter. I have an edittext,where i implement on textChangeListener

package com.talagbe.schymn;

import java.util.ArrayList;

import database.DatabaseHelper;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView.OnItemClickListener;

 public class Home extends Fragment {

    private static final String DB_NAME = "schymn.sqlite";
    private static final String TABLE_NAME = "Hymns";
    private static final String Hymn_ID = "_id";
    private static final String Hymn_Title = "Title";
    private static final String Hymn_Text = "Text";
    private SQLiteDatabase database;

ListView list;
EditText search;
HymnsAdapter vadapter;
ArrayList<Hymns> HymnsList;
String url;
Context context=null;


public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
      return inflater.inflate(R.layout.index, container,false);
}


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    list = (ListView)getActivity().findViewById(R.id.hymn_list);
    search = (EditText) getActivity().findViewById(R.id.search);
    HymnsList = new ArrayList<Hymns>();

    DatabaseHelper dbOpenHelper = new DatabaseHelper(getActivity(), DB_NAME);
    database = dbOpenHelper.openDataBase();

    fillHymns();
    //setUpList();

}



private void fillHymns() {
    Cursor hymnCursor = database.query(TABLE_NAME,
                                         new String[] 
                                         {Hymn_ID, Hymn_Title,Hymn_Text},
                                         null, null, null, null
                                         , Hymn_Title);
    hymnCursor.moveToFirst();
    if(!hymnCursor.isAfterLast()) {
        do {
            Hymns hy = new Hymns();
            hy.setTitle(hymnCursor.getString(1));
            hy.setText(hymnCursor.getString(2));
            HymnsList.add(hy);

        } while (hymnCursor.moveToNext());
    }
    hymnCursor.close();
     vadapter = new HymnsAdapter(getActivity().getApplicationContext(),R.layout.hymns,HymnsList);
    list.setAdapter(vadapter);

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

            Intent intent = new Intent(getActivity().getApplicationContext(), Hymn_Text.class);
            intent.putExtra("Title",HymnsList.get(position).getTitle());
            intent.putExtra("Text",HymnsList.get(position).getText());
            startActivity(intent);
            //Log.i("Text",HymnsList.get(position).getText());

        }








    });


    search.addTextChangedListener( new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int start, int before, int count) {
            // TODO Auto-generated method stub
            if(count>0){


            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
             Home.this.vadapter.getFilter().filter(s);
                Log.i("Changed",s.toString());
        }
    });
}




  }

The log,logs whatever input i type in,but doesn't show the listview. Thank you

I am using asmack in my android application inside the service.

Here is my code which is inside onCreate():

    smackInit = SmackAndroid.init(this);
    XMPPConnection.DEBUG_ENABLED = true;
    try{AndroidConnectionConfiguration config = new AndroidConnectionConfiguration("domain.com", 5222);
    //config.setSendPresence(true);
    config.setSASLAuthenticationEnabled(true);
    config.setReconnectionAllowed(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        config.setTruststoreType("AndroidCAStore");
        config.setTruststorePassword(null);
        config.setTruststorePath(null);
    } else {
        config.setTruststoreType("BKS");
        String path = System.getProperty("javax.net.ssl.trustStore");
        if (path == null)
            path = System.getProperty("java.home") + File.separator + "etc"
                + File.separator + "security" + File.separator
                + "cacerts.bks";
        config.setTruststorePath(path);
    }
    ProviderManager.getInstance().addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
    ProviderManager.getInstance().addExtensionProvider(DeliveryReceiptRequest.ELEMENT, new DeliveryReceiptRequest().getNamespace(), new DeliveryReceiptRequest.Provider());
        connection = null;
        connection = new XMPPConnection(config);
        connection.connect();

        connection.addConnectionListener(this);
        connection.login(userName, password);
    catch(Exception e){
        e.printStackTrace();

    }

I am preventing my service from killing so restarting my service if user kills manually

Here is my service code:

@Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      onHandleIntent(intent);
      serviceRunning.running=true;
      onCreate();

      return START_STICKY;
   }

When service starts for first time it works fine. but when it restart it sometimes give Not Connected to server on connection.login(userName, password); line and sometime says already logged in to the server. It happens every time the service restarts.

Thanks for help mates...

In our app OneBusAway Android (open-source on Github), we need to be notified when the user dismisses a particular reminder notification, so we don't post another reminder notification for the same event (how long until their bus arrives).

We're doing this by listening for an Intent in our app, registered as the DeleteIntent with the Notification. When the user dismisses the notification (either by swiping it away, or tapping the clear button in the notification window), our app should receive that Intent.

From testing, it seems that with the current version on Google Play (and the current master branch on Github), the DeleteIntent is never received in our application in the following versions of Android:

  • Android 4.4.3
  • Android 4.4.4

However, the exact same code DOES work (i.e., the Intent registered as the DeleteIntent is received by the app) on:

  • Android 2.3.3
  • Android 2.3.6
  • Android 4.1.2

I've looked at the following SO posts that deal with DeleteIntent, and none of the solutions listed work on Android 4.4.3 and 4.4.4:

The current working master branch uses a Service to listen for the Intent. However, based on some of the above posts, I did tweak some of the code to be more in line with working examples that use a BroadcastReceiver to listen for the Intent.

The code using the BroadcastReceiver is in the following Github branch:

https://github.com/CUTR-at-USF/onebusaway-android/tree/issue104-RepeatingReminders

Below are excerpts for what my current version looks like (that still works on Android 4.1.2 and lower, but not 4.4.3 or 4.4.4), along with links to Github source:


Creating the notification

https://github.com/CUTR-at-USF/onebusaway-android/blob/issue104-RepeatingReminders/onebusaway-android/src/main/java/com/joulespersecond/seattlebusbot/tripservice/NotifierTask.java#L131

private Notification createNotification(Uri alertUri) {
    //Log.d(TAG, "Creating notification for alert: " + alertUri);
    Intent deleteIntent = new Intent(mContext, AlarmReceiver.class);
    deleteIntent.setAction(TripService.ACTION_CANCEL);
    deleteIntent.setData(alertUri);

    return new NotificationCompat.Builder(mContext)
            .setSmallIcon(R.drawable.ic_stat_notification)
            .setDefaults(Notification.DEFAULT_ALL)
            .setOnlyAlertOnce(true)
            .setDeleteIntent(PendingIntent.getBroadcast(mContext, 0,
                    deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT))
            .setAutoCancel(true)
                    //.setLights(0xFF00FF00, 1000, 1000)
                    //.setVibrate(VIBRATE_PATTERN)
            .build();
}

Title and other dynamic notification info are set a few lines later (and reset later, if the notification remains undismissed):

@SuppressWarnings("deprecation")
private void setLatestInfo(Notification notification,
        String stopId,
        String routeId,
        long timeDiff) {
    final String title = mContext.getString(R.string.app_name);

    final PendingIntent intent = PendingIntent.getActivity(mContext, 0,
            new ArrivalsListActivity.Builder(mContext, stopId).getIntent(),
            PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(mContext,
            title,
            getNotifyText(routeId, timeDiff),
            intent);
}

TripService contains the constants for the action:

public static final String ACTION_CANCEL =
        "com.joulespersecond.seattlebusbot.action.CANCEL";

AlarmReceiver

https://github.com/CUTR-at-USF/onebusaway-android/blob/issue104-RepeatingReminders/onebusaway-android/src/main/java/com/joulespersecond/seattlebusbot/AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {

    private static final String TAG = "AlarmReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "In onReceive with intent action " + intent.getAction());
        ...
    }
}

AndroidManifest

https://github.com/CUTR-at-USF/onebusaway-android/blob/issue104-RepeatingReminders/onebusaway-android/src/main/AndroidManifest.xml

<receiver android:name=".AlarmReceiver">
     <!-- These action names must match the constants in TripService -->
      <intent-filter>
         <action android:name="com.joulespersecond.seattlebusbot.action.SCHEDULE" />
         <action android:name="com.joulespersecond.seattlebusbot.action.POLL" />
         <action android:name="com.joulespersecond.seattlebusbot.action.CANCEL" />
     </intent-filter>
 </receiver>

With the above, on Android 4.4.3/4.4.4, the AlarmReceiver never sees the Intent when the user dismisses the notification.

I also tried adding a MIME type, as specified in Custom actions using implicit intents between applications, but that didn't work on Android 4.4.3/4.4.4 either:

Intent deleteIntent = new Intent(mContext, AlarmReceiver.class);
    deleteIntent.setAction(TripService.ACTION_CANCEL);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        deleteIntent.setDataAndTypeAndNormalize(alertUri, TripService.REMINDER_MIME_TYPE);
    } else {
        deleteIntent.setDataAndType(alertUri, TripService.REMINDER_MIME_TYPE);
    }

    return new NotificationCompat.Builder(mContext)
            .setSmallIcon(R.drawable.ic_stat_notification)
            .setDefaults(Notification.DEFAULT_ALL)
            .setOnlyAlertOnce(true)
            .setDeleteIntent(PendingIntent.getBroadcast(mContext, 0,
                    deleteIntent, 0))
                    //.setLights(0xFF00FF00, 1000, 1000)
                    //.setVibrate(VIBRATE_PATTERN)
            .build();

REMINDER_MIME_TYPE is application/vnd.com.joulespersecond.seattlebusbot.reminder

Manifest for using the MIME type:

<receiver android:name=".AlarmReceiver">
        <!-- These action names must match the constants in TripService -->
        <intent-filter>
            <action android:name="com.joulespersecond.seattlebusbot.action.SCHEDULE" />
            <action android:name="com.joulespersecond.seattlebusbot.action.POLL" />
            <action android:name="com.joulespersecond.seattlebusbot.action.CANCEL" />

            <data android:mimeType="application/vnd.com.joulespersecond.seattlebusbot.reminder" />
        </intent-filter>
    </receiver>

I also tried not using the support library (i.e., using Notification.Builder instead of NotificationCompat.Builder), but that didn't change anything either.

I also tried removing the use of Notification.setLatestEventInfo() (by registering a single static title for the reminder using the NotificationCompat.Builder), since this method is deprecated, but again, no change.

Any ideas why this isn't working on Android 4.4.3/4.4.4?

More info is shown in the Github issue for this problem.

good morning, I need a code for me I look for music files in the memory Blast, I'm doing a music player for android, and I can not find that file on the phone, only reads files in the raw folder of eclipse

many thanks and I hope the answer :)

Hey guys I'm working with launcher 3 source code and want to include this code on the home screen:

<include layout="@layout/quicklaunch" 
 android:layout_width="match_parent"
            android:layout_height="match_parent" />

quicklaunch is a slide up menu that has the most common tools users use on it i want to include it in launcher 3's home screen what xml would i add this include to?

Thanks in advance!

I know that there are a few question about this subject, but I read them and I tried the soluttion but it didn't work :(

the PHP script give this json array result: data[x] =

         ["alon","62","1.82","22","0","70","0","1"]

(this is the data[x] variable)

I have to convert this result to Java variabls like name,weight,height etc.. but I don't know how..

please help me

my function:

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





        private final HttpClient Client = new DefaultHttpClient();
        private String Error = null;

        protected void onPreExecute() {


        }

        protected Void doInBackground(String... urls) {
            try {

                  HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                data[x] = Client.execute(httpget, responseHandler);

            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
                cancel(true);
            }

            return null;
        }

        public void onPostExecute(Void unused) {

            String name = null,weight = null;
            if (Error != null) {  
            } else {

                // here I have to do something with the arrays... 

            Toast.makeText(getApplicationContext(),"d:" + data[x] + "o:" + name + " : " + weight, Toast.LENGTH_LONG).show(); 
             }
            x++;
        }

    }

This app I am working on has worked in the past (besides a few errors with parse and some random app crashes) In an attempt to fix my parse problem I updated my parse sdk. After that everything stopped working and I had a Jar mismatch which I search and tried to fix anyway I have a few warnings now that I put code in my app to use (They have been used in the past) all of a sudden it is now telling me that it is not used Please Please Help me.

My Main Activity:

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParseUser;
import com.parse.PushService;
import com.parse.LogInCallback;


public class MainActivity extends ActionBarActivity {

    private String un, pw;
    public TextView username;
    public EditText pass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Parse.initialize(this, "Key",
                "Key");
        PushService.setDefaultPushCallback(this, MainActivity.class);
        PushService.startServiceIfRequired(this);
        ParseInstallation.getCurrentInstallation().saveInBackground();
        PushService.subscribe(this, "push", MainActivity.class);
        setContentView(R.layout.activity_main);

        username = (TextView) findViewById(R.id.editloginusername);
        pass = (EditText) findViewById(R.id.editpass);

        Button login = (Button) findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {

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

                un = username.getText().toString();
                pw = pass.getText().toString();

                ParseUser.logInInBackground(un, pw, new LogInCallback() {
                    public void done(ParseUser user, ParseException e) {
                        if (user != null) {
                            new CallMainPage().execute();

                        } else {
                            // username.setText("");
                            pass.setText("");
                            makeToast("User name or password not recognized.");

                        }

                    }
                });

            }
        });

        Button signup = (Button) findViewById(R.id.signup);
        signup.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new CallSignup().execute();
            }
        });

    }

    @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);
    }

    public class CallSignup extends AsyncTask<Void, Void, String> {
        protected String doInBackground(Void... urls) {
            Intent intent = new Intent(MainActivity.this, Signup.class);
            MainActivity.this.startActivity(intent);
            return "";
        }
    }

    public class CallMainPage extends AsyncTask<Void, Void, String> {
        protected String doInBackground(Void... urls) {
            Intent intent = new Intent(MainActivity.this, MainPage.class);
            MainActivity.this.startActivity(intent);
            return "";
        }
    }

    public void makeToast(String text) {
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(getApplicationContext(), text, duration);
        toast.show();
    }

}

My Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.marsfirst.mars_app"
    android:versionCode="15"
    android:versionName="1.8.4.3" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission android:name="org.marsfirst.mars_app"
        android:protectionLevel="signature" />
    <uses-permission android:name="org.marsfirst.mars_app" />





    <application
        android:name="org.marsfirst.mars_app"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="org.marsfirst.mars_app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.Signup"
            android:label="@string/signup"
            android:parentActivityName="org.marsfirst.mars_app.MainActivity" >
            <intent-filter />

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.marsfirst.mars_app.MainActivity" />
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.MainPage"
            android:label="Main Page" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.Webpage"
            android:label="Website"
            android:parentActivityName="org.marsfirst.mars_app.MainPage" >
            <intent-filter />

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.marsfirst.mars_app.MainPage" />
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.TeamNews"
            android:label="Team News"
            android:parentActivityName="org.marsfirst.mars_app.MainPage" >
            <intent-filter />

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.marsfirst.mars_app.MainPage" />
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.OprPage"
            android:label="OPR Page"
            android:parentActivityName="org.marsfirst.mars_app.MainPage" >
            <intent-filter />

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.marsfirst.mars_app.MainPage" />
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.MechPage"
            android:label="Mechanical Page"
            android:parentActivityName="org.marsfirst.mars_app.MainPage" >
            <intent-filter />

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.marsfirst.mars_app.MainPage" />
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.DriveNews"
            android:label="Drive News"
            android:parentActivityName="org.marsfirst.mars_app.MainPage" >
            <intent-filter />

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.marsfirst.mars_app.MainPage" />
        </activity>
        <activity
            android:name="org.marsfirst.mars_app.ProgramingPage"
            android:label="Programming Page"
            android:parentActivityName="org.marsfirst.mars_app.MainPage" >
            <intent-filter />

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="org.marsfirst.mars_app.MainPage" />
            </activity>
        <activity
            android:name="org.marsfirst.tutorials.pushnotifications.Application"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
            </activity>


               <service android:name="com.parse.PushService" />
        <receiver android:name="com.parse.ParseBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.parse.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="org.marsfirst.mars_app" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

screenshot of my project

http://imgur.com/vTTRY9R

This question already has an answer here:

I guess i'm not declaring it right, it also says that "frontFrag is never used, this is my first time working with fragments.

NullPointer exception at:

at MainAtivity.initFrontFragment(MainActivity.java:87)

at MainActivity.onSectionAttached(MainActivity.java:71)

at MainActivity$PlaceholderFragment.onAttach(MainActivity.java:162)

Code for mainactivity:

package (removed for stack overflow);

import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

private NavigationDrawerFragment mNavigationDrawerFragment;

private CharSequence mTitle;
FrontFragment frontFrag;


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

    FrontFragment frontFrag =new FrontFragment();

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();



    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));



}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
            .commit();
}

public void onSectionAttached(int number) {
    FragmentManager manager=getSupportFragmentManager();
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_section1);

            initFrontFragment(new FrontFragment());

            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            break;
        case 3:
            mTitle = getString(R.string.title_section3);
            break;
    }
}

protected void initFrontFragment(Fragment fragment){

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(android.R.id.content, frontFrag);
    fragmentTransaction.commit();


}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@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);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

}

Code for fragment:

package com.OscarJunker.resturantlocaterexample.pcbuilderhandbook.pcbuilderhandbook;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;





public class FrontFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment FrontFragment.
 */
// TODO: Rename and change types and number of parameters
public static FrontFragment newInstance(String param1, String param2) {
    FrontFragment fragment = new FrontFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
public FrontFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_front, container, false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}

}

I'm trying to use the DrawerLayout with ActionBarDrawerToggle. see my code below:

public class MainActivity extends ActionBarActivity {

private static final String TAG = MainActivity.class.getName();

private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;

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

    FeedsFragment feeds = new FeedsFragment();

    if (findViewById(R.id.main) != null) {

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

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

        mDrawerToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,
                R.drawable.ic_drawer,
                R.string.drawer_open,
                R.string.drawer_close);

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportFragmentManager().beginTransaction().add(R.id.main, feeds).commit();

    } else if (findViewById(R.id.content) != null) {

        NavDrawerFragment nav = new NavDrawerFragment();
        getSupportFragmentManager().beginTransaction()
                .add(R.id.nav, nav)
                .add(R.id.content, feeds)
                .commit();
    }
}

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

@Override
public void onConfigurationChanged(Configuration config) {
    super.onConfigurationChanged(config);
    mDrawerToggle.onConfigurationChanged(config);
}
}

and my view:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<FrameLayout
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!--<include layout="@layout/nav" />-->
<fragment
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:name="com.primeirochute.com.primeirochute.fragment.NavDrawerFragment"
    tools:layout="@layout/nav" />

</android.support.v4.widget.DrawerLayout>

But when I run my project, the left menu (DrawerLayout) just show on my screen doesn't make the slider event.

On some versions of Android, an Activity in my app is not always receiving a shortcut triggered Intent.

The app creates a shortcut with an intent intended for a specific Activity (SomeActivity) in the app

Intent shortcutIntent = new Intent(this, SomeActivity.class);
Intent i = new Intent();

i.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
i.putExtra(Intent.EXTRA_SHORTCUT_NAME, 'shortcut name');
i.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
i.setAction("com.android.launcher.action.INSTALL_SHORTCUT");                                                   sendBroadcast(i);

The shortcut is installed as expected.

For a Nexus 5 (4.4.4) and Samsung S5 (4.4.2) and an old Samsung (2.3.6) everything works as expected, namely SomeActivity's onCreate function is called when the shortcut is clicked.

But for other devices e.g. Sony Xperia (4.3) it works as expected if you have previously exited from the app, but if the app is in the background (having previously tasked away from the app by pressing the Home button) then when the shortcut is pressed neither of SomeActivity's onCreate or onNewIntent are called.

I managed to fix the problem by either setting a flag on the intent:

scIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

or setting the launchMode in the manifest to singleTask.

In both these cases onCreate of SomeActivity is always called irrespective of the state of the app (not running or in background).

But launchModes of standard or singleTop don't work (if the app is in background), the app merely comes to the foreground but SomeActivity's onCreate or onNewIntent are not called. I don't understand why they aren't.

For the record I originally had no launchMode defined (so defaults to standard) and everything behaved correctly. I believe the problem only surfaced when I updated SDK build tools to:

  • Android SDK Tools 23.0.2
  • Android SDK Platform Tools 20
  • Android Build Tools 20

I am currently working on a Mobile Application Development in my corporation, where we have an app to develop to Android and iOS.

It was developed, before this project came up, a tiny framework on C++ that would allow us to reuse code to core functionalities (for a high percentage of future apps), on both Android and iOS (on Android we acess it through JNI and in iOs... well, much simpler.mm).

I just joined the team and for this app we need a small and simple local database, but it's important to built a database handler that will easily support scability and adaptation to easy change and reuse on future projects.

We are going to use sqlite, but there is a question that I indeed need your good knowledge for:

Should I create this database manager on objective-c and then repeat it on Java, which means no respect for DRY (altough that in the future the reuse of this code would be high given the design I would do) but keeps it simpler and better implemented (since my C++ experienced is minimal compared to Java or Obj-c), or does it worth to implement it in C++ and be able to use the same code **on both platforms**?

I am making an android twitter client and am using fragments to show each tweet. When I want to update the timeline I want the new fragments to appear on top in order, but I can't seem to find any way to add them to the top. I am using a TableLayout and adding them like this right now:

         while (newTweets > 0) {
                TweetFragment tweet = new TweetFragment();
                tweet.setStatus(timeline.get(newTweets - 1));

                getSupportFragmentManager().beginTransaction()
                        .add(R.id.fragment_container, tweet).commit();

                newTweets--;
            }

This puts the old tweets at the bottom of the timeline though. Is there any way to do this without creating an entirely new tableLayout?

I have 3 TextView components that represent 3 different bars. I have created a scale animation so the percentage in each bar will grow from bottom of the container to the height of the TextView (each text has different size according to the percentage). The problem is that I created only one ScaleAnimation object but it behave differently if I use different background to that TextView. This is my code of the animation object and the TextView:

ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, (float)1.0, Animation.RELATIVE_TO_SELF, (float)1.0);
scaleAnimation.setFillAfter(true);
scaleAnimation.setDuration(1000);

tvHomeTeamPercentage.startAnimation(scaleAnimation);
tvDrawPercentage.startAnimation(scaleAnimation);
tvAwayTeamPercentage.startAnimation(scaleAnimation);

It is important to mention that the there is no difference between the text views at all except their height and their background (which is 9patch in all cases).

I am working on android game..I have set FPS to 30.It is going fine.there is some speed up object on the road,if sprite takes that, it will increase sprite speed.

I have increase FPS. no effect.I need to show a particular sprite animation first not all.

I read document from QuickBlox about chat feature.i got the idea form the sample code of QuickBlox. In my requirement i need to show list of room in which user is involved, not all room for that application. i read in the document its possible using chat 2.0

QBRoomChatManager roomChatManager = QBChatService.getInstance().getRoomChatManager();
        roomChatManager.createDialog("Chat with Bob, Sam, Garry", QBDialogType.GROUP, occupantIdsList, this);

I tried to use this code to create group but there isn't QBRoomChatManager in the library. How can i use this method to create group?

I would like to know if something like this is possible, and it would be good if somebody gave me a hint how to achieve it. enter image description here

I can think of only one way how to do it, put

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

and add view above activity that looks like an action bar with a icon that goes beyond this pseidoaction bar. But are there some better way how to do it?