今天首先是分享介面的設計與完成,也就是發帖功能的實現
FenxiangFragment.java
package com.example.share;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.example.share.dao.postDao;
import com.example.share.entity.MyUser;
import com.example.share.entity.post;
import com.example.share.utils.CommonUtils;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class FenxiangFragment extends Fragment {
private static final int PICK_IMAGE_REQUEST = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
private static final int REQUEST_LOCATION_PERMISSION = 3;
private ArrayList
private ImageGridAdapter adapter;
private FusedLocationProviderClient fusedLocationClient;
private String locationString;
private TextView locationTextView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fenxiang, container, false);
EditText editText = view.findViewById(R.id.editTextShareContent);
GridView gridView = view.findViewById(R.id.gridViewImages);
Button shareButton = view.findViewById(R.id.buttonShare);
Button locationButton = view.findViewById(R.id.buttonLocation);
locationTextView = view.findViewById(R.id.textViewLocation);
imageUris = new ArrayList<>();
adapter = new ImageGridAdapter(getActivity(), imageUris);
gridView.setAdapter(adapter);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
gridView.setOnItemClickListener((parent, view1, position, id) -> {
if (position == imageUris.size()) {
openImageSelector();
}
});
shareButton.setOnClickListener(v -> submitPost(editText.getText().toString(), imageUris));
locationButton.setOnClickListener(v -> requestLocation());
return view;
}
private void openImageSelector() {
final CharSequence[] options = {"從相簿中選擇圖片", "開啟相機", "取消"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("選擇操作");
builder.setItems(options, (dialog, item) -> {
if (options[item].equals("從相簿中選擇圖片")) {
requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, PICK_IMAGE_REQUEST);
} else if (options[item].equals("開啟相機")) {
requestPermission(Manifest.permission.CAMERA, REQUEST_IMAGE_CAPTURE);
} else if (options[item].equals("取消")) {
dialog.dismiss();
}
});
builder.show();
}
private void requestPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
} else {
handlePermissionGranted(requestCode);
}
}
private void handlePermissionGranted(int requestCode) {
if (requestCode == PICK_IMAGE_REQUEST) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
} else if (requestCode == REQUEST_IMAGE_CAPTURE) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(getActivity(), "沒有找到相機應用", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_LOCATION_PERMISSION) {
requestLocation();
}
}
private void requestLocation() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
} else {
fusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(), location -> {
if (location != null) {
locationString = "Lat: " + location.getLatitude() + ", Lng: " + location.getLongitude();
locationTextView.setText(locationString);
Toast.makeText(getActivity(), "位置: " + locationString, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "無法獲取位置", Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
handlePermissionGranted(requestCode);
} else {
Toast.makeText(getActivity(), "許可權被拒絕", Toast.LENGTH_SHORT).show();
}
}
private void submitPost(String text, ArrayList<Uri> imageUris) {
SharedPreferences sharedPref = getActivity().getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
String username = sharedPref.getString("username", ""); // 獲取儲存的使用者名稱,如果沒有則預設為空字串
post post1 = new post(username,text,imageUris);
postDao postDao = new postDao();
postDao.savePost(username,text,imageUris);
sendDataToServer(text);
for (Uri uri : imageUris) {
sendImageToServer(uri);
}
Toast.makeText(getActivity(), "釋出成功", Toast.LENGTH_SHORT).show();
}
private void sendDataToServer(String text) {
System.out.println("傳送文字到伺服器: " + text);
}
private void sendImageToServer(Uri uri) {
System.out.println("傳送圖片到伺服器: " + uri.toString());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
Uri imgUri = data.getData();
if (imgUri != null) {
imageUris.add(imgUri);
adapter.notifyDataSetChanged();
}
} else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK && data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bitmap = (Bitmap) extras.get("data");
if (bitmap != null) {
Uri imgUri = getImageUriFromBitmap(getActivity(), bitmap);
imageUris.add(imgUri);
adapter.notifyDataSetChanged();
}
}
}
}
private Uri getImageUriFromBitmap(Context context, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
}
fragment_fenxiang.xml
<EditText
android:id="@+id/editTextShareContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="分享你的新鮮事..."
android:inputType="textMultiLine"
android:padding="10dp"/>
<GridView
android:id="@+id/gridViewImages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextShareContent"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:padding="4dp"/>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/buttonLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/gridViewImages"
android:text="獲取位置"
android:padding="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:id="@+id/textViewLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/gridViewImages"
android:layout_alignParentRight="true"
android:padding="8dp"
android:text="位置"
android:textColor="#000000"
android:textSize="14sp" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/buttonShare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/buttonLocation"
android:text="發表"
android:padding="10dp"
android:layout_marginTop="10dp"/>