You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Android手机上传JSON文件至Firebase数据库?

Hey there! Let me walk you through exactly how to upload a JSON file from your Android device to Firebase Database—whether you're using Realtime Database or Cloud Firestore. I’ll break this down into actionable steps with code snippets you can adapt for your project.

1. Pre-requisites & Setup

First, make sure your Android project is connected to Firebase:

  • Create a Firebase project in the Firebase Console, add your Android app, and place the google-services.json file in your app's root directory.
  • Add the required Firebase dependencies to your app-level build.gradle file:
    • For Realtime Database:
      implementation 'com.google.firebase:firebase-database:20.3.0'
      
    • For Cloud Firestore:
      implementation 'com.google.firebase:firebase-firestore:24.10.0'
      
    • If you'll use Gson for JSON parsing (recommended):
      implementation 'com.google.code.gson:gson:2.10.1'
      
2. Read the JSON File from Your Android Device

JSON files can be stored in different locations on your device—here are the most common scenarios:

Option A: Read from the Assets Folder

If your JSON file is bundled with your app in the assets directory:

Kotlin

private fun loadJsonFromAssets(context: Context, fileName: String): String? {
    return try {
        val inputStream = context.assets.open(fileName)
        val size = inputStream.available()
        val buffer = ByteArray(size)
        inputStream.read(buffer)
        inputStream.close()
        String(buffer, Charsets.UTF_8)
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}

Java

private String loadJsonFromAssets(Context context, String fileName) {
    try {
        InputStream inputStream = context.getAssets().open(fileName);
        int size = inputStream.available();
        byte[] buffer = new byte[size];
        inputStream.read(buffer);
        inputStream.close();
        return new String(buffer, StandardCharsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Option B: Read from External Storage

If the JSON file is stored in external storage (like Downloads folder), first request storage permissions:

Kotlin (Permission Handling)

// Check and request READ_EXTERNAL_STORAGE permission (Android 12 and below)
val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted ->
    if (isGranted) {
        // Permission granted, proceed to read the file
        val jsonContent = loadJsonFromExternalStorage("/storage/emulated/0/Download/data.json")
        uploadToFirebase(jsonContent)
    } else {
        // Permission denied, show error message
        Toast.makeText(this, "Storage permission required to read the file", Toast.LENGTH_SHORT).show()
    }
}

// Trigger permission request when needed
requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)

// Read file from external storage
private fun loadJsonFromExternalStorage(filePath: String): String? {
    return try {
        val file = File(filePath)
        FileInputStream(file).bufferedReader().use { it.readText() }
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}
3. Upload to Firebase Realtime Database

Once you have the JSON content as a string, upload it to Realtime Database:

Kotlin Example

private fun uploadToRealtimeDatabase(jsonString: String?) {
    jsonString?.let {
        try {
            // Parse JSON string to JSONObject
            val jsonObject = JSONObject(it)
            // Get reference to your database node
            val dbRef = FirebaseDatabase.getInstance().getReference("uploaded_json")
            // Use push() to generate a unique ID for the new entry
            dbRef.push()
                .setValue(jsonObject)
                .addOnSuccessListener {
                    Toast.makeText(this, "JSON uploaded successfully!", Toast.LENGTH_SHORT).show()
                }
                .addOnFailureListener { e ->
                    Toast.makeText(this, "Upload failed: ${e.message}", Toast.LENGTH_SHORT).show()
                }
        } catch (e: JSONException) {
            e.printStackTrace()
            Toast.makeText(this, "Invalid JSON format", Toast.LENGTH_SHORT).show()
        }
    }
}

Alternative: Parse to Map for Flexibility

If you need to modify the JSON data before upload, convert it to a Map using Gson:

val gson = Gson()
val dataMap: Map<String, Any> = gson.fromJson(jsonString, object : TypeToken<Map<String, Any>>() {}.type)
dbRef.push().setValue(dataMap)
4. Upload to Firebase Cloud Firestore

For Firestore (document-based database), the process is similar but uses collections and documents:

Kotlin Example

private fun uploadToFirestore(jsonString: String?) {
    jsonString?.let {
        try {
            val gson = Gson()
            val dataMap: Map<String, Any> = gson.fromJson(it, object : TypeToken<Map<String, Any>>() {}.type)
            // Get reference to your Firestore collection
            val db = FirebaseFirestore.getInstance()
            db.collection("uploaded_json")
                .add(dataMap)
                .addOnSuccessListener { documentReference ->
                    Toast.makeText(this, "Uploaded with ID: ${documentReference.id}", Toast.LENGTH_SHORT).show()
                }
                .addOnFailureListener { e ->
                    Toast.makeText(this, "Upload failed: ${e.message}", Toast.LENGTH_SHORT).show()
                }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "Failed to parse JSON", Toast.LENGTH_SHORT).show()
        }
    }
}
Important Notes
  • Database Security Rules: During development, you can temporarily set open rules for testing:
    {
      "rules": {
        ".read": true,
        ".write": true
      }
    }
    
    For production, replace these with secure rules (e.g., only allow authenticated users to write).
  • File Size Limits: Realtime Database limits single nodes to 10MB, while Firestore limits single documents to 1MB. For larger JSON files, store the file in Firebase Storage and save a reference to it in the database instead.
  • Scoped Storage: On Android 10+, use MediaStore API to access files instead of direct file paths to comply with scoped storage policies.

内容的提问来源于stack exchange,提问作者Amarsaikhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:08:53