Im having a problem saving/ creating a file on my sdcard to save text to, i am trying to check if the file is created and if not create it, then write certain data to it on button click. Here is my code and error output:
This is the error output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds/ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity}: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2187)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ContextImpl.makeFilename(ContextImpl.java:2165)
at android.app.ContextImpl.getFileStreamPath(ContextImpl.java:964)
at android.content.ContextWrapper.getFileStreamPath(ContextWrapper.java:195)
at ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity.onCreate(MainActivity.java:207)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2151)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
and here is the code for the file saving:
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = getFileStreamPath(SDRoot + "/output.txt");
if(!output.exists()){
try {
output.createNewFile();
Context context = getApplicationContext();
CharSequence text = "Output File Created!";
int duration = Toast.LENGTH_LONG;
Toast fileCreated = Toast.makeText(context, text, duration);
fileCreated.show();
} catch (IOException e) {
Context context = getApplicationContext();
CharSequence text = "Output File Not Created!";
int duration = Toast.LENGTH_LONG;
Toast fileNotCreated = Toast.makeText(context, text, duration);
fileNotCreated.show();
e.printStackTrace();
}
}
Button addbutton = (Button)findViewById(R.id.addMeds);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputLine = medOut.toString() + doseOut.getText() + dayout.getText() + timeOut.getText();
try {
FileOutputStream fOut = new FileOutputStream(output);
OutputStreamWriter myOutputStreamWriter = new OutputStreamWriter(fOut);
myOutputStreamWriter.append(outputLine);
myOutputStreamWriter.flush();
myOutputStreamWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
http://developer.android.com/reference/android/content/Context.html#getFileStreamPath(java.lang.String)
Parameters : name The name of the file for which you would like to get its path.
If you give a path (containing "/") instead, it will crash as you have already noticed.
Besides, this function applies only for your application private files, created with openFileOuput for instance.
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
Just do like this :
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = new File(SDRoot + "/output.txt");
Related
I'm trying to create files and write arrray's values on it and I don't have errors in my code most probably there is some exception that i can not see.
Here is my code :
for (int i = 0; i < groups.size(); i++) {
try{
Log.d("a" , "broj grupa " + groups.size());
h = "C" + (i+1) + ".txt" ;
// File root = new File(Environment.getExternalStorageDirectory(), "Notes");
File root = new File(Environment.DIRECTORY_DOWNLOADS +h);
if (!root.exists()) {
root.mkdirs(); // this will create folder.
// root.createNewFile();
}
File filepath = new File(root, h );
FileWriter writer = new FileWriter(filepath);
for(int ii=0 ; ii < groups.get(i).size(); ii++)
{
// System.out.println(groups.get(i).get(ii)+"\n");
String broj = groups.get(i).get(ii).toString();
Log.d("ima li podataka ovamo ", broj);
writer.write(broj);
writer.flush();
}
writer.close();
}
catch(IOException e){
e.toString();
}
}
And Main Activity :
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long [] array = new long[142];
int kkkod;
try {
// OPENING THE REQUIRED TEXT FILE
BufferedReader reader = new BufferedReader(new InputStreamReader(
getAssets().open("renkhex.txt")));
String myLine = reader.readLine();
int i = 0;
while (myLine != null) {
String heksakodbezpraznina = myLine.replaceAll(" ", "");
//Log.d("a da li je to : " , heksakodbezpraznina);
kkkod = Integer.parseInt(heksakodbezpraznina, 16);
// Log.d("to je" , "integer vrednost = " + kkkod);
array[i]= kkkod;
i=i+1;
myLine = reader.readLine();
}
reader.close();
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Error Opening the File !!!", Toast.LENGTH_LONG).show();
}
new KMeans(3,142,array) ;
}
}
Here is my LogCat :
Process: hesh.rtxt, PID: 2119
java.lang.RuntimeException: Unable to start activity ComponentInfo{hesh.rtxt/hesh.rtxt.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at hesh.rtxt.KMeans.<init>(KMeans.java:98)
at hesh.rtxt.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
When I run program it's not stoping, also It writes to much Output to process.
Why am i getting this error??
04-27 16:09:19.823 32255-32255/com.example.myapplication D/AndroidRuntime﹕ Shutting down VM
04-27 16:09:19.823 32255-32255/com.example.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41597db8)
04-27 16:09:19.823 32255-32255/com.example.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 32255
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3830)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3825)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.myapplication.MainActivity.storeImage(MainActivity.java:139)
at com.example.myapplication.MainActivity.save_btn(MainActivity.java:150)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3825)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
What my application does is, opens up the camera application via an intent. Then loads the image/bitmao into an imageview. Whenever i click the save_btn button it gives me this error. Could anybody tell me why and give me a solution? Thank you.
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
private static final String TAG = "MyActivity";
Bitmap image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openCamera();
setContentView(R.layout.activity_main);
findViewById(R.id.captureImage).bringToFront();
findViewById(R.id.saveImage).bringToFront();
imageView = (ImageView) findViewById(R.id.imageView2);
}
protected void onSaveInstanceState(Bundle outState){
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
file.delete();
}
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE) {
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
// Reduce the amount of dynamic heap used by expanding the JPEG into a memory array that's already scaled to match the size of the destination view
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float) height / (float) reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float) width / (float) reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
public void capture_btn(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Pictures/Wiki_Camera"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="camera_wiki"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
public void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
public void save_btn(View v) {
storeImage(image);
}
}
Just guessing but it seems you store taken image only for local variable
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
While later in the code you try to store image from class variable with the same name
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
public void storeImage(Bitmap image) {
imageView.buildDrawingCache();
Bitmap bm_img = imageView.getDrawingCache();
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bm_img.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
I am receiving this fatal Error, when I try to access one particular function zipIt().
It doesn't matter from where I try to access it I always receive this error. This function simply zips a folder but program don't even go inside this function.
Logcat is displayed below:
Process: com.test.shahid, PID: 14839
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5050)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1264)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1080)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5050)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1264)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1080)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
at java.io.FileOutputStream.<init>(FileOutputStream.java:117)
at com.test.shahid.MainActivity.zipIt(MainActivity.java:170)
at com.test.shahid.MainActivity.dispatchTakePictureIntent(MainActivity.java:490)
at com.test.shahid.MainActivity.onClickPhoto(MainActivity.java:468)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5050)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1264)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1080)
at dalvik.system.NativeStart.main(Native Method)
05-23 09:48:22.023 14839-14839/com.test.shahid I/Process﹕ Sending signal. PID: 14839 SIG: 9
Here is the function and variables associated with this function.
private static final File INPUT_FOLDER = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
private static final String ZIPPED_FOLDER = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
protected void zipIt(File inputFolder, String zipFilePath) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
String myname =inputFolder.toString();
ZipEntry folderZipEntry = new ZipEntry(myname);
zipOutputStream.putNextEntry(folderZipEntry);
File[] contents = inputFolder.listFiles();
for (File f : contents) {
if (f.isFile())
zipFile(f, zipOutputStream);
}
zipOutputStream.closeEntry();
zipOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void zipFile(File inputFile, ZipOutputStream zipOutputStream) {
try { // A ZipEntry represents a file entry in the zip archive
// We name the ZipEntry after the original file's name
ZipEntry zipEntry = new ZipEntry(inputFile.getName());
zipOutputStream.putNextEntry(zipEntry);
FileInputStream fileInputStream = new FileInputStream(inputFile);
byte[] buf = new byte[1024];
int bytesRead;
// Read the input file by chucks of 1024 bytes
// and write the read bytes to the zip stream
while ((bytesRead = fileInputStream.read(buf)) > 0) {
zipOutputStream.write(buf, 0, bytesRead);
}
// close ZipEntry to store the stream to the file
zipOutputStream.closeEntry();
System.out.println("Regular file :" + inputFile.getCanonicalPath() + " is zipped to archive :" + ZIPPED_FOLDER);
} catch (IOException e) {
e.printStackTrace();
}
}
Well this is from where i am calling this function. I called this function just to check otherwise i have called this function from button and from several other functions. But nothing works.
public void onSync(View v) throws JSONException, IOException {
zipIt(INPUT_FOLDER, ZIPPED_FOLDER);
if (!isConnected()) {
AlertDialog.Builder mBuilder = new Builder(this);
mBuilder.setMessage("Please Enable Wifi to use this service");
mBuilder.setTitle("Enable WIFI");
mBuilder.setCancelable(false);
mBuilder.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(
Settings.ACTION_WIFI_SETTINGS);
startActivity(i);
}
}
);
mBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// This code might cause problem so check when
// device is available
MainActivity.this.finish();
}
}
);
// create alert dialog
AlertDialog alertDialog = mBuilder.create();
// show it
alertDialog.show();
tvIsConnected.setText("You are NOT conncted");
// Intent myIntent = new
// Intent(Settings.ACTION_WIFI_SETTINGS);
// startActivity(myIntent);
return;
}
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
handler.sendEmptyMessage(MSG_SYNC);
}
NullPointerException
Do you have "WriteExternalStorage" permision in your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Did you check the file path?
Environment.getExternalStorageDirectory() + "/some_foulder/file.txt"
I am getting a Java null pointer exception Unable to start receiver error. I am making an app which receives the push from the parse.com and I am getting the error for Android 4.0.3 - 4.0.4, and also when I restart the some devices..
My LogCat is
**java.lang.RuntimeException: Unable to start receiver com.omega.omegaplus.main.MyCustomReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2419)
at android.app.ActivityThread.access$1500(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1322)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.omega.omegaplus.main.MyCustomReceiver.onReceive(MyCustomReceiver.java:30)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2408)
... 10 more**
My broadcast receiver is
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String message = extras != null ? extras.getString("com.parse.Data")
: "";
Log.e("message ", " " + message);
JSONObject jObject;
try {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
catch (JSONException e) {
e.printStackTrace();
}
}
When I reboot my phone then also it showing same error..., otherwise it is working fine.
I'll have a guess that message has the value of "" or NULL
JSONObject jObject;
try {
if (message != null && !message.equals("") {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
}
catch (JSONException e) {
e.printStackTrace();
}
I fetching audio from soundcloud and i can stream that audio in my app also,Now the things is how to upload audio to soundcloud and then i want to send the id to my server side also.
My requirement is using the upload button i want to get the file from external storage directory and then i want to send the upload audio.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new GinfyDbAdapter(this);
setContentView(R.layout.upload_audiogallery);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
upload = (ImageButton) findViewById(R.id.btnupload);
btnstop = (Button) findViewById(R.id.btnstop);
//Bundle extras = getIntent().getExtras();
token = (Token) this.getIntent().getSerializableExtra("token");
wrapper = new ApiWrapper("3b70c135a3024d709e97af6b0b686ff3",
"51ec6f9c19487160b5942ccd4f642053",
null,
token);
//for speech to text and recording purpose
setButtonHandlers();
enableButtons(false);
mp = new MediaPlayer();
upload .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String rootpath = Environment.getExternalStorageDirectory().getAbsolutePath();
//loadAllAudios(rootpath);
File file = new File("/mnt/sdcard/Download/57FYsUnoWxj2.128.mp3");
String path = file.getAbsolutePath();
new MyAsyncTask().execute(path);
UploadToSoundCloudTask uploadTask = new UploadToSoundCloudTask(this, wrapper);
uploadTask.execute(new AudioClip(path));
}
});
}
private class UploadToSoundCloudTask extends AsyncTask<AudioClip, Integer, Integer> {
private Uploadaudiogallery recordActivity;
private ApiWrapper wrapper;
private String clipName;
public UploadToSoundCloudTask(OnClickListener onClickListener, ApiWrapper wrapper) {
this.recordActivity = (Uploadaudiogallery) onClickListener;
this.wrapper = wrapper;
}
#SuppressLint("NewApi")
protected Integer doInBackground(AudioClip... clips) {
try {
Log.d("DDDDD", "uploading in background...");
File audioFile = new File(clips[0].path);
audioFile.setReadable(true, false);
HttpResponse resp = wrapper.post(Request.to(Endpoints.TRACKS)
.add(Params.Track.TAG_LIST, "demo upload")
.withFile(Params.Track.ASSET_DATA, audioFile));
Log.d("DDDDD", "background thread done...");
return Integer.valueOf(resp.getStatusLine().getStatusCode());
} catch (IOException exp) {
Log.d("DDDDD",
"Error uploading audioclip: IOException: "
+ exp.toString());
return Integer.valueOf(500);
}
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Integer result) {
Log.d("DDDDD", "UI thread resume: got result...");
if (result.intValue() == HttpStatus.SC_CREATED) {
Toast.makeText(
this.recordActivity,
"upload successful: "
+ ": " + clipName, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
this.recordActivity,
"Invalid status received: " + result.toString()
+ ": " + clipName, Toast.LENGTH_SHORT).show();
}
}
}
I used Java api-wrapper jar file also.while click upload its shows applicaiton has stopped
Logcat error
10-25 10:35:27.203: E/AndroidRuntime(1921): FATAL EXCEPTION: main
10-25 10:35:27.203: E/AndroidRuntime(1921): java.lang.ClassCastException: com.ibetter.Ginfy.Uploadaudiogallery$4 cannot be cast to com.ibetter.Ginfy.Uploadaudiogallery
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.ibetter.Ginfy.Uploadaudiogallery$UploadToSoundCloudTask.<init>(Uploadaudiogallery.java:85)
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.ibetter.Ginfy.Uploadaudiogallery$4.onClick(Uploadaudiogallery.java:192)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.view.View.performClick(View.java:4204)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.view.View$PerformClick.run(View.java:17355)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.os.Handler.handleCallback(Handler.java:725)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.os.Handler.dispatchMessage(Handler.java:92)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.os.Looper.loop(Looper.java:137)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-25 10:35:27.203: E/AndroidRuntime(1921): at java.lang.reflect.Method.invokeNative(Native Method)
10-25 10:35:27.203: E/AndroidRuntime(1921): at java.lang.reflect.Method.invoke(Method.java:511)
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-25 10:35:27.203: E/AndroidRuntime(1921): at dalvik.system.NativeStart.main(Native Method)
How can i get the path and uplaod audio to soundcloud and then send id to my server side..
Replace this
UploadToSoundCloudTask uploadTask = new UploadToSoundCloudTask(this, wrapper); uploadTask.execute(new AudioClip(path));
By
UploadToSoundCloudTask uploadTask = new UploadToSoundCloudTask(ActivtiyName.this, wrapper); uploadTask.execute(new AudioClip(path));
In your case this does nto refer to activity context
To upload check the sample here
https://github.com/soundcloud/java-api-wrapper/blob/master/src/examples/java/com/soundcloud/api/examples/UploadFile.java
Downalod java-wrapper-api.jar and add it to libs folder
Get the path of the audio file from sdcard
To uplaod
http://developers.soundcloud.com/docs#uploading
Quoting from the above link
To upload a sound, send a POST request to the /tracks endpoint
Create a wrapper instance:
ApiWrapper wrapper = new ApiWrapper("client_id", "client_secret", null, null);
Obtain a token:
wrapper.login("username", "password");
Make a POST request to the /tracks endpoint. On Button click invoke AsyncTask
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
wrapper = new ApiWrapper("client_id",
"client_secret",
null,
null);
token = wrapper.login("username", "password");
upload();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Upload method.
public void upload()
{
try {
Log.d("DDDDD", "uploading in background...");
File audioFile = new File("/mnt/sdcard/Music/A1.mp3");
// replace the hardcoded path with the path of your audio file
audioFile.setReadable(true, false);
HttpResponse resp = wrapper.post(Request.to(Endpoints.TRACKS)
.add(Params.Track.TITLE, "A1.mp3")
.add(Params.Track.TAG_LIST, "demo upload")
.withFile(Params.Track.ASSET_DATA, audioFile));
Log.i("......",""+Integer.valueOf(resp.getStatusLine().getStatusCode()));
Log.d("DDDDD", "background thread done...");
} catch (IOException exp) {
Log.d("DDDDD",
"Error uploading audioclip: IOException: "
+ exp.toString());
}
}