尝试写入.json时应用程序崩溃



已编辑

所以我正试图写一个能写入.Json的代码,但我的应用程序一直在崩溃。

我遵循了一些关于该做什么的教程,但没有任何帮助。

我的代码如下:

AndroidManifest:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name = "android.permission.WRITE_INTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

主要活动:

private静态最终字符串FILE_NAME=";MySheet.json";;

public字符串chkFile(上下文上下文({字符串json=null;

try {
InputStream is = context.getAssets().open(FILE_NAME);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
...
protected  void sdBTN(View v, Context context)
{
String txt1 = input1.getText().toString();
String txt2 = input2.toString();
String txt3 = unput3.toString();
JSONObject object = null;
try {
object = new JSONObject(chkFile(this));
} catch (JSONException e) {
e.printStackTrace();
}

try {
object.put("name", text1);
object.put("googleSheet", myGoogleSheet);
object.put("googleScript", myGoogleScript);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);

}

我在assets文件夹中创建了该文件,但该应用程序仍然显示出与我之前的.txt尝试相同的关闭结果。

我遵循教程,但没有帮助。

您应该检查控制台日志输出,以查看问题中包含的实际错误消息。使用Android日志记录类。添加如下格式的日志:

import android.util.Log;
...
private static final String TAG = "MyAppName";
Log.i(TAG, "Some info message such as mkdir: "+file);
if (BuildConfig.DEBUG) {
Log.d(TAG, "Some debug message here");
}

去掉e.printStackTrace()并使用:

Log.e(TAG, "Failed to save:"+file, e);

当您的应用程序从Android Studio启动后运行,并连接到USB上的设备时,请转到Android Studio的Logcat选项卡。Logcat选项卡允许过滤名称-只需键入";MyAppName"然后再次运行测试。

您有'file.mkdir((;'在chkFile((中引用FILE_NAME,该FILE_NAME也传递给openFileOutput(FILE_NAME…(,所以在打开该路径写入文件之前,您可能已经将文件路径创建为目录。

最新更新