Affichage des articles dont le libellé est Active questions tagged android - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged android - Stack Overflow. Afficher tous les articles

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.