1

我试图获取用户位置。如何将用户位置保存到数据库?也许我可以通过它的纬度和经度保存位置。现在我可以用标记在地图上获取用户位置。真的需要帮助。谢谢。

登录注册.java

             package mp.memberuse;

            import android.app.Activity;
            import android.content.Context;
            import android.content.Intent;
            import android.content.SharedPreferences;
            import android.content.SharedPreferences.Editor;
            import android.database.Cursor;
            import android.database.sqlite.SQLiteDatabase;
            import android.os.Bundle;
            import android.view.View;
            import android.widget.Button;
            import android.widget.EditText;
            import android.widget.TabHost;
            import android.widget.TabHost.TabSpec;
            import android.widget.TextView;

            public class LoginRegister extends Activity {

Button btn1, btn2, btn3;
EditText tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9, tf10, tf11;
TextView tv1, tv2;
SQLiteDatabase db;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TabHost tabs = (TabHost) this.findViewById(R.id.lt2tabhost);
    tabs.setup();

    TabSpec ts1 = tabs.newTabSpec("Login");
    ts1.setIndicator("Login");
    ts1.setContent(R.id.c1);
    tabs.addTab(ts1);

    TabSpec ts2 = tabs.newTabSpec("Register");
    ts2.setIndicator("Register");
    ts2.setContent(R.id.c2);
    tabs.addTab(ts2);

    btn1 = (Button)findViewById(R.id.button1);
    btn2 = (Button)findViewById(R.id.button2);
    btn3 = (Button)findViewById(R.id.button3);

    tf1=(EditText) findViewById(R.id.editText1);
    tf2=(EditText) findViewById(R.id.editText2);
    tf3=(EditText) findViewById(R.id.editText3);
    tf4=(EditText) findViewById(R.id.editText4);
    tf5=(EditText) findViewById(R.id.editText5);
    tf6=(EditText) findViewById(R.id.editText6);
    tf7=(EditText) findViewById(R.id.editText7);
    tf8=(EditText) findViewById(R.id.editText8);
    tf9=(EditText) findViewById(R.id.editText9);
    tf10=(EditText) findViewById(R.id.editText10);

    tv1=(TextView) findViewById(R.id.login);
    tv2=(TextView) findViewById(R.id.register);



    try
    {
        db = SQLiteDatabase.openOrCreateDatabase("sdcard/Members.db", null);
        db.beginTransaction();
        db.execSQL("create table if not exists Members (username text PRIMARY KEY, password text, fullname text, nric text, address text, phone text, email text);");
        db.setTransactionSuccessful();
        db.endTransaction();
    }
    catch(Exception e)
    {
    }

    btn1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v)
        {
            String username, password;
            username = tf1.getText().toString();
            password = tf2.getText().toString();

            try
            {
                String sql="select * from Members;";
                Cursor c1= db.rawQuery(sql, new String[]{});
                String sqlusername, sqlpassword, fullname;


                while(c1.moveToNext())
                {
                    sqlusername = c1.getString(0);
                    sqlpassword = c1.getString(1);
                    fullname = c1.getString(2);

                    if(username.equals(sqlusername) && password.equals(sqlpassword))
                    {
                        SharedPreferences prefs = getSharedPreferences("myPreferences",Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putString("fullname", fullname);
                        editor.commit();

                        Intent intent = new Intent(LoginRegister.this, Map.class);
                        startActivity(intent);
                    }
                    else
                    {
                        tv1.setText("Invalid user");
                    }
                }
            }
            catch(Exception e)
            {
            }
        }
    });

    btn2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v)
        {
            String username, password, cpassword, fullname, nric, address, phone, email;
            username = tf3.getText().toString();
            password = tf4.getText().toString();
            cpassword = tf5.getText().toString();
            fullname = tf6.getText().toString();
            nric = tf7.getText().toString();
            address = tf8.getText().toString();
            phone = tf9.getText().toString();
            email = tf10.getText().toString();

            if(!password.equals(cpassword))
            {
                tv2.setText("Password & Confirm Password does not match.");
            }
            else if(username.equals("") || password.equals("") || cpassword.equals("") || fullname.equals("") || nric.equals("") || address.equals("") || phone.equals("") || email.equals(""))
            {
                tv2.setText("Do not leave any field empty.");
            }
            else
            {
                try
                {
                    db.beginTransaction();
                    db.execSQL("insert into Members(username, password, fullname, nric, address, phone, email) values('"+username+"','"+password+"','"+fullname+"','"+nric+"','"+address+"','"+phone+"','"+email+"');");
                    db.setTransactionSuccessful();
                    db.endTransaction();    
                }
                catch(Exception e)
                {
                }
                    tv2.setText("Register Complete.");
                    tf3.setText("");
                    tf4.setText("");
                    tf5.setText("");
                    tf6.setText("");
                    tf7.setText("");
                    tf8.setText("");
                    tf9.setText("");
                    tf10.setText(""); 
            }
        }
    });

    btn3.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v)
        {
            tf3.setText("");
            tf4.setText("");
            tf5.setText("");
            tf6.setText("");
            tf7.setText("");
            tf8.setText("");
            tf9.setText("");
            tf10.setText("");           
        }
    });
}
    }

地图.java

      package mp.memberuse;

      import android.app.Dialog;
      import android.location.Criteria;
      import android.location.Location;
      import android.location.LocationListener;
      import android.location.LocationManager;
      import android.os.Bundle;
      import android.support.v4.app.FragmentActivity;
      import android.view.Menu;
      import android.widget.TextView;

      import com.google.android.gms.common.ConnectionResult;
      import com.google.android.gms.common.GooglePlayServicesUtil;
      import com.google.android.gms.maps.CameraUpdateFactory;
      import com.google.android.gms.maps.GoogleMap;
      import com.google.android.gms.maps.SupportMapFragment;
      import com.google.android.gms.maps.model.BitmapDescriptorFactory;
      import com.google.android.gms.maps.model.LatLng;
      import com.google.android.gms.maps.model.MarkerOptions;

      public class Map extends FragmentActivity  {

          GoogleMap googleMap;

          @Override
          protected void onCreate(Bundle savedInstanceState) 
          {
              super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if(status!=ConnectionResult.SUCCESS)
    { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }
    else 
    { // Google Play Services are available

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

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        LocationListener locationListener = new LocationListener() 
        {
          public void onLocationChanged(Location location) 
          {
          // redraw the marker when get location update.
          drawMarker(location);
          }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
            // TODO Auto-generated method stub

        }
        };

        if(location!=null)
        {
           //PLACE THE INITIAL MARKER              
           drawMarker(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
    }
 }
private void drawMarker(Location location)
{
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.addMarker(new MarkerOptions().position(currentPosition).snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
    .title("ME"));

     String currentLocation = Double.toString(location.getLatitude()) + Double.toString(location.getLongitude());

SharedPreferences prefs = getSharedPreferences("myPreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

editor.putString("currentLocation", currentLocation);
editor.commit();

Intent intent = new Intent(Map.this, SendMessage.class);
startActivity(intent);
}

 }

发送消息.java

        package mp.memberuse;

        import android.app.Activity;
        import android.content.Context;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.content.SharedPreferences.Editor;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.location.LocationManager;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TabHost;
        import android.widget.TabHost.TabSpec;
        import android.widget.TextView;

        public class SendMessage extends Activity{

Button btn1;
EditText tf1;
TextView tv1, tv2;
SQLiteDatabase db;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);

    btn1 = (Button)findViewById(R.id.button1);


    tf1=(EditText) findViewById(R.id.editText1);

    tv1=(TextView) findViewById(R.id.welcome);
    tv2=(TextView) findViewById(R.id.submit);

    SharedPreferences prefs = getSharedPreferences("myPreferences",Context.MODE_PRIVATE);

    final String fullname= prefs.getString("fullname", null);
    final String currentlocation= prefs.getString("currentlocation", null);

    tv1.setText("Welcome " + fullname);

    try
    {
        db = SQLiteDatabase.openOrCreateDatabase("sdcard/Request.db", null);
        db.beginTransaction();
        db.execSQL("create table if not exists Request (fullname text, location text, message text);");
        db.setTransactionSuccessful();
        db.endTransaction();
    }
    catch(Exception e)
    {
    }

    btn1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v)
        {
            String text = tf1.getText().toString();

            db.beginTransaction();
            db.execSQL("insert into Request values("+fullname+","+currentlocation+","+text+")");

            tf1.setText("");
            tv2.setText("Message Sent!");
        }
    });
}
        }
4

0 回答 0