如何将值从片段按钮传递到另一个活动

时间:2016-02-09 21:49:30

标签: android google-maps android-activity android-fragmentactivity

所以我有一张谷歌地图应用程序的地图片段。我想将标记(lat / lng)中的值传递给保存位置的String,然后我想将该值传递给另一个应用程序中的TextField。然后,该文本字段将存储到我构建的SQLite数据库中。

我目前的地图活动如下

public class MapActivity extends FragmentActivity
    implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener,
    Serializable {

GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final int EDITOR_REQUEST_CODE = 1001;
public static final String LOCAT_KEY = "location";
private GoogleApiClient mLocationClient;
private Marker marker;
Bundle bundle;
String value;
private static final double
        CITY_LAT = 53.3478,
        CITY_LNG = -6.2597;

Circle shape;
public String lat;
public String lng;
public String location;

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

    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabled = service
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    // check if enabled and if not send user to the GSP settings

    if (!enabled) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }

    // Getting reference to Button
    Button btnDraw = (Button) findViewById(R.id.btn_draw);

    if (servicesOK()) {
        mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        if (initMap()) {

            gotoLocation(CITY_LAT, CITY_LNG, 12);

            mMap.setMyLocationEnabled(true);

            mLocationClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();

            mLocationClient.connect();


        } else {
            Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
        }

    } else {
        mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    }

    bundle = new Bundle();

    btnDraw.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String location = lat + "," + lng;
            // Checks, whether location is captured
            ((TextView) findViewById(R.id.editLocation)).setText(location);
        }
    });
}

注意我只将代码添加到激活的实际按钮中。

我在XML文件中单击的按钮代码如下:

<Button
android:id="@+id/btn_draw"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/save_location_btn"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="mapLocationClick"/>

最后我的编辑器类代码如下:

public class EditorActivity extends AppCompatActivity {

public static final String KEY_ID = "id";
public static final String KEY_TIME = "time" ;
public static final String KEY_LOCAT = "location";


private String action;
private EditText editor;
private EditText editorDate;
private EditText editorTime;
private EditText editorLocation;
private ImageButton dateButton;
private ImageButton timeButton;
private ImageButton locationButton;
private String noteFilter;
private String oldText;
private String oldDate;
private String oldTime;
private String oldLocation;
String value = null;


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

    editor = (EditText) findViewById(R.id.editText);
    editorDate = (EditText) findViewById(R.id.editDate);
    editorTime = (EditText) findViewById(R.id.editTime);
    editorLocation = (EditText) findViewById(R.id.editLocation);
    dateButton = (ImageButton) findViewById(R.id.imgButtonCal);
    timeButton = (ImageButton) findViewById(R.id.imgButtonClock);
    locationButton = (ImageButton) findViewById(R.id.imgButtonMap);

    //enableEdit = (FloatingActionButton) findViewById(R.id.fabEdit);

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras == null) {
        action = Intent.ACTION_INSERT;
        setTitle(getString(R.string.new_note));
    }
    else {
        long id = extras.getLong(KEY_ID);

        if (id == 0){
            action = Intent.ACTION_INSERT;
            setTitle(getString(R.string.new_note));

            long time = intent.getLongExtra(KEY_TIME, 0);
            if (time != 0) {
                Date d = new Date(time);
                String dateString= DateFormat.format("yyyy-MM-dd", `d).toString();`
                editorDate.setText(dateString);
            }

        }

        else {
            action = Intent.ACTION_EDIT;
            setTitle(getString(R.string.edit_note));

            Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id);
            noteFilter = DBOpenHelper.NOTE_ID + "=" + uri.getLastPathSegment();

            Cursor cursor;
            cursor = getContentResolver().query(uri,
                    DBOpenHelper.ALL_COLUMNS, noteFilter, null, null);
            cursor.moveToFirst();
            oldText = cursor.getString(cursor.getColumnIndex(NOTE_TEXT));
            oldDate = cursor.getString(cursor.getColumnIndex(NOTE_DATE));
            oldTime = cursor.getString(cursor.getColumnIndex(NOTE_TIME));
            oldLocation = cursor.getString(cursor.getColumnIndex(NOTE_LOCATION));
            editor.setText(oldText);
            editor.setEnabled(false);
            editorDate.setText(oldDate);
            editorDate.setEnabled(false);
            dateButton.setEnabled(false);
            editorTime.setText(oldTime);
            editorTime.setEnabled(false);
            timeButton.setEnabled(false);
            editorLocation.setText(oldLocation);
            editorLocation.setEnabled(false);
            locationButton.setEnabled(false);
            //saveButton.setEnabled(false);
            editor.requestFocus();
            //enableEdit.setEnabled(true);
            //enableSave.setEnabled(false);
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (action.equals(Intent.ACTION_EDIT)){
        getMenuInflater().inflate(R.menu.menu_editor, menu);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (item.getItemId()) {
        case android.R.id.home:
            finishEditing();
            break;
        case R.id.action_delete:
            deleteNote();
            break;
        case R.id.action_edit:
            enableFields();
            break;
    }

    return true;
}
private void enableFields(){
    if(NotesProvider.CONTENT_URI != null) {
        editor.setEnabled(true);
        editorDate.setEnabled(true);
        dateButton.setEnabled(true);
        editorTime.setEnabled(true);
        timeButton.setEnabled(true);
        editorLocation.setEnabled(true);
        locationButton.setEnabled(true);

    }
}
private void deleteNote() {
    getContentResolver().delete(NotesProvider.CONTENT_URI,
            noteFilter,null);
    Toast.makeText(this, R.string.note_deleted,
            Toast.LENGTH_SHORT).show();
    setResult(RESULT_OK);
    finish();
}

private void finishEditing(){
    String newText = editor.getText().toString().trim();
    String newDate = editorDate.getText().toString().trim();
    String newTime = editorTime.getText().toString().trim();
    String newLocation = editorLocation.getText().toString().trim();

    switch (action) {
        case Intent.ACTION_INSERT:
            if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0){
                setResult(RESULT_CANCELED);
            } else{
                insertNote(newText, newDate, newTime, newLocation);
            }
            break;
        case Intent.ACTION_EDIT:
            if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0 && newLocation.length() == 0){
                deleteNote();
            }else if (oldText.equals(newText) && oldDate.equals(newDate) && oldTime.equals(newTime) && oldLocation.equals(newLocation)){
                setResult(RESULT_CANCELED);
            }else {
                updateNote(newText, newDate, newTime, newLocation);
            }
    }
    finish();
}

private void updateNote(String noteText, String noteDate, String noteTime, String noteLocation) {
    ContentValues values = new ContentValues();
    values.put(NOTE_TEXT, noteText);
    values.put(NOTE_DATE, noteDate);
    values.put(NOTE_TIME, noteTime);
    values.put(NOTE_LOCATION, noteLocation);
    getContentResolver().update(NotesProvider.CONTENT_URI, values, noteFilter, null);
    Toast.makeText(this, R.string.note_updated, Toast.LENGTH_SHORT).show();
    setResult(RESULT_OK);
}

private void insertNote(String noteText, String noteDate, String noteTime, String noteLocation) {
    ContentValues values = new ContentValues();
    values.put(NOTE_TEXT, noteText);
    values.put(NOTE_DATE, noteDate);
    values.put(NOTE_TIME, noteTime);
    values.put(NOTE_LOCATION, noteLocation);
    getContentResolver().insert(NotesProvider.CONTENT_URI, values);
    setResult(RESULT_OK);
}

@Override
public void onBackPressed() {
    finishEditing();
}

public void onSaveNote(View view) { finishEditing();}

public void onButtonClicked(View v){
    TimePickerFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}

public void showDatePickerDialog(View v) {
    DatePickerFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

public void openMapFragment(View v) {
    Intent intent = new Intent(this, MapActivity.class);
    startActivity(intent);
}

任何人都帮助我,所以当我点击按钮时,它将从该位置获取值并将其保存在之前加载的上一个类中。

1 个答案:

答案 0 :(得分:0)

我找到了答案。我在地图类中创建了以下内容

  

btnDraw.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            // Checks, whether location is captured
            Intent intent = MapActivity.this.getIntent();
            intent.putExtra(LATITUDE_EXTRA, lat);
            intent.putExtra(LONGITUDE_EXTRA, lng);
            MapActivity.this.setResult(RESULT_OK, intent);
            MapActivity.this.finish();
        }
    });

然后我通过以下内容将它添加到Editor类中。

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MAP_REQUEST_CODE && resultCode == RESULT_OK) {
        String lat = data.getStringExtra(MapActivity.LATITUDE_EXTRA);
        String lng = data.getStringExtra(MapActivity.LONGITUDE_EXTRA);

        editorLocation.setText(lat + ", " + lng);
    }
    else {
        Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show();
    }
}

似乎我需要添加一个新意图并使用onActivityResult。

相关问题