Мой TextView не хранится в моей базе данных? - PullRequest
0 голосов
/ 08 февраля 2012

Я пытаюсь соединить мою базу данных в два Editview и одно Textview. edit-views хранят, но проблема с сохранением текстовых представлений, я хотел бы сохранить значения Geo points (Lat & Lang) в виде TextView в моей базе данных. Вот мой код

public class Mydatabase4meActivity extends Activity {
    /** Called when the activity is first created. */
    ArrayList<String> al=new ArrayList<String>();
    EditText username_edt,pass_edt;
    Bitmap b;
    Button login_but;
    MyDatabase mdb;
    ImageView iv;
    SQLiteDatabase sqlite;
    TextView tv;
    Cursor c;
    LocationManager mlocManager;
    LocationListener mlocListener;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        username_edt=(EditText)findViewById(R.id.editText1);
        pass_edt=(EditText)findViewById(R.id.editText2);
        login_but=(Button)findViewById(R.id.button1);
        tv=(TextView)findViewById(R.id.textView1);
        // text view
        mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        mlocListener = new MyLocationListener();

       for (String provider: mlocManager.getAllProviders()) {
        System.out.println(provider);
        Location loc = mlocManager.getLastKnownLocation(provider);
        if (loc != null) {
        Double latitude = loc.getLatitude();
        Double longitude = loc.getLongitude();
        String Text = "Current location for provider "+ provider + ":"  + "Lat=" + latitude.toString() + " Long=" + longitude.toString();
        //tv.getTag(Text);
        tv.setText(Text);
        //Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
        }
        }
       mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);


        }
    public class MyLocationListener implements LocationListener

    {

        public void onLocationChanged(Location loc) {
            // TODO Auto-generated method stub

            loc.getLatitude();
            loc.getLongitude();
            String Text = "My current location is: "+ "Latitud ="  + loc.getLatitude() +
            "Longitud = " + loc.getLongitude();
            //tv.setText(Text);
            tv.setText(Text = "My current location is: "+ "Latitud ="  + loc.getLatitude() +
                    "Longitud = " + loc.getLongitude());
            //Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
        }
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            tv.getText();
            Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
        }

        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            tv.getText();
            Toast.makeText( getApplicationContext(),"Gps Enabled", Toast.LENGTH_SHORT).show();
        }

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

        }

}
    @Override
    protected void onDestroy() {
    super.onDestroy();
    if (mlocManager != null) {
    mlocManager.removeUpdates(mlocListener);
    mlocManager = null;
    }

//    login button
        login_but.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                mdb=new MyDatabase(getApplicationContext(), "abcdef", null, 1);
                sqlite=mdb.getWritableDatabase();
                ContentValues cv=new ContentValues();
                cv.put("Employeename", username_edt.getText().toString());
                cv.put("password", pass_edt.getText().toString());
                cv.put("coordinates", tv.getText().toString());
                sqlite.insert("employee", null, cv);
                 String col[]={"Employeename","password","coordinates"};
                    c=sqlite.query("employee",col, null, null, null, null, null);

                    if(c!=null){
                        c.moveToFirst();
                        do{
                            int i=c.getInt(c.getColumnIndex("Employeename"));
                            al.add(""+i);
                            String str=c.getString(c.getColumnIndex("coordinates"));
                            al.add(str);
                            String str1=c.getString(c.getColumnIndex("password"));
                            al.add(str1);

                        }while(c.moveToNext());
                    }

                    mdb.close();
                   sqlite.close(); 

                }
        });
        Toast.makeText(getApplicationContext(), "data is inserted", Toast.LENGTH_SHORT).show();

    }
}

вот это класс myDatabase

public class MyDatabase extends SQLiteOpenHelper{

    public MyDatabase(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("create table employee(Employeename varchar2(10),password integer(10),coordinates varchar2(7,2));");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

мой XML-файл ..

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
<EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="USERNAME" >


    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="PASSWORD"
        android:inputType="textPassword" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:text="Login" />


</LinearLayout>

1 Ответ

0 голосов
/ 08 февраля 2012

Взять строку глобальной переменной.

String strlatlong = null;

Теперь вы принимаете значения широты и долготы в двойном типе. Таким образом, вы можете хранить в строке. 1) если у вас есть одно поле lat-long в базе данных следующим образом:

strlatlong = String.valueOf(latitude)+" "+String.valueOf(longitude);

вставить в БД следующим образом:

cv.put ( "координаты", strlatlong);

2) если у вас есть два поля в базе данных, вы можете использовать следующее:

 String strlat = null;
 String strlong = null;
strlat = String.valueOf(latitude);
strlong =String.valueOf(longitude);

вставить в БД следующим образом:

cv.put("coordinate_lat",strlat);
cv.put("coordinate_long",strlong);

Вам следует изменить поля базы данных.

public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("create table employee(Employeename varchar2(10),password integer(10),coordinate_lat varchar,coordinate_long varchar);");

}

Изменения над таблицей позволят вам вставить в таблицу код, указанный выше.

...