samedi 25 avril 2015

Send latitude and Longitude from the BoadcastReceiver when the internet connection is avialable


I want to send JSON String

{
    "latitude": 53.86898504,
    "longitude": 10.66561187,
    "time": "25.04.2015 11:37:11",
    "route": 4
} 

to the server every 60 seconds so when I try to send the JSON string from my internet connection BroadcastReceiver the JSON string is null there but when I send the data from onLocationChanged method I am getting the string in the PostData class but I want to send the data just when the internet connection is avialable if the internet is not avialable i will store the string for short time. How can I implement it to get the JSONString in the CONNECTIVITY_ACTION BroadcastReceiver?

I appreciate any help.

MainActivity class:

public class MainActivity extends ActionBarActivity {

Location location;
LocationManager locationManager;
String jSONString;

    TextView textJSON;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textJSON = (TextView) findViewById(R.id.textJSON);


        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new myLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, ll);


    }

    private class BroadcastReceiverListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                     //code to get the strongest wifi access point in the JSON string the routes's value.
            }

            else if (intent.getAction().equals(
                    android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {

                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo netInfo = connectivityManager
                        .getActiveNetworkInfo();

                boolean isConnected = netInfo != null
                        && netInfo.isConnectedOrConnecting();
                if (isConnected) {
                    Toast.makeText(context,
                            "The device is connected to the internet ",
                            Toast.LENGTH_SHORT).show();
                if (location == null) {

                    Location locat = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (locat == null) {

                        LocationListener locLis = new myLocationListener();
                        LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        Criteria criteria = new Criteria();
                        Looper myLooper = Looper.myLooper();

                        locMan.requestSingleUpdate(criteria, locLis,
                                myLooper);

                    } else {
                        System.out.println("locat is not null");
                    }

                } else {
                    PostData sender = new PostData();
                    sender.timer(jSONString);
                    textJSON.setText(jSONString);
                }


                } else {
                    Toast.makeText(context,
                            "Please connect the device to the internet.",
                            Toast.LENGTH_SHORT).show();
                }

            }
        }

    }

    class myLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {

            if (location != null) {
                double pLong = location.getLongitude();
                double pLat = location.getLatitude();
                ...
                String time = sdf.format(location.getTime());

                jSONString = convertToJSON(pLong, pLat, time);
                System.out.println("The output of onLocationChanged: "+ jSONString);

                //The code works fine here. JSON string has its values here but in broadcastReceiver JSON string has null.
//              PostData sender = new PostData();
//              sender.timer(jSONString);
//              textJSON.setText(jSONString);



            }
        }
    }
}


Android sticky list headers


I want to make sticky list headers like Contact application ! I tried to make to parallel lists but I can not synchronize them.. Any idea how to it please !

Below the example (letter B)

enter image description here

Thanks !!


Copy sqlite db file from Android terminal to Windows OS


I want to copy the sqlite database from data/data/[package name]/databases/ to Windows Operating system.

Currently, I am inside Android Terminal shell of Android studio and my current path is /data/data/example.com.sensor/databases.

There is a sqlite file in this directory. The name is sensor.sqlite.

This is perhaps an easy question for experience user like you. However, I have spent 2 hours yet I find the result.

Thank you.

Regards,

Jimmy


Make Android Activity Dialog On Start


I want to to make an App. When it is started is should show an new Activty which is an dialog and has a transparent background like here: http://ift.tt/1f3ecyb

Do you have any idea, how I can make it with Android?


Responsive CSS works everywhere except the Internet Browser on Droid Phone (Galaxy S4)


I have got my website working everywhere except the default "Internet" browser on the Droid phone. It looks great in Chrome on the phone. It passes all the Google tests for mobile ready. It looks good on iPhone. Here's the site ... http://ift.tt/1DKrWbs.

It's driving me crazy. Does anyone know why?


How to save add button dynamically in android?


The code for add button dynamically when user need it , When user click on “addService” this code take (a name for button and a value to use in intent for this button) from second activity then add button dynamically in this activity with the name and intent and user can click it for service . How to save the button that add dynamically by user ? ..............................................................................

        Button btn = new Button(MainActivity.this);
        btn.setText(buttonName);
        layout.addView(btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = serviceNum;
                Intent e = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null));
                startActivity(e);
            }
        });


Logo is not showing up on action bar


I'm trying to simply put a logo on my ActionBar in android but nothing seems to be working. I have literally tried every solution I could find on this website and others without any luck. Any help would be appreciated,

Jacob

Here is my java:

public class Home extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);





        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setLogo(R.drawable.ic_launcher);


        mNavItems.add(new NavItem("Home", "Find everything you need to know in one place", R.drawable.home_icon));
        mNavItems.add(new NavItem("Learn About Our Programs", "Learn about what we do to help the city", R.drawable.list));
        mNavItems.add(new NavItem("About Us", "Get to know about us on the personal level", R.drawable.info_circled_alt));
        mNavItems.add(new NavItem("Contact Us", "Want to know more about something? Send us an email or phone call", R.drawable.questionm));

        // DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // Populate the Navigtion Drawer with options
        mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
        mDrawerList = (ListView) findViewById(R.id.navList);
        DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
        mDrawerList.setAdapter(adapter);

        // Drawer Item click listeners
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItemFromDrawer(position);
            }
        });
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_opem, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                Log.d(TAG, "onDrawerClosed: " + getTitle());

                invalidateOptionsMenu();
            }


        };


        mDrawerLayout.setDrawerListener(mDrawerToggle);

    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle
        // If it returns true, then it has handled
        // the nav drawer indicator touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }







    private void selectItemFromDrawer(int position) {


        // Close the drawer
        mDrawerLayout.closeDrawer(mDrawerPane);
        Intent intent;
        switch (position) {


            case 0:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Intent i = new Intent(Home.this, Home.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(i);


                        overridePendingTransition(R.animator.animation1, R.animator.animation2);
                    }
                }, 300);
                break;
            case 1:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Intent i = new Intent(Home.this, FindOpp.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(i);


                        overridePendingTransition(R.animator.animation1, R.animator.animation2);;
                    }
                }, 300);



                break;


            case 2:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Intent i = new Intent(Home.this, About_Us.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(i);


                        overridePendingTransition(R.animator.animation1, R.animator.animation2);;
                    }
                }, 300);
                break;

        }
    }


    }

class NavItem {
    String mTitle;
    String mSubtitle;
    int mIcon;

    public NavItem(String title, String subtitle, int icon) {
        mTitle = title;
        mSubtitle = subtitle;
        mIcon = icon;
    }
}
class DrawerListAdapter extends BaseAdapter {

    Context mContext;
    ArrayList<NavItem> mNavItems;

    public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
        mContext = context;
        mNavItems = navItems;
    }

    @Override
    public int getCount() {
        return mNavItems.size();
    }

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

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

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

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.drawer_item, null);
        }
        else {
            view = convertView;
        }

        TextView titleView = (TextView) view.findViewById(R.id.title);
        TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
        ImageView iconView = (ImageView) view.findViewById(R.id.icon);

        titleView.setText( mNavItems.get(position).mTitle );
        subtitleView.setText( mNavItems.get(position).mSubtitle );
        iconView.setImageResource(mNavItems.get(position).mIcon);

        return view;
    }

}
class PreferencesFragment extends Fragment {


    public PreferencesFragment() {
        // Required empty public constructor
    }


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

}


How to clear html page before showing into a webview in Android?


I have the URL of a webpage to be displayed into a webview in my Android app. Before showing this page i want to clear the html code of this page from some tag (such as the header, footer, ecc..) in order to show only few information. How can i do it? I tried to solve the issue working with JSoup but i can't understand how to create and pass the "new page" to the webview. Anybody can help me?


Android colour resource - making a colour an alias of another


Is there a way to do something like the following?

<color name="gray1">#eeeeee</color>
<color name="separator_line_gray">@color/gray1</color>

So that I can use separator_line_gray in my code and quickly change it from gray1 to gray2 if needed


Cordova Plugin: Unable to retrieve path to picture


Searching for a solution to the following problem for a while and can't seem to find any solutions. Any help is welcome.

The camera plugin of cordova returns the following error when trying to access a picture using the camera.

Unable to retrieve path to picture!

I tried FILE_URI and DATA_URL.

I use cordova version 5.0.0 and cordova-plugin-camera.

The following path fails e.g.

/storage/emulated/0/Download/horse-331746_640.jpg 

The following path functions e.g.

/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-2015019-WA0000.JPG 

My Function:

function captureNow(bGallery){

    if(bGallery === true){
        navigator.camera.getPicture(onCapturePhoto, cameraOnFail, {
            quality: 100,
            correctOrientation: 1,
            targetWidth: 500,
            targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.PHOTOLIBRARY
        });
    } else {
        navigator.camera.getPicture(onCapturePhoto, cameraOnFail, {
            quality: 100,
            correctOrientation: 1,
            targetWidth: 500,
            targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            destinationType: Camera.DestinationType.FILE_URI
        });
    }
}


Read large file data using buffered reader in android


hi i want to read large remote file into string using buffered reader.but i got half data of remote file.Please help to get full data of remote file.

BufferedReader reader = new BufferedReader(new InputStreamReader( inputstream),8*1024);

        StringBuilder sb = new StringBuilder(999999);
        String line;

        while ((line = reader.readLine()) != null) {
            Log.e("Line is ",line);
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("Content: ", sb.toString());


Working with the Youtube-Api


I have several Tutorial Videos on Youtube and i want to include them into my Application. So i have a fix set of Youtube-URL's.

I want to show a list of these videos for that i somehow need to get the thumbnail, the title and the description of each Youtube-URL and to show it. When the user clicks on a item of the listview i want the selected youtube video to be played inside my application.

Unfortunately i cant find example which are showing how to achieve these things. playing youtube videos is easy but i dont know how to get the thumbnail, title and descritpion of given youtube url's.


What is wrong in my android app with HttpPost?


I'm making a new android app, when I send a values with HttpPost to my web file post.php, but it is don't working. What is it wrong ?

activity_activity_main.xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".ActivityPrincipal">

</RelativeLayout>

ActivityPrincipal.java

package com.pixelayer.httppost.httppostandroid;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class ActivityPrincipal extends ActionBarActivity {

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

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost("http://ift.tt/1zYSQMa"); //
    replace with
    // your url

    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);

    nameValuePair.add(new BasicNameValuePair("nome", "test_user"));

    nameValuePair.add(new BasicNameValuePair("site", "testeandroid"));

    // Encoding data

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    // making request

    try {
        HttpResponse response = httpClient.execute(httpPost);
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        // Log exception
        e.printStackTrace();
    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_activity_principal, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.pixelayer.httppost.httppostandroid" >

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

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

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

</manifest>

Thank you so much


Would storing many images in an Android apk file be viable for a social app


I am creating a social app for android and am planning ahead, what would be a viable way in Android to store potentially millions of user generated uploaded photos. I have a MySQL database that saves the image path and was thinking of creating a folder outside of the /drawable directory to save the physical images. I could do that but then I thought that if I did then the Android APK file would just balloon in size since your storing all the images within the app; is there a better way to store many images? I been searching around for answers but there aren't many on this topic for android.


Authenticate method is NULL when automatic login


After a user has already logged into the app, I have their username and password saved to shared preferences, therefore when they login again, they should be able to authenticate automatically and subsequently bypass the login activity.

I have started and binded the service, and sent the authenticate methods to the server, yet the section:

                             result = imService.authenticateUser(
                                     userName.trim(),
                                     password.trim());

always returns NULL and does not allow automatic logging in.

Why would this be the case?

The loggingIn class

public class LoggingIn extends Activity {

     protected static final int NOT_CONNECTED_TO_SERVICE = 0;
     protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
     public static final String AUTHENTICATION_FAILED = "0";
     public static final String FRIEND_LIST = "FRIEND_LIST";
     protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
     protected static final int NOT_CONNECTED_TO_NETWORK = 3;
     private EditText usernameText;
     private EditText passwordText;

     private JSONObject resultObject;
     public static String userId = null;

     private Manager imService;
     public static final int SIGN_UP_ID = Menu.FIRST;
     public static final int EXIT_APP_ID = Menu.FIRST + 1;

     // For GCM
     String regid;
     GoogleCloudMessaging gcm;
     AtomicInteger msgId = new AtomicInteger();
     SharedPreferences prefs;
     Context context;

     public static final String EXTRA_MESSAGE = "message";
     public static final String PROPERTY_REG_ID = "registration_id";
     private static final String PROPERTY_APP_VERSION = "appVersion";
     private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

     private ServiceConnection mConnection = new ServiceConnection() {
         public void onServiceConnected(ComponentName className, IBinder service) {
             // This is called when the connection with the service has been
             // established, giving us the service object we can use to
             // interact with the service. Because we have bound to a explicit
             // service that we know is running in our own process, we can
             // cast its IBinder to a concrete class and directly access it.
             imService = ((MessagingService.IMBinder) service).getService();

             if (imService.isUserAuthenticated() == true) {
                 // Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
                 Intent i = new Intent(LoggingIn.this, MainActivity.class);
                 startActivity(i);
                 LoggingIn.this.finish();
             }
         }

         public void onServiceDisconnected(ComponentName className) {
             // This is called when the connection with the service has been
             // unexpectedly disconnected -- that is, its process crashed.
             // Because it is running in our same process, we should never
             // see this happen.
             imService = null;
             Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
                     Toast.LENGTH_SHORT).show();
         }
     };

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

              /*
               * Start and bind the imService
               */
         startService(new Intent(getBaseContext(), MessagingService.class));

         // Bind it
         bindService(new Intent(getBaseContext(), MessagingService.class),
                 mConnection, Context.BIND_AUTO_CREATE);

         // Initiate Volley:
         final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();

         //Remove title bar
         this.requestWindowFeature(Window.FEATURE_NO_TITLE);

         //Remove notification bar
         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

         // For auto logging in:
         if (!SaveSharedPreference.getUserName(getApplicationContext()).isEmpty()) {

                     setContentView(R.layout.feast_loading_splash_page);

                     final String userName = SaveSharedPreference.getUserName(getApplicationContext());

                     final String password = SaveSharedPreference.getPassword(getApplicationContext());

                    Log.v("TEST GCM Service Login","SharedPref Username is " + userName + " and password " + password);

                     Thread loginThread = new Thread() {
                         private Handler handler = new Handler();

                         @Override
                         public void run() {
                             String result = null;

                             try {

                                 result = imService.authenticateUser(
                                         userName.trim(),
                                         password.trim());

                             } catch (UnsupportedEncodingException e) {

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

                             if (result == null || result.equals(AUTHENTICATION_FAILED)) {
                /*
                * Authenticatin failed, inform the user
                */
                                 handler.post(new Runnable() {
                                     public void run() {
                                         Toast.makeText(
                                                 getApplicationContext(),
                                                 R.string.make_sure_username_and_password_correct,
                                                 Toast.LENGTH_LONG).show();

                                         // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                     }
                                 });

                             } else {

                /*
                * if result not equal to authentication failed, result
                * is equal to friend and group list of the user 0: is
                * for friends, 1: is for groups
                */
                                 handler.post(new Runnable() {
                                     public void run() {
                                         Intent i = new Intent(LoggingIn.this,
                                                 MainActivity.class);
                                         startActivity(i);
                                         LoggingIn.this.finish();

                                     }
                                 });

                             }

                         }
                     };
                     loginThread.start();

                 }


         //setContentView(R.layout.loggin_in);
         setContentView(R.layout.feast_login_page);
         //setTitle("Login");

         ImageButton loginButton = (ImageButton) findViewById(R.id.button1);

             // So don't need to log in manually, just click the button
             usernameText = (EditText) findViewById(R.id.username);
             passwordText = (EditText) findViewById(R.id.password);

             // Used for expeditied login
             //usernameText.setText("kjakah08"); //(EditText) findViewById(R.id.username);
             //passwordText.setText("farside"); // (EditText) findViewById(R.id.password);

             loginButton.setOnClickListener(new OnClickListener() {
                 public void onClick(View arg0) {
                     if (imService == null) {
                         Toast.makeText(getApplicationContext(),
                                 R.string.not_connected_to_service,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(NOT_CONNECTED_TO_SERVICE);
                         return;
                     } else if (imService.isNetworkConnected() == false) {
                         Toast.makeText(getApplicationContext(),
                                 R.string.not_connected_to_network,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(NOT_CONNECTED_TO_NETWORK);

                     } else if (usernameText.length() > 0
                             && passwordText.length() > 0) {

                         Thread loginThread = new Thread() {
                             private Handler handler = new Handler();

                             @Override
                             public void run() {
                                 String result = null;

                                 try {
                                     result = imService.authenticateUser(
                                             usernameText.getText().toString().trim(),
                                             passwordText.getText().toString().trim());
                                 } catch (UnsupportedEncodingException e) {

                                     e.printStackTrace();
                                 }
                                 if (result == null
                                         || result.equals(AUTHENTICATION_FAILED)) {
                                      /*
                                       * Authenticatin failed, inform the user
                                       */
                                     handler.post(new Runnable() {
                                         public void run() {
                                             Toast.makeText(
                                                     getApplicationContext(),
                                                     R.string.make_sure_username_and_password_correct,
                                                     Toast.LENGTH_LONG).show();

                                             // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                         }
                                     });

                                 } else {

                                      /*
                                       * if result not equal to authentication failed,
                                       * result is equal to friend and group list of
                                       * the user 0: is for friends, 1: is for groups
                                       */
                                     handler.post(new Runnable() {
                                         public void run() {

                                             // If log in successful, then save
                                             // username and password to shared
                                             // preferences:

                                             SaveSharedPreference.setUserName(
                                                     getApplicationContext(),
                                                     usernameText.getText()
                                                             .toString());

                                             SaveSharedPreference.setPassword(
                                                     getApplicationContext(),
                                                     passwordText.getText()
                                                             .toString());

                                             Intent i = new Intent(LoggingIn.this,
                                                     MainActivity.class);
                                             startActivity(i);
                                             LoggingIn.this.finish();

                                         }
                                     });

                                 }

                             }
                         };
                         loginThread.start();

                     } else {
                          /*
                           * Username or Password is not filled, alert the user
                           */
                         Toast.makeText(getApplicationContext(),
                                 R.string.fill_both_username_and_password,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
                     }

                     // GET the users id!!
                     JsonObjectRequest getUserId = new JsonObjectRequest(Request.Method.GET,
                             "http://" + Global.getFeastOnline() + "/getUserData/" + usernameText.getText().toString() + ".json", ((String) null),
                             new Response.Listener<JSONObject>() {
                                 @Override
                                 public void onResponse(JSONObject response) {

                                     // Parse the JSON:
                                     try {
                                         resultObject = response.getJSONObject("userInfo");
                                         userId = resultObject.getString("id");

                                         Log.v("USER ID", "The user id is " + userId);

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

                                 }
                             },
                             new Response.ErrorListener() {
                                 @Override
                                 public void onErrorResponse(VolleyError error) {
                                     Log.d("Error.Response", error.toString());
                                 }
                             });

                     requestQueue.add(getUserId);

                 }
             });

     }

     @Override
     protected Dialog onCreateDialog(int id) {
         int message = -1;
         switch (id) {
             case NOT_CONNECTED_TO_SERVICE:
                 message = R.string.not_connected_to_service;
                 break;
             case FILL_BOTH_USERNAME_AND_PASSWORD:
                 message = R.string.fill_both_username_and_password;
                 break;
             case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
                 message = R.string.make_sure_username_and_password_correct;
                 break;
             case NOT_CONNECTED_TO_NETWORK:
                 message = R.string.not_connected_to_network;
                 break;
             default:
                 break;
         }

         if (message == -1) {
             return null;
         } else {
             return new AlertDialog.Builder(LoggingIn.this)
                     .setMessage(message)
                     .setPositiveButton(R.string.OK,
                             new DialogInterface.OnClickListener() {
                                 public void onClick(DialogInterface dialog,
                                                     int whichButton) {
                                                    /* User clicked OK so do some stuff */
                                 }
                             }).create();
         }
     }

     @Override
     protected void onPause() {
         unbindService(mConnection);
         super.onPause();
     }

     @Override
     protected void onResume() {
         bindService(new Intent(LoggingIn.this, MessagingService.class),
                 mConnection, Context.BIND_AUTO_CREATE);

         super.onResume();
     }

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

         menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
         menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);

         return result;
     }

     @Override
     public boolean onMenuItemSelected(int featureId, MenuItem item) {

         switch (item.getItemId()) {
             case SIGN_UP_ID:
                 Intent i = new Intent(LoggingIn.this, SigningUp.class);
                 startActivity(i);
                 return true;
             case EXIT_APP_ID:

                 return true;
         }

         return super.onMenuItemSelected(featureId, item);
     }

 }


android - java string.format()


Coming from C# i'm trying to port what I know over into Android.

I'm basically trying to do a string.Format with 2 variables.

Here is the code. val1 = "HelloWorld" va2 = 11

EditText edt = (EditText)findViewById(R.id.main_studentName);
    String val = edt.getText().toString();

    EditText edt2 = (EditText)findViewById(R.id.main_studentAge);
    String val2 = edt2.getText().toString();

    String sqlSampleString = String.format("insert into Students(StudentName,StudentAge) Values('%1$',%2$)", val,val2);
    myDatabase.execSQL(sqlSampleString);

Here is the error in LogCat

04-25 10:44:47.858    9701-9701/com.example.mycomp.buildingproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.mycomp.buildingproject, PID: 9701
    java.lang.IllegalStateException: Could not execute method of the activity

SupportMapFragment doesn't start on SDK 10


I created an Android application which uses the SupportMapFragment. Now I have to be able to use it on SDK 10 as well. Although this is really an outdated version, I'm obliged to use it...

When starting the activity with the SupportMapFragment, the app crashes with this error message:

java.lang.RuntimeException: Unable to start activity ComponentInfo{lokeren.viae.com.lokeren/com.viae.notification.activity.MapActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class fragment

This is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<permission
    android:name="com.viae.notification.maps.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

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


<uses-permission android:name="com.viae.notification.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<!-- TEST -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

<uses-feature
    android:name="android.hardware.camera"
    android:required="false" />
<!-- android:theme="@style/AppTheme"
        android:theme="@android:style/Theme.AppCompat.Light"
        android:theme="@style/Theme.AppCompat.-->
<application
    android:allowBackup="true"
    android:exported="true"
    android:icon="@drawable/logo"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name="com.viae.notification.activity.MapActivity"
        android:label="Lokeren">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.viae.notification.activity.NotificationActivity"
        android:label="Melding">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.viae.notification.activity.MapActivity" />
    </activity>

    <service
        android:name="com.viae.common.service.impl.LocationService"
        android:label="@string/viae_location_service_name"></service>

    <service
        android:name="com.viae.notification.database.service.impl.NotificationService"
        android:label="@string/viae_notification_service_name"></service>

    <provider
        android:name="com.viae.notification.database.provider.NotificationProvider"
        android:authorities="com.viae.stad.lokeren.Notification"
        android:exported="false" />

    <provider
        android:name="com.viae.notification.database.provider.NotificationImageProvider"
        android:authorities="com.viae.stad.lokeren.NotificationImage"
        android:exported="false" />

    <provider
        android:name="com.viae.notification.database.provider.UrgencyProvider"
        android:authorities="com.viae.stad.lokeren.Urgency"
        android:exported="false" />

    <provider
        android:name="com.viae.notification.database.provider.CategoryProvider"
        android:authorities="com.viae.stad.lokeren.Category"
        android:exported="false" />

    <provider
        android:name="com.viae.notification.database.provider.CountryProvider"
        android:authorities="com.viae.stad.lokeren.Country"
        android:exported="false" />

    <provider
        android:name="com.viae.notification.database.provider.CityProvider"
        android:authorities="com.viae.stad.lokeren.City"
        android:exported="false" />

    <provider
        android:name="com.viae.notification.database.provider.AddressProvider"
        android:authorities="com.viae.stad.lokeren.Address"
        android:exported="false" />

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

And this is my activity configuration:

<android.support.v4.widget.DrawerLayout xmlns:android="http://ift.tt/nIICcg"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <fragment
            android:id="@+id/google_map"
            class="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <fragment
            android:id="@+id/menu"
            class="com.viae.notification.activity.MenuFragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</FrameLayout>
<!-- The navigation drawer -->
<LinearLayout
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:gravity="bottom|center"
    android:orientation="vertical">

    <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://ift.tt/nIICcg"
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/left_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="#ffffff"
            android:choiceMode="singleChoice"
            android:divider="@android:color/darker_gray"
            android:dividerHeight="0dp" />
    </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

Can someone tell me what I'm doing wrong? 'cus as I read in the documentation, this should be available on SDK 10 too...


Using the emulator, how can I find and view CSV files?


I have the IO needed for writing a CSV file, however I want to be able to open it.

So my two problems, locating the file

If I use:

private static void csvFile(String sFileName) {

try
{
    FileWriter writer = new FileWriter(sFileName);

    writer.append("DisplayName");
    writer.append(",");
    writer.append("Age");
    writer.append('\n');
}
catch (IOException e)
{
    e.printStackTrace();
}

Then in my main class

csvFile("SPREADSHEET.csv");

Where would it save on the emulator since I didnt give it a directory? How could I find this file and open it on an emulator to ensure that it was doing things correctly? The emulator doesn't have capability to open such files unless I read it from java.


Cannot rename a folder


I want to rename a folder :

public static boolean renommerDossierPhoto(String table, String ancienPk, String nouveauPk) {

    if (Integer.parseInt(ancienPk) < 0) { 

        String ancienDir = table + File.separator + "n" + ancienPk.substring(1);

        File ancienDossier = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DOSSIER_PPAL_PHOTOS + File.separator + ancienDir);

        String nouveauDir = table + File.separator + nouveauPk;

        File nouveauDossier = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DOSSIER_PPAL_PHOTOS + File.separator + nouveauDir);

        return ancienDossier.renameTo(nouveauDossier);

    }

    return true;

}

The structure of the directories is : internal storage/Pictures/projectName/parcelle/n1/img_20150425_163809.png Here parcelle is the value of the parameter table in the above method. These directories already exist and the folder n1 contains the image img_20150425_163809.png.

So I want to rename the folder n1 to the third parameter , say 5.

At runtime this method returns false ! So what is wrong in my code ?


requestAnimationFrame doesn't work on Chrome Beta for Android when function fired first time


I'm experimenting on this simple structure: HTML:

<video width=340></video>
<canvas></canvas>
<button id=button>Start</button>

JavaScript:

var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame
  , doc = document
  , webcam = doc.querySelector('video')
  , canvas = doc.querySelector('canvas')
  , ctx = canvas.getContext('2d')
  , button = doc.getElementById('button')
  ;

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
var playWebcam = function() {
    navigator.getUserMedia(
        constraints = {
            audio: true,
            video: true
        },
        function(stream) {
            webcam.src = window.URL.createObjectURL(stream);
            webcam.play();
            paintCanvas.source(webcam);
        },
        function(err) {
            console.log(err);
        }
    );
};

var paintCanvas =  {
    source: function(x) {
        this.x = x;
        this.paint(this.x);
    },
    paint: function() {
        var that = this;
        this.paint.prototype = function() { that.draw(this.x); }
        this.paint.prototype(this.x);
    },
    draw: function() {
        ctx.drawImage(this.x, 0, 0, canvas.width, canvas.height);
        requestAnimationFrame(this.paint.prototype);
    }
}

button.addEventListener('click', function() {
    playWebcam();
}, false);

It is working fine on PC, but it does not work on Chrome Beta for Android unless you tab the Start button for the second time.

How to make it make it works instantly without the need of re-tabbing the button.


Image adapter leaking memory?


I have a simple ListActivity that shows images and I inizialize my OkHttpClient for Picasso Builder in the constructor of the image adapter:

picassoClient = new OkHttpClient();
picassoClient.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request newRequest = chain
            .request()
            .newBuilder()
            .addHeader("Cookie","xyz")
            .build();

        return chain.proceed(newRequest);
    }
});

new Picasso.Builder(context).downloader(new OkHttpDownloader(picassoClient)).build();

then in getView() I use Picasso to load images in ImageView:

Picasso.with(context).load(xyzUrl).fit().centerCrop().into(vImage);

It works well, but on device's rotation i see that heap size sometimes slowly grows and sometimes remains stable. Am i leaking memory or is there something wrong in code?

EDIT: I inserted this code after Picasso's call in the getView()

if (BuildConfig.DEBUG) {
    Log.i("HEAP SIZE",
    String.valueOf(Runtime.getRuntime().totalMemory() / 1024));
}

and I found that the heap size's growth happens in the getView() after loading bitmap into ImageView. What is wrong?


Android DatePicker compatibility issue with MonkeyTalk library


I have implemented an Android app, and just added MonkeyTalk library to test the usability of the system by recording user interaction with the app.

After using this library, everything works, but DataPicker!

I use the following method to show DataPicker dialog:

private void setSpecificDate() {

    int mYear = calendar.get(Calendar.YEAR);
    int mMonth = calendar.get(Calendar.MONTH);
    int mDay = calendar.get(Calendar.DAY_OF_MONTH);
    DatePickerDialog dpd = new DatePickerDialog(getActivity(), 
            new OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {

                // part of code uses retrieved data from DataPicker...

                }
            }, mYear, mMonth, mDay);
    dpd.show();
}

Then, as soon as I click to show the DatePicker, it crashes, I get the runtime error, and the program fails!

When I just comment out dpd.show(); It works, but nothing happens.

I have also tested to use TimePicker instead of DatePicker to check app behavior, and it worked!

The runtime error:

E/AndroidRuntime( 2679): FATAL EXCEPTION: main
E/AndroidRuntime( 2679): Process: com.parse.f8, PID: 2679
E/AndroidRuntime( 2679): java.lang.reflect.UndeclaredThrowableException
E/AndroidRuntime( 2679):    at $Proxy6.onItemSelected(Unknown Source)
E/AndroidRuntime( 2679):    at android.widget.AdapterView.fireOnSelected(AdapterView.java:897)
E/AndroidRuntime( 2679):    at android.widget.AdapterView.access$200(AdapterView.java:48)
E/AndroidRuntime( 2679):    at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:865)
E/AndroidRuntime( 2679):    at android.os.Handler.handleCallback(Handler.java:739)
E/AndroidRuntime( 2679):    at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime( 2679):    at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime( 2679):    at android.app.ActivityThread.main(ActivityThread.java:5221)
E/AndroidRuntime( 2679):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 2679):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 2679):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
E/AndroidRuntime( 2679):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
E/AndroidRuntime( 2679): Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime( 2679):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 2679):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.automators.AutomatorBase$MonkeyInvocationHandler.invoke(AutomatorBase.java:571)
E/AndroidRuntime( 2679):    at java.lang.reflect.Proxy.invoke(Proxy.java:397)
E/AndroidRuntime( 2679):    ... 12 more
E/AndroidRuntime( 2679): Caused by: java.lang.IllegalStateException: Unable to find field mOnDateChangedListener in any superclass of android.view.View$ListenerInfo
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.automators.AutomatorBase.chainListenerFor(AutomatorBase.java:483)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.automators.DatePickerAutomator.installDefaultListeners(DatePickerAutomator.java:43)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.processView(FunctionalityAdder.java:71)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.walkTree(FunctionalityAdder.java:48)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.walkTree(FunctionalityAdder.java:58)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.walkTree(FunctionalityAdder.java:58)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.walkTree(FunctionalityAdder.java:58)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.walkTree(FunctionalityAdder.java:58)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.walkTree(FunctionalityAdder.java:58)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.FunctionalityAdder.walkTree(FunctionalityAdder.java:58)
E/AndroidRuntime( 2679):    at com.gorillalogic.fonemonkey.aspects.OnCreate.ajc$afterReturning$com_gorillalogic_fonemonkey_aspects_OnCreate$7$35d40fb6(OnCreate.aj:115)
E/AndroidRuntime( 2679):    at com.parse.f8.view.SettingAdvTime.setSpecificDate(SettingAdvTime.java:396)
E/AndroidRuntime( 2679):    at com.parse.f8.view.SettingAdvTime.access$3(SettingAdvTime.java:373)
E/AndroidRuntime( 2679):    at com.parse.f8.view.SettingAdvTime$1.onItemSelected(SettingAdvTime.java:122)
E/AndroidRuntime( 2679):    ... 16 more

I would appreciate anyone's assist to solve this problem.


Youtube Request gets blocked


I wanted to use the Android Youtube API for that i created an API key in google console and added it to my project. Now when i execute a Youtube Query i get the following message:

04-25 16:41:05.899: W/System.err(7213): com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
04-25 16:41:05.900: W/System.err(7213): {
04-25 16:41:05.900: W/System.err(7213):   "code" : 403,
04-25 16:41:05.900: W/System.err(7213):   "errors" : [ {
04-25 16:41:05.900: W/System.err(7213):     "domain" : "usageLimits",
04-25 16:41:05.900: W/System.err(7213):     "message" : "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
04-25 16:41:05.900: W/System.err(7213):     "reason" : "ipRefererBlocked",
04-25 16:41:05.900: W/System.err(7213):     "extendedHelp" : "http://ift.tt/1fljiJ4"
04-25 16:41:05.900: W/System.err(7213):   } ],
04-25 16:41:05.900: W/System.err(7213):   "message" : "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
04-25 16:41:05.900: W/System.err(7213): }

What else do i have to do to make google not blocking my request? The request limit per user is 3000 per day and i used 0 of it.


set 2 characters as one


I have a bt TextView that contains two items.

bt.setText("O" + "u");

I want to consider this two item as one and when I hit the delete button, both of the remove. How can I do it? Thanks a lot.


AutoCompleteTextView's Adapter Wrap whole screen


I want AutoCompleteTextView adapter upper to specific layout as in image below

enter image description here

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:clipChildren="false"
    tools:context=".HandleAllActivity" >

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:clipChildren="false" >

        <!-- Framelayout to display Fragments -->

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

        <!-- Listview to display slider menu -->

        <include
            android:id="@+id/drawer_star_side_ref"
            android:layout_width="150dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            layout="@layout/drawer_start_side" />

        <include
            android:id="@+id/drawer_end_side_ref"
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:layout_gravity="end"
            layout="@layout/drawer_end_side" />
    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>

Code of ActionBar is

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:gravity="center" >

    <ImageView
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:onClick="drawerOpenOrClose"
        android:src="@drawable/drawer_selector"
        android:tag="left" />

    <ImageView
        android:id="@+id/toggleButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:onClick="drawerOpenOrClose"
        android:src="@drawable/drawer_selector"
        android:tag="right" />

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/toggleButton1"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/toggleButton2"
        android:layout_toRightOf="@+id/toggleButton1"
        android:background="@drawable/ractangle_shape"

        android:singleLine="true" >
    </AutoCompleteTextView>

</RelativeLayout>

values of adapter is loaded from database


Differenciate between onMarkerClick and onClusterItemClick event in Android


I am using google map v2 with 1000 plus markers being fetched from web service. So for this reason i am using map clustering. I am showing info window onMarkerClick but the problem is that when the user click on cluster it shows info window because onMarkerClick event is triggered. I want to zoom further when cluster of markers is clicked. There is onClusterItemClick event but its not working with onMarkerClick. Any feasible solution is appreciated in advance.

Thanks


Android AsincTask terminated before completion if connection or device is slow


I have an AsyncTask where I invoke a method that download some data from internet and performs certain operations.

In the emulator this works always despite the connection speed but on real devices if connection or device isn't fast this task is automatically terminated. I don't know why, but probably there is some kind of default timeout in Android default task management.

How could I fix this problem?

How to force the completion of the task always?

Here my code

myTask = new AsyncTask<Void, Void, Void>() {
            ProgressDialog pd;
            boolean correctlyInitialized = true;


            @Override
            protected void onPreExecute() {
                pd= new ProgressDialog(CatcherTree.this);


                pd.setCancelable(false);
                try {
                    pd.show();
                } catch (Error e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected Void doInBackground(Void... params) {
                long t = System.currentTimeMillis();

               //this method requires time to complete
                updateAllDataSet(CatcherTree.this);

                return null;
            }

            @Override
            protected void onPostExecute(Void rate) {
                pd.dismiss();

            }
        }.execute();


AdRequest Builder cannot be resolved to a type


I finished developing a game for Android using a slightly modified version of the framework at http://ift.tt/1yhsJkp. Then I followed this tutorial:http://ift.tt/W4GKD7 and successfully added an ad but not on my main activity as this framework does not have a .xml file for the main activity (surface view in pure java code). However, I want ads to appear on the main activity too since that contains 95% of the game. I managed to successfully add a test view (button) on the surfaceview using an online tutorial but when I changed the button to an AdView I got this error:

"AdRequest.Builder cannot be resolved to a type" in

AdRequest adRequest = new AdRequest.Builder().build();.

Can someone tell me what could cause this error? Eclipse accepted the exact same code in my other activity on the same project but not here. I have imported these

import com.google.ads.AdRequest;
import com.google.android.gms.ads.AdView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    appContext = this.getApplicationContext();
    mainLayout = new FrameLayout(this);
    adLayout = new RelativeLayout(this);

    adView = new AdView(this);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // google test id
    //AdRequest adRequest = new AdRequest.Builder().build();
    adView.setAdSize(AdSize.BANNER);


    RelativeLayout.LayoutParams lp1 = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams lp2 = new LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    adLayout.setLayoutParams(lp2);
    adLayout.addView(adView);
    lp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);  
    lp1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    adView.setLayoutParams(lp1); 

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    int frameBufferWidth = isPortrait ? 800 : 1280;
    int frameBufferHeight = isPortrait ? 1280 : 800;
    Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth, frameBufferHeight, Config.RGB_565);

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float scaleX = (float) frameBufferWidth / metrics.widthPixels;
    float scaleY = (float) frameBufferHeight / metrics.heightPixels;

    GameScreen.deviceWidth = metrics.widthPixels;
    GameScreen.deviceHeight = metrics.heightPixels;

    prefs = this.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
    prefsExist = prefs.contains("showValueAddition");
    loadDefaultSettings();

    renderView = new AndroidFastRenderView(this, frameBuffer);
    graphics = new AndroidGraphics(getAssets(), frameBuffer);
    fileIO = new AndroidFileIO(this);
    audio = new AndroidAudio(this);
    input = new AndroidInput(this, renderView, scaleX, scaleY);
    screen = getInitScreen(prefs);

    mainLayout.addView(renderView);
    mainLayout.addView(adLayout);
    setContentView(mainLayout);
}

Any help is appreciated.


setVisibility not working [duplicate]


This question already has an answer here:

I am trying to hide a button if a logged in user is a Donor. I have my code like this.

String typ = user.get("type").toString();
    Log.d("before checking type", typ);

    if (typ == "Donor"){

        ne.setVisibility(View.GONE);
        //ne.setEnabled(false);
    }

In the log, I get the result Donor, so I know the call to the database is working. But the button I need to hide, doesn't hide. Anyone knows why?


When Extending, View invalidate() method does not call OnDraw of Android


I know similar question has been asked multiple times but most questions answers deal with ViewGroup and not simple View class it self , some suggest to set the setWillNotDraw(false) this does not work in my case .

public class Animated_class extends View {
private Paint paint,paint2,paint3,paint4;
private float percentage;
float fangle;
ObjectAnimator ob;
String month;



public void setPercentage(Float percentage,String month) {
    this.month=month;
    this.percentage=percentage;
    Float p=360f;

  ob=ObjectAnimator.ofFloat(this,"fangle",0f,p);
  ob.setDuration(2000);
  ob.start();
}


public void setFangle(float value) {
    Log.e("animation", "setfangle:" +value+" "+fangle);
    this.fangle = value;
   invalidate();
}



public Animated_class(Context context,AttributeSet st) {
    super(context,st);
    setWillNotDraw(false);


    TypedArray a = context.getTheme().obtainStyledAttributes(
            st,
            R.styleable.Animated_class,
            0, 0);

    try {

        percentage = a.getFloat(R.styleable.Animated_class_percentage, 0);
        month=a.getString(R.styleable.Animated_class_month);
    } finally {
        a.recycle();
    }

    paint2=new Paint();
    paint3=new Paint();
    paint4=new Paint();
    paint4.setTextSize(50);
    paint2.setAntiAlias(true);
    paint3.setAntiAlias(true);

    paint2.setARGB(255,255,255,255);
    paint3.setARGB(255,67,187,118);



}

public Animated_class(Context context) {
    super(context);
    setWillNotDraw (false);

    paint2=new Paint();
    paint3=new Paint();
    paint4=new Paint();
    paint4.setTextSize(50);
    paint2.setAntiAlias(true);
    paint3.setAntiAlias(true);

    paint2.setARGB(255,255,255,255);
    paint3.setARGB(255,67,187,118);





}

@Override
protected void onDraw(Canvas canvas) {
     super.onDraw(canvas);


        RectF rec = new RectF(170, 170, 470, 470);


        canvas.drawArc(rec, 0, fangle, true, paint2);



    Log.e("onDraw", "inside"+fangle);



}

}

this is a simple code to animate the formation of a circle by drawing an arc from 0 to 360 degree.

this is my log:

so here you can see onDraw is only called twice and set method is working fine by setting value of fangle from 0 to 360 but onDraw is not being called .

    04-25 04:34:41.676      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:0.0 0.0
04-25 04:34:41.737      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:0.0 0.0
04-25 04:34:41.902      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:6.1577725 0.0
04-25 04:34:41.908      473-473/com.example.pulkittyagi.animated_date E/onDraw﹕ inside0.0
04-25 04:34:42.159      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:37.253803 6.1577725
04-25 04:34:42.161      473-473/com.example.pulkittyagi.animated_date E/onDraw﹕ inside0.0
04-25 04:34:42.179      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:40.232426 37.253803
04-25 04:34:42.183      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:43.126938 40.232426
04-25 04:34:42.200      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:46.29702 43.126938
04-25 04:34:42.216      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:49.562428 46.29702
04-25 04:34:42.234      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:52.720783 49.562428
04-25 04:34:42.250      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:56.164543 52.720783
04-25 04:34:42.267      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:59.696617 56.164543
04-25 04:34:42.285      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:63.099342 59.696617
04-25 04:34:42.301      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:66.79556 63.099342
04-25 04:34:42.318      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:70.57257 66.79556
04-25 04:34:42.333      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:74.19863 70.57257
04-25 04:34:42.350      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:78.12458 74.19863
04-25 04:34:42.366      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:82.12312 78.12458
04-25 04:34:42.384      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:85.95028 82.12312
04-25 04:34:42.400      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:90.08165 85.95028
04-25 04:34:42.417      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:94.27712 90.08165
04-25 04:34:42.434      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:98.281715 94.27712
04-25 04:34:42.451      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:102.59308 98.281715
04-25 04:34:42.467      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:106.959625 102.59308
04-25 04:34:42.483      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:111.11699 106.959625
04-25 04:34:42.500      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:115.58175 111.11699
04-25 04:34:42.517      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:120.09245 115.58175
04-25 04:34:42.533      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:124.37693 120.09245
04-25 04:34:42.550      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:128.96759 124.37693
04-25 04:34:42.568      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:133.5947 128.96759
04-25 04:34:42.583      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:137.97981 133.5947
04-25 04:34:42.600      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:142.66812 137.97981
04-25 04:34:42.617      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:147.38298 142.66812
04-25 04:34:42.633      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:151.84183 147.38298
04-25 04:34:42.650      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:156.59874 151.84183
04-25 04:34:42.668      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:161.37236 156.59874
04-25 04:34:42.683      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:165.87738 161.37236
04-25 04:34:42.700      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:170.67365 165.87738
04-25 04:34:42.716      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:175.47658 170.67365
04-25 04:34:42.733      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:180.0 175.47658
04-25 04:34:42.750      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:184.80605 180.0
04-25 04:34:42.767      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:189.60869 184.80605
04-25 04:34:42.783      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:194.12262 189.60869
04-25 04:34:42.800      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:198.90883 194.12262
04-25 04:34:42.816      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:203.68161 198.90883
04-25 04:34:42.833      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:208.15817 203.68161
04-25 04:34:42.850      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:212.89508 208.15817
04-25 04:34:42.866      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:217.60841 212.89508
04-25 04:34:42.883      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:222.02019 217.60841
04-25 04:34:42.900      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:226.67847 222.02019
04-25 04:34:42.917      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:231.30347 226.67847
04-25 04:34:42.933      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:235.62308 231.30347
04-25 04:34:42.950      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:240.17407 235.62308
04-25 04:34:42.966      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:244.68216 240.17407
04-25 04:34:42.983      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:248.88301 244.68216
04-25 04:34:43.000      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:253.29868 248.88301
04-25 04:34:43.016      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:257.66208 253.29868
04-25 04:34:43.033      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:261.7183 257.66208
04-25 04:34:43.050      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:265.97137 261.7183
04-25 04:34:43.066      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:270.1632 265.97137
04-25 04:34:43.083      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:274.0497 270.1632
04-25 04:34:43.101      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:278.11407 274.0497
04-25 04:34:43.117      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:282.10837 278.11407
04-25 04:34:43.133      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:285.80136 282.10837
04-25 04:34:43.150      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:289.65182 285.80136
04-25 04:34:43.166      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:293.4241 289.65182
04-25 04:34:43.183      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:296.90067 293.4241
04-25 04:34:43.200      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:300.51355 296.90067
04-25 04:34:43.217      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:304.0405 300.51355
04-25 04:34:43.233      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:307.27924 304.0405
04-25 04:34:43.250      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:310.63226 307.27924
04-25 04:34:43.266      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:313.8921 310.63226
04-25 04:34:43.284      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:316.87305 313.8921
04-25 04:34:43.300      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:319.94556 316.87305
04-25 04:34:43.316      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:322.91827 319.94556
04-25 04:34:43.333      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:325.62305 322.91827
04-25 04:34:43.350      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:328.3961 325.62305
04-25 04:34:43.366      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:331.06326 328.3961
04-25 04:34:43.383      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:333.47525 331.06326
04-25 04:34:43.400      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:335.93167 333.47525
04-25 04:34:43.417      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:338.27695 335.93167
04-25 04:34:43.433      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:340.38116 338.27695
04-25 04:34:43.449      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:342.5059 340.38116
04-25 04:34:43.466      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:344.51477 342.5059
04-25 04:34:43.483      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:346.2983 344.51477
04-25 04:34:43.500      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:348.07822 346.2983
04-25 04:34:43.517      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:349.7383 348.07822
04-25 04:34:43.533      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:351.19016 349.7383
04-25 04:34:43.550      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:352.6143 351.19016
04-25 04:34:43.567      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:353.91534 352.6143
04-25 04:34:43.587      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:355.02658 353.91534
04-25 04:34:43.600      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:356.08615 355.02658
04-25 04:34:43.617      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:357.02014 356.08615
04-25 04:34:43.633      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:357.7839 357.02014
04-25 04:34:43.650      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:358.47235 357.7839
04-25 04:34:43.667      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:359.03354 358.47235
04-25 04:34:43.683      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:359.44513 359.03354
04-25 04:34:43.700      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:359.7582 359.44513
04-25 04:34:43.717      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:359.94315 359.7582
04-25 04:34:43.733      473-473/com.example.pulkittyagi.animated_date E/animation﹕ setfangle:360.0 359.94315


How to send data back to MainActivity


I have MainActivity and I´m using startActivityForResult in it for open another activity in which i´m working with some data in list. I can edit these data and delete too. After clicking on back button of my phone I want to send this edited list back to main activity. Where should i create that intent with that new list?Is there any method which i can override for that back button?


ANDROID- Send money to user? Paypal


In my Android app, I need it to where, if the user has enough points, then they can click a button that will then send them money through PayPal. It's basically like those apps where you watch ads for points, then you redeem for PayPal cash. The problem is, I can't seem to find a way to do this, even though I've seen it done with countless apps.

To give a better understanding of what I am trying to achieve, here is a scenario:

Bob has 1,000 points. In the app, 1,000 points is $1 USD. He clicks a button that says 'Redeem $1'. The app then prompts him to sign into his PayPal account, and then it sends Bob the money (to his PayPal).

How can I achieve this?


Android video editor (maybe using FFmpeg for Android)


I need to create an app that allows trimming/splitting videos and remove their audio. How can I do this?

I've read about FFmped in this question FFMPEG on Android but I need to know if is it possible to use it in an app built with the SDK, not the NDK.


JUnit test failed to launch


I am doing my first JUnit test project but its not working.

I did two methods two test.

my console is giving me message " Failed to launch test" !

How can I solve it ?

package test;

public class Junit {

public String concentrate (String one, String two){ 

    return one + two;

}

public int multiply (int number1, int number2 ){

    return number1*number2;

}



}


How do I create array adapter with Image array


I have 2 array

Array 1 :

String[] web = {"Google Plus","Twitter","Windows","Bing","Itunes","Wordpress","Drupal"} ;

Array 2 :

String[] web = {"@drawable/img1","@drawable/img2","@drawable/img3","@drawable/img4","@drawable/img5","@drawable/img6","@drawable/img7"} ;

And I wnat create ArrayAdapter that use my Array1 for TextView and use Array2 for icon of row

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.single_row,R.id.textView,array);


Rotating bitmap in main game loop without overloading GC in Android


What is the correct way to rotate bitmap every frame in main game loop? What I have tried:

I created rotated bitmap every frame:

Bitmap image, tmp;
Matrix m;
...
public void mainGameLoop(Canvas c){
    m.reset();
    m.postRotate(angle);
    tmp = Bitmap.createBitmap(image, 0, 0, width, height, m, true);
    c.drawBitmap(tmp, 50, 50, null);
}

However, because Bitmap.createBitmap creates bitmap every frame Garbage Collector works so madly, it causes low FPS.

I have tried saving bitmap in array at all angles, and just taking bitmap which I want to. However, this needs a lot of RAM and app just couldn't launch at high screen resolutions.

If you have any ideas, please comment below.


Create simple android nfc reader/writer


I want to create a simple nfc reader/writer for android. My plan is that when I open my app I can place an RFID tag on the back of my phone and get a choice to read or write to the tag. If I choose read I want the phone to show the information on the tag and if I choose write I should be able to write something to the tag.

I have tried to look into this and read other peoples code but I cant' make anything of it probably due to my quite limited java knowledge. I would like some pointers to where I can find more basic information and from there start with the reader part and add the writer when that's working.


How to display image on client side using String,String is send Server?


My server sends string message to my client and the client reads the string.
String message is successfully sent, then this String is used for image identification.

I have done coding for this task but I can't run it.

Here is my class:

  private class ChatClientThread extends Thread {

    String name;
    String dstAddress;
    int dstPort;

    String msgToSend = "";
    boolean goOut = false;

    ChatClientThread(String name, String address, int port) {
        this.name = name;
        dstAddress = address;
        dstPort = port;
    }

    @Override
    public void run() {
        Socket socket = null;
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;

        try {
            socket = new Socket(dstAddress, dstPort);
            dataOutputStream = new DataOutputStream(
            socket.getOutputStream());
            dataInputStream = new DataInputStream(socket.getInputStream());
            dataOutputStream.writeUTF(name);
            dataOutputStream.flush();
            int counter = 0;
            while (!goOut) {
                if (dataInputStream.available() > 0) {
                    msgLog += dataInputStream.readUTF();
                    // start editing
                    String[] separated = msgLog.split("\\,");

                    for (int i = 2; i < separated.length - 1; i += 2) {
                        String symbol = separated[i];
                        String num = separated[i + 1];
                        String resourceName = symbol + num;
                        int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
                        ImageView im = (ImageView) findViewById(resID);
                        Context context = im.getContext();
                        int id = context.getResources().getIdentifier(resourceName, "drawable", context.getPackageName());
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(im.getLayoutParams());
                        //43,0,0,0


                        lp.setMargins(counter * 65, 24, 40, 5); //left,right,top,bottom
                        im.setLayoutParams(lp);
                        im.setImageResource(id);
                        // im.setOnClickListener(this);
                        counter++;
                    }


                    /* MainActivity.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                chatMsg.setText(msgLog);
                            }
                        });*/
                }

                if (!msgToSend.equals("")) {
                    dataOutputStream.writeUTF(msgToSend);
                    dataOutputStream.flush();
                    msgToSend = "";
                }
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
            final String eString = e.toString();
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
                }

            });
        } catch (IOException e) {
            e.printStackTrace();
            final String eString = e.toString();
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
                }

            });
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    loginPanel.setVisibility(View.VISIBLE);
                    chatPanel.setVisibility(View.GONE);
                }

            });
        }

    }

    private void sendMsg(String msg) {
        msgToSend = msg;
    }

    private void disconnect() {
        goOut = true;
    }
  }

  }


Cannot instate the type PagerAdapter? What's wrong?


Hey guys I'm trying to swipe between my activities using PagerAdapter but I'm getting error here's my code, I'm a little new to development of Android, so I'm unable to understand the problem where I've found the solution on Internet. Can anybody tell me how to exactly fix it? Any help would be appreciated, thanks! Here's my code:

PagerAdapter.java :-

package com.example.prototype;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class PagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;

    }

    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }
}

ViewPagerFragmentActivity :-

package com.example.prototype;

import java.util.List;
import java.util.Vector;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;

import com.example.prototype.R;
import com.example.prototype.Games;
import com.example.prototype.Movies;
import com.example.prototype.Songs;

public class ViewPagerFragmentActivity extends FragmentActivity {

    private PagerAdapter mPagerAdapter;

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

        this.initialisePaging();
    }

    private void initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Games.class.getName()));
        fragments.add(Fragment.instantiate(this, Movies.class.getName()));
        fragments.add(Fragment.instantiate(this, Songs.class.getName()));

        this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);      //Error at this line!!!

        ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager);
        pager.setAdapter(this.mPagerAdapter);
    }
}

Whole LogCat :-

04-25 14:08:12.082: E/vinput-seamless(108): found PS2 device
04-25 14:08:12.082: E/vinput-seamless(108): found seamless mouse device
04-25 14:08:17.726: E/setdpi(286): Setting DPI to 240
04-25 14:08:17.858: E/SurfaceFlinger(116): setOrientation with orientation=0
04-25 14:08:17.858: E/SurfaceFlinger(116): setOrientation orientation=0
04-25 14:08:17.858: E/FramebufferNativeWindow(116): setOrientation with fbDev=0xb85a1af0 fbDev->setOrientation=0xb6003f20 orientation=0
04-25 14:08:18.230: E/local_camera(112): We have a problem with the player connection 22 (Invalid argument)
04-25 14:08:21.930: E/PhonePolicy(117): Could not preload class for phone policy: com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback
04-25 14:08:23.410: E/Genymotion(301): usbOnlinePath not found
04-25 14:08:23.410: E/Genymotion(301): batteryStatusPath not found
04-25 14:08:23.410: E/Genymotion(301): batteryHealthPath not found
04-25 14:08:23.410: E/Genymotion(301): batteryPresentPath not found
04-25 14:08:23.410: E/Genymotion(301): batteryCapacityPath and batteryEnergyPaths not found
04-25 14:08:23.410: E/Genymotion(301): batteryVoltagePath not found
04-25 14:08:23.410: E/Genymotion(301): batteryTemperaturePath not found
04-25 14:08:23.410: E/Genymotion(301): batteryTechnologyPath not found
04-25 14:08:25.174: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:08:25.182: E/libsuspend(301): Error opening /sys/power/autosleep: No such file or directory
04-25 14:08:25.182: E/libsuspend(301): Error opening /sys/power/wakeup_count: Permission denied
04-25 14:08:25.182: E/libsuspend(301): failed to initialize autosuspend
04-25 14:08:25.282: E/WVMExtractor(119): Failed to open libwvm.so
04-25 14:08:25.318: E/WVMExtractor(119): Failed to open libwvm.so
04-25 14:08:25.326: E/EventHub(301): could not get driver version for /dev/input/mouse3, Not a typewriter
04-25 14:08:25.350: E/EventHub(301): could not get driver version for /dev/input/mouse2, Not a typewriter
04-25 14:08:25.366: E/EventHub(301): could not get driver version for /dev/input/mouse1, Not a typewriter
04-25 14:08:25.406: E/EventHub(301): could not get driver version for /dev/input/mouse0, Not a typewriter
04-25 14:08:25.442: E/EventHub(301): could not get driver version for /dev/input/mice, Not a typewriter
04-25 14:08:25.458: E/ConnectivityService(301): Ignoring protectedNetwork 10
04-25 14:08:25.458: E/ConnectivityService(301): Ignoring protectedNetwork 11
04-25 14:08:25.458: E/ConnectivityService(301): Ignoring protectedNetwork 12
04-25 14:08:25.466: E/WifiStateMachine(301): Failed to reload STA firmware java.lang.IllegalStateException: command '2 softap fwreload eth1 STA' failed with '400 2 Softap operation failed (Success)'
04-25 14:08:25.570: E/WifiConfigStore(301): Error parsing configurationjava.io.FileNotFoundException: /data/misc/wifi/ipconfig.txt: open failed: ENOENT (No such file or directory)
04-25 14:08:25.574: E/WifiStateMachine(301): Failed to set frequency band 0
04-25 14:08:26.402: E/GpsLocationProvider(301): no AGPS interface in agps_data_conn_open
04-25 14:08:26.454: E/ActivityThread(423): Failed to find provider info for com.android.inputmethod.latin.dictionarypack
04-25 14:08:26.458: E/BinaryDictionaryGetter(423): Could not find a dictionary pack
04-25 14:08:27.922: E/WVMExtractor(119): Failed to open libwvm.so
04-25 14:08:28.074: E/WVMExtractor(119): Failed to open libwvm.so
04-25 14:08:28.270: E/WVMExtractor(119): Failed to open libwvm.so
04-25 14:08:28.314: E/WVMExtractor(119): Failed to open libwvm.so
04-25 14:08:28.334: E/WVMExtractor(119): Failed to open libwvm.so
04-25 14:08:30.174: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:08:51.417: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:08:56.417: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:01.418: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:06.417: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:11.417: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:16.418: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:21.417: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:26.418: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:31.421: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:36.421: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:41.421: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:46.429: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:51.430: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:09:56.433: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:01.433: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:06.434: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:11.434: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:16.433: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:21.433: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:26.437: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:31.437: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:36.437: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:41.437: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:46.438: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:51.437: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:10:56.437: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:01.441: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:06.441: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:11.441: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:16.441: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:21.441: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:26.441: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:31.442: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:36.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:41.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:46.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:51.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:11:56.446: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:01.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:06.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:11.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:16.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:21.445: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:26.449: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:31.449: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:36.449: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:41.449: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:46.449: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:51.450: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:12:56.449: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:13:01.449: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:13:06.453: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:13:11.453: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'
04-25 14:13:16.453: E/Genymotion(301): Could not open '/sys/class/power_supply/genymotion_fake_path/present'