private String recholder = "not";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/recordingnijez.mp3";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myRecorder.setOutputFile(outputFile);
addListenerButton();
}
private void addListenerButton() {
recbtn = (Button)findViewById(R.id.recbut);
recbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
}
public void start(View view){
if ("recording".equals(recholder)){
try {
myRecorder.stop();
myRecorder.release();
//myRecorder = null;
recbtn.setText(getString(R.string.recBtn));
recholder="not";
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
else{
try {
File file = new File (Environment.getExternalStorageDirectory() + "/recordingnijez.mp3");
if (file.exists()){
file.delete();
myRecorder.prepare();
myRecorder.start();
recholder="recording";
recbtn.setText(getString(R.string.stopBtn));
}
else{
myRecorder.prepare();
myRecorder.start();
recholder="recording";
recbtn.setText(getString(R.string.stopBtn));
}
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
}
it has problem when i try to record twice. i dont know how to fix it i tried everything
heres the logcat
02-12 09:33:50.471: A/libc(1894): Fatal signal 11 (SIGSEGV) at 0x00000010 (code=1), thread 1894 (.example.mixpad)
02-12 09:33:51.191: E/Trace(1961): error opening trace file: No such file or directory (2)
02-12 09:33:51.331: D/dalvikvm(1961): GC_FOR_ALLOC freed 43K, 3% free 8017K/8195K, paused 3ms, total 3ms
02-12 09:33:51.359: I/dalvikvm-heap(1961): Grow heap (frag case) to 10.785MB for 3067212-byte allocation
02-12 09:33:51.379: D/dalvikvm(1961): GC_CONCURRENT freed 1K, 2% free 11011K/11207K, paused 13ms+3ms, total 21ms
02-12 09:33:51.499: D/libEGL(1961): loaded /system/lib/egl/libEGL_emulation.so
02-12 09:33:51.507: D/(1961): HostConnection::get() New Host Connection established 0xb8b8a110, tid 1961
02-12 09:33:51.531: D/libEGL(1961): loaded /system/lib/egl/libGLESv1_CM_emulation.so
02-12 09:33:51.531: D/libEGL(1961): loaded /system/lib/egl/libGLESv2_emulation.so
02-12 09:33:51.611: W/EGL_emulation(1961): eglSurfaceAttrib not implemented
02-12 09:33:51.627: D/OpenGLRenderer(1961): Enabling debug mode 0
02-12 09:33:51.691: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b908e0): name, size, mSize = 1, 1048576, 1048576
02-12 09:33:51.735: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8ba7d10): name, size, mSize = 2, 5184, 1053760
02-12 09:33:51.775: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8bccaf8): name, size, mSize = 4, 20736, 1074496
02-12 09:33:51.839: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b8f730): name, size, mSize = 5, 3067200, 4141696
02-12 09:33:51.867: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8be9798): name, size, mSize = 6, 7488, 4149184
02-12 09:33:51.871: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b88ff0): name, size, mSize = 7, 40984, 4190168
02-12 09:33:51.875: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b8f7c0): name, size, mSize = 8, 37412, 4227580
02-12 09:33:51.883: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8ba8b60): name, size, mSize = 9, 33276, 4260856
02-12 09:33:51.887: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b9c0d8): name, size, mSize = 10, 32712, 4293568
02-12 09:33:51.891: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b8b840): name, size, mSize = 11, 2304, 4295872
I meet this problem too, please use myRecorder=null, I think that because myRecorder.release() has bug,
you can do that:
myRecorder.stop();
myRecorder.release();
myRecorder = null;
and other place append judgement
if(myRecorder != null){ ... }
Try adding this:
mediaRecorder.stop();
mediaRecorder.reset(); //instead of release() and =null
And then in
public void onStop() {
mediaRecorder.release();
mediaRecorder = null;
I have this...
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
... and works fine!
Try calling super first in your onCreate :
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Related
My app gets data from a PHP file. 3 normal textdata and 5 image urls. The app displays them in a recyclerview with cardviews.
My problem is, that the app crashes when getting empty image urls.
But with empty textdata the app works without problems.
Like:
textdata with content + image urls with content = works
Empty textdata + empty image urls = App crashes
Empty textdata + image urls with content = works
textdata with content + empty image urls = App crashes
This is the getting and sending (to RecyclerviewAdapter) Code:
public void JSON_DATA_WEB_CALL (String url){
jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(solutionTemplate.this, GetDataAdapter1, exerciseAdapter);
recyclerView.setAdapter(recyclerViewadapter);
}
The mainproblem is:
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
Working:
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
Not working:
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
Getting image urls with content is necassary!
But it should work without it!
This is the GetDataAdapter:
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number1) {
this.phone_number = phone_number1;
}
public String getSubject2() {
return subject2;
}
public void setSubject2(String subject2) {
this.subject2 = subject2;
}
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageUrl2() {
return ImageURL2;
}
public void setImageUrl2(String imageServerUrl2) {
this.ImageURL2 = imageServerUrl2;
}
public String getImageUrl3() {
return ImageURL3;
}
public void setImageUrl3(String imageServerUrl3) {
this.ImageURL3 = imageServerUrl3;
}
public String getImageUrl4() {
return ImageURL4;
}
public void setImageUrl4(String imageServerUrl4) {
this.ImageURL4 = imageServerUrl4;
}
public String getImageUrl5() {
return ImageURL5;
}
public void setImageUrl5(String imageServerUrl5) {
this.ImageURL5 = imageServerUrl5;
}
RecyclerViewAdapter:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
final GetDataAdapter current = getItem(position - 1);
final ViewHolder holder1 = (ViewHolder) holder;
final ImageLoader imageLoader = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader2 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader3 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader4 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader5 = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(current.getImageUrl(),
ImageLoader.getImageListener(
holder1.imageView1,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader2.get(current.getImageUrl2(),
ImageLoader.getImageListener(
holder1.imageView2,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader3.get(current.getImageUrl3(),
ImageLoader.getImageListener(
holder1.imageView3,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader4.get(current.getImageUrl4(),
ImageLoader.getImageListener(
holder1.imageView4,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader5.get(current.getImageUrl5(),
ImageLoader.getImageListener(
holder1.imageView5,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
holder1.imageView1.setImageUrl(current.getImageUrl(), imageLoader);
holder1.imageView2.setImageUrl(current.getImageUrl2(), imageLoader2);
holder1.imageView3.setImageUrl(current.getImageUrl3(), imageLoader3);
holder1.imageView4.setImageUrl(current.getImageUrl4(), imageLoader4);
holder1.imageView5.setImageUrl(current.getImageUrl5(), imageLoader5);
holder1.NameTextView.setText(current.getName());
holder1.PhoneNumberTextView.setText(current.getPhone_number());
holder1.SubjectTextView.setText(current.getSubject2());
ImageAdapter:
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
PHP:
<?php
$conn = mysqli_connect('localhost', 'root', '','webapp');
$id = $_GET['id'];
$sql = "SELECT * FROM answers WHERE id='$id' ORDER BY id DESC";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array(
'url2'=>$row['images'],
'url3'=>$row['images2'],
'url4'=>$row['images3'],
'url5'=>$row['images4'],
'url6'=>$row['images5'],
'subject'=>$row['subject'],
'phone'=>$row['phone'],
'name'=>$row['name']));
}
echo json_encode(array_values($result));
mysqli_close($conn);
?>
If PHP sends url2, url3, url4... without content the app chrashes, but phone, name, subject with empty values works without problems.
I think Android has a Problem with converting empty imageurls and with displaying it.
EDIT:
A lot of users said that I have to add the Logcat:
07-16 13:12:10.713 1578-1990/system_process W/ActivityManager: Force finishing activity com.example.jakob.webapplicationsave/.solutionTemplate
07-16 13:12:10.822 1578-1990/system_process W/ActivityManager: Force finishing activity com.example.jakob.webapplicationsave/.Main2Activity
07-16 13:12:10.946 1578-2630/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
07-16 13:12:10.947 1578-2630/system_process D/EGL_emulation: eglCreateContext: 0x9c2be040: maj 2 min 0 rcv 2
07-16 13:12:10.953 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:10.962 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:11.323 1578-1592/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{e46f507 u0 com.example.jakob.webapplicationsave/.solutionTemplate t497 f}
07-16 13:12:11.372 1930-2076/com.android.launcher3 I/OpenGLRenderer: Initialized EGL, version 1.4
07-16 13:12:11.374 1930-2076/com.android.launcher3 D/EGL_emulation: eglCreateContext: 0xae414660: maj 2 min 0 rcv 2
07-16 13:12:11.385 1930-2076/com.android.launcher3 D/EGL_emulation: eglMakeCurrent: 0xae414660: ver 2 0 (tinfo 0xae412440)
07-16 13:12:11.423 1930-2076/com.android.launcher3 D/EGL_emulation: eglMakeCurrent: 0xae414660: ver 2 0 (tinfo 0xae412440)
07-16 13:12:13.537 1270-1616/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 38006369 , only wrote 37870012
07-16 13:12:14.795 13519-13519/com.example.jakob.webapplicationsave I/Process: Sending signal. PID: 13519 SIG: 9
07-16 13:12:14.814 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:14.815 1578-2630/system_process E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9b6834a0
07-16 13:12:14.830 1578-2182/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
07-16 13:12:14.830 1578-2182/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 13519 uid 10062
07-16 13:12:14.833 1578-2182/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
07-16 13:12:14.847 1578-1713/system_process D/GraphicsStats: Buffer count: 5
07-16 13:12:14.847 1578-1625/system_process W/InputDispatcher: channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
07-16 13:12:14.847 1578-2182/system_process I/WindowState: WIN DEATH: Window{7af27b1 u0 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity}
07-16 13:12:14.847 1578-1625/system_process E/InputDispatcher: channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
07-16 13:12:14.847 1578-1625/system_process W/InputDispatcher: channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)' ~ Consumer closed input channel or an error occurred. events=0x9
07-16 13:12:14.847 1578-1625/system_process E/InputDispatcher: channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)' ~ Channel is unrecoverably broken and will be disposed!
07-16 13:12:14.847 1578-2182/system_process W/InputDispatcher: Attempted to unregister already unregistered input channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)'
07-16 13:12:14.848 1578-2179/system_process I/WindowState: WIN DEATH: Window{cd3daa3 u0 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate}
07-16 13:12:14.848 1578-2179/system_process W/InputDispatcher: Attempted to unregister already unregistered input channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)'
07-16 13:12:14.853 1259-1259/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
07-16 13:12:14.853 1578-1963/system_process I/ActivityManager: Process com.example.jakob.webapplicationsave (pid 13519) has died
07-16 13:12:15.026 1578-1597/system_process W/AppOps: Finishing op nesting under-run: uid 1000 pkg android code 24 time=0 duration=0 nesting=0
07-16 13:12:17.958 1270-1616/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 38145850 , only wrote 38008822
07-16 13:13:00.065 1259-1351/? D/hwcomposer: hw_composer sent 312 syncs in 60s
07-16 13:14:00.056 1259-1351/? D/hwcomposer: hw_composer sent 5 syncs in 60s
I tried to translate this C/C++ code to Java for Android. http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/sobel_derivatives/sobel_derivatives.html#sobel-derivatives
Unfortunately, it doesn't work.
My code:`public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
if (status == LoaderCallbackInterface.SUCCESS ) {
// now we can call opencv code !
try {
krawedz();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("moje", "brak obrazka");
e.printStackTrace();
}
} else {
super.onManagerConnected(status);
}
}
};
#Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5,this, mLoaderCallback);
}
public void krawedz() throws IOException{
Mat src, src_gray = null;
Mat grad_x = null, grad_y = null;
Mat abs_grad_x = null, abs_grad_y = null;
Mat grad = null;
int skala = 1;
int delta = 0;
int depth = 3; //CV16_S
//zaĆaduj obrazek
src = Utils.loadResource(this, R.drawable.obraz);
if(src.empty()){
Log.e("moje", "brak obrazka");
}
//na szaro
Imgproc.GaussianBlur(src, src_gray, new org.opencv.core.Size(3,3), 0, 0);
Imgproc.cvtColor(src, src_gray, 7 ); //7=CV_RGB2GRAY
//Gradient x
//Imgproc.Scharr(src_gray, grad_x, depth, 1, 0, skala, delta, Imgproc.BORDER_DEFAULT);
Imgproc.Sobel(src_gray, grad_x, depth, 1, 0, 3, skala, delta, Imgproc.BORDER_DEFAULT);
Core.convertScaleAbs(grad_x, abs_grad_x);
//Gradient Y
//Imgproc.Scharr(src_gray, grad_y, depth, 0, 1, skala, delta, Imgproc.BORDER_DEFAULT);
Imgproc.Sobel(src_gray, grad_y, depth, 0, 1, 3, skala, delta, Imgproc.BORDER_DEFAULT);
Core.convertScaleAbs(grad_y, abs_grad_y);
Core.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
// zamiana macierzy na bitmape:
Bitmap bm = Bitmap.createBitmap(grad.cols(), grad.rows(),Bitmap.Config.ARGB_8888);
Utils.matToBitmap(grad, bm);
// rysowanie bitmapy
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(bm);
}
}`
What LogCat thinks about this code:
03-14 16:45:52.944: E/AndroidRuntime(25349): FATAL EXCEPTION: main
03-14 16:45:52.944: E/AndroidRuntime(25349): Process: com.example.wykrywanie_krawedzi, PID: 25349
03-14 16:45:52.944: E/AndroidRuntime(25349): java.lang.NullPointerException
03-14 16:45:52.944: E/AndroidRuntime(25349): at org.opencv.imgproc.Imgproc.GaussianBlur(Imgproc.java:533)
03-14 16:45:52.944: E/AndroidRuntime(25349): at com.example.wykrywanie_krawedzi.MainActivity.krawedz(MainActivity.java:73)
03-14 16:45:52.944: E/AndroidRuntime(25349): at com.example.wykrywanie_krawedzi.MainActivity$1.onManagerConnected(MainActivity.java:38)
03-14 16:45:52.944: E/AndroidRuntime(25349): at org.opencv.android.AsyncServiceHelper$1.onServiceConnected(AsyncServiceHelper.java:318)
03-14 16:45:52.944: E/AndroidRuntime(25349): at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1110)
03-14 16:45:52.944: E/AndroidRuntime(25349): at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1127)
03-14 16:45:52.944: E/AndroidRuntime(25349): at android.os.Handler.handleCallback(Handler.java:733)
03-14 16:45:52.944: E/AndroidRuntime(25349): at android.os.Handler.dispatchMessage(Handler.java:95)
03-14 16:45:52.944: E/AndroidRuntime(25349): at android.os.Looper.loop(Looper.java:136)
03-14 16:45:52.944: E/AndroidRuntime(25349): at android.app.ActivityThread.main(ActivityThread.java:5086)
03-14 16:45:52.944: E/AndroidRuntime(25349): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 16:45:52.944: E/AndroidRuntime(25349): at java.lang.reflect.Method.invoke(Method.java:515)
03-14 16:45:52.944: E/AndroidRuntime(25349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
03-14 16:45:52.944: E/AndroidRuntime(25349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
03-14 16:45:52.944: E/AndroidRuntime(25349): at dalvik.system.NativeStart.main(Native Method)
replace
grad_x = null, grad_y = null, abs_grad_x = null, abs_grad_y = null, grad = null
by
grad_x = new Mat(), grad_y = new Mat(), abs_grad_x = new Mat(), abs_grad_y = new Mat(), grad = new Mat();
My app contains MainActivity class and several fragments.
One of the is the registration fragment which I want it to be able tho interact with my database which should contain only one table named USERS to whom I will CRUD.
I've opened the MySQLiteOpenHelper class that extends SQLiteOpenHelper and created a User class as well.
I've declared:
MySQLiteOpenHelper db = new MySQLiteOpenHelper(this);
in the activity's onCreate method.
My question is how do I interact with this db from the fragments?
I've tried the following code but it didn't work:
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class registration extends Fragment {
public registration() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.registration, container,
false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
final EditText etFirstName = (EditText) getActivity().findViewById(
R.id.etFirstName);
final EditText etLastName = (EditText) getActivity().findViewById(
R.id.etLastName);
final EditText etEmail = (EditText) getActivity().findViewById(
R.id.etEmail);
final EditText etUsername = (EditText) getActivity().findViewById(
R.id.etUsername);
final EditText etPassword = (EditText) getActivity().findViewById(
R.id.etPassword);
Button bDone = (Button) getActivity().findViewById(R.id.bDone);
bDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);//do I need this??
db.addUser(new User(etFirstName.getText().toString(),
etLastName.getText().toString(), etEmail.getText()
.toString(), etUsername.getText().toString(),
etPassword.getText().toString()));
}
});
}
}
What happens now is that the moment I click the DONE button the app crushes...
Thank's!!
MySQLiteOpenHelper looks like this:
import java.util.LinkedList;
import java.util.List;
import android.R.string;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="MyDB";
private static final String TABLE_USERS="USERS";
private static final String FIRST_NAME="First_name";
private static final String LAST_NAME="Last_name";
private static final String EMAIL="Email";
private static final String USERNAME="Username";
private static final String PASSWORD="Password";
private static final String COLUMNS[]={FIRST_NAME, LAST_NAME, EMAIL, USERNAME, PASSWORD};
public MySQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_MyDB_TABLE = "CREATE TABLE USERS ( " +
"First_name TEXT, " +
"Last_name TEXT, "+
"Email KEY TEXT NOT NULL, "+
"Username TEXT NOT NULL, "+
"Password TEXT NOT NULL)";
db.execSQL(CREATE_MyDB_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS USERS");
this.onCreate(db);
}
public void addUser(User user){
Log.d("addUser", user.toString());
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(FIRST_NAME, user.getFirstName());
values.put(LAST_NAME, user.getLastName());
values.put(EMAIL, user.getEmail());
values.put(USERNAME, user.getUsername());
values.put(PASSWORD, user.getPassword());
db.insert(TABLE_USERS, null, values);
db.close();
}
public User getUser(String Email){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=
db.query(TABLE_USERS, COLUMNS, "Email =?", new String[] {String.valueOf(Email)}, null, null, null);
if (cursor != null)
cursor.moveToFirst();
User user=new User();
user.setFirstName(cursor.getString(0));
user.setLastName(cursor.getString(1));
user.setEmail(cursor.getString(2));
user.setUsername(cursor.getString(3));
user.setPassword(cursor.getString(4));
Log.d("getUser ("+Email+")", user.toString());
return user;
}
public List<User> getAllUsers(){
List<User> users=new LinkedList<User>();
String query="SELECT * FROM "+TABLE_USERS;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query, null);
User user=null;
if (cursor.moveToFirst()){
do{
user=new User();
user.setFirstName(cursor.getString(0));
user.setLastName(cursor.getString(1));
user.setEmail(cursor.getString(2));
user.setUsername(cursor.getString(3));
user.setPassword(cursor.getString(4));
users.add(user);
} while (cursor.moveToNext());
}
Log.d("getAllUsers", users.toString());
return users;
}
public int updateUser(User user){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(FIRST_NAME, user.getFirstName());
values.put(LAST_NAME, user.getLastName());
values.put(EMAIL, user.getEmail());
values.put(USERNAME, user.getUsername());
values.put(PASSWORD, user.getPassword());
int i=db.update(TABLE_USERS, values, "Email =?", new String[]{String.valueOf(user.getEmail())});
db.close();
return i;
}
public void deleteUser(User user){
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_USERS, "Email =?", new String[]{String.valueOf(user.getEmail())});
db.close();
Log.d("deleteUser", user.toString());
}
}
LogCat:
04-18 12:16:09.132: E/Trace(1051): error opening trace file: No such file or directory (2)
04-18 12:16:09.404: D/libEGL(1051): loaded /system/lib/egl/libEGL_emulation.so
04-18 12:16:09.416: D/(1051): HostConnection::get() New Host Connection established 0xb9324060, tid 1051
04-18 12:16:09.492: D/libEGL(1051): loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-18 12:16:09.492: D/libEGL(1051): loaded /system/lib/egl/libGLESv2_emulation.so
04-18 12:16:09.672: W/EGL_emulation(1051): eglSurfaceAttrib not implemented
04-18 12:16:09.708: D/OpenGLRenderer(1051): Enabling debug mode 0
04-18 12:16:09.800: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb931a8e0): name, size, mSize = 1, 1048576, 1048576
04-18 12:16:09.960: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9331d10): name, size, mSize = 2, 5184, 1053760
04-18 12:16:10.068: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9309b60): name, size, mSize = 4, 20736, 1074496
04-18 12:16:10.072: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb932d4b8): name, size, mSize = 5, 9216, 1083712
04-18 12:16:10.140: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9312810): name, size, mSize = 7, 7488, 1091200
04-18 12:16:10.152: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9325d70): name, size, mSize = 8, 100, 1091300
04-18 12:16:10.212: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb93176a0): name, size, mSize = 10, 7488, 1098788
04-18 12:16:10.252: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9373798): name, size, mSize = 11, 7488, 1106276
04-18 12:16:10.336: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9315840): name, size, mSize = 12, 2304, 1108580
04-18 12:16:42.528: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9378b38): name, size, mSize = 78, 7488, 1116068
04-18 12:16:42.800: D/dalvikvm(1051): GC_CONCURRENT freed 142K, 3% free 8216K/8391K, paused 14ms+0ms, total 25ms
04-18 12:16:44.200: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9308998): name, size, mSize = 85, 7488, 1123556
04-18 12:16:44.216: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9316848): name, size, mSize = 86, 7488, 1131044
04-18 12:16:53.192: D/addUser(1051): First name: dsfLast name: dsfdsfEmail: dsfdsfUsername: Password:
04-18 12:16:53.196: D/AndroidRuntime(1051): Shutting down VM
04-18 12:16:53.196: W/dalvikvm(1051): threadid=1: thread exiting with uncaught exception (group=0xa627b288)
04-18 12:16:53.200: E/AndroidRuntime(1051): FATAL EXCEPTION: main
04-18 12:16:53.200: E/AndroidRuntime(1051): java.lang.NullPointerException
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.craftyonhand.www.MySQLiteOpenHelper.addUser(MySQLiteOpenHelper.java:60)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.craftyonhand.www.registration$1.onClick(registration.java:47)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.view.View.performClick(View.java:4084)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.view.View$PerformClick.run(View.java:16966)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.os.Handler.handleCallback(Handler.java:615)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.os.Handler.dispatchMessage(Handler.java:92)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.os.Looper.loop(Looper.java:137)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.app.ActivityThread.main(ActivityThread.java:4745)
04-18 12:16:53.200: E/AndroidRuntime(1051): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 12:16:53.200: E/AndroidRuntime(1051): at java.lang.reflect.Method.invoke(Method.java:511)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-18 12:16:53.200: E/AndroidRuntime(1051): at dalvik.system.NativeStart.main(Native Method)
04-18 12:16:55.792: I/Process(1051): Sending signal. PID: 1051 SIG: 9
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);//do I need this??
Yes you need it and you also need to pass a non-null valid Context as an argument. In a fragment, you can use getActivity() to get the activity to use as a Contextonce the fragment is attached to its host activity.
Okay so it does show on logcat but for some reason it says that there is no such table USERS... As far as I know it should open it if it does not exsits. Am I wrong?
Possibly you have an older version of the database file around. Clear app data or uninstall it to remove it and make the database helper onCreate() create set up the tables for you. See When is SQLiteOpenHelper onCreate() / onUpgrade() run?
for more.
You should change this
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);//do I need this??
With
MySQLiteOpenHelper db = new MySQLiteOpenHelper(getActivity());//do I need this??
Replace
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);
with
MySQLiteOpenHelper db = new MySQLiteOpenHelper(getActivity());
Update onUpgrade() method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String CREATE_MyDB_TABLE = "CREATE TABLE IF NOT EXISTS USERS ( " +
"First_name TEXT, " +
"Last_name TEXT, "+
"Email KEY TEXT NOT NULL, "+
"Username TEXT NOT NULL, "+
"Password TEXT NOT NULL)";
db.execSQL(CREATE_MyDB_TABLE);
this.onCreate(db);
}
I'am using the following code from the tutorial :
http://geekonjava.blogspot.in/2014/03/upload-image-on-server-in-android-using.html
Whenever I run the code , it shows the following error on log cat and force closes the app on click of Upload Button. Can anyone help me on this ?
03-30 09:00:35.026: E/Trace(1086): error opening trace file: No such file or directory (2)
03-30 09:00:35.238: D/libEGL(1086): loaded /system/lib/egl/libEGL_emulation.so
03-30 09:00:35.242: D/(1086): HostConnection::get() New Host Connection established 0xb85a7800, tid 1086
03-30 09:00:35.646: D/libEGL(1086): loaded /system/lib/egl/libGLESv1_CM_emulation.so
03-30 09:00:35.650: D/libEGL(1086): loaded /system/lib/egl/libGLESv2_emulation.so
03-30 09:00:37.062: W/EGL_emulation(1086): eglSurfaceAttrib not implemented
03-30 09:00:37.106: D/OpenGLRenderer(1086): Enabling debug mode 0
03-30 09:00:37.158: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8550e18): name, size, mSize = 1, 1048576, 1048576
03-30 09:00:38.226: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8562e40): name, size, mSize = 2, 2304, 1050880
03-30 09:00:38.386: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb85555a0): name, size, mSize = 4, 9216, 1060096
03-30 09:00:38.398: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb858bd48): name, size, mSize = 5, 3328, 1063424
03-30 09:00:38.486: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8539dd0): name, size, mSize = 7, 1024, 1064448
03-30 09:00:43.450: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8577238): name, size, mSize = 9, 3328, 1067776
03-30 09:00:43.898: W/dalvikvm(1086): threadid=10: thread exiting with uncaught exception (group=0xa62e3288)
03-30 09:00:43.898: E/AndroidRuntime(1086): FATAL EXCEPTION: Thread-95
03-30 09:00:43.898: E/AndroidRuntime(1086): java.lang.NullPointerException
03-30 09:00:43.898: E/AndroidRuntime(1086): at java.io.File.fixSlashes(File.java:185)
03-30 09:00:43.898: E/AndroidRuntime(1086): at java.io.File.<init>(File.java:134)
03-30 09:00:43.898: E/AndroidRuntime(1086): at com.sunil.upload.MainActivity.uploadFile(MainActivity.java:115)
03-30 09:00:43.898: E/AndroidRuntime(1086): at com.sunil.upload.MainActivity$1.run(MainActivity.java:72)
03-30 09:00:43.898: E/AndroidRuntime(1086): at java.lang.Thread.run(Thread.java:856)
03-30 09:00:44.050: W/EGL_emulation(1086): eglSurfaceAttrib not implemented
03-30 09:00:44.230: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8558c50): name, size, mSize = 12, 15360, 1083136
03-30 09:00:44.242: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8551420): name, size, mSize = 13, 9216, 1092352
03-30 09:00:44.294: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8551880): name, size, mSize = 14, 9216, 1101568
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::flush: target size: 660940
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::callback: name, removed size, mSize = 9, 3328, 1098240
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::callback: name, removed size, mSize = 1, 1048576, 49664
03-30 09:00:45.634: E/WindowManager(1086): Activity com.sunil.upload.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#53473594 that was originally added here
03-30 09:00:45.634: E/WindowManager(1086): android.view.WindowLeaked: Activity com.sunil.upload.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#53473594 that was originally added here
03-30 09:00:45.634: E/WindowManager(1086): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.Window$LocalWindowManager.addView(Window.java:547)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.Dialog.show(Dialog.java:277)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.ProgressDialog.show(ProgressDialog.java:116)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.ProgressDialog.show(ProgressDialog.java:99)
03-30 09:00:45.634: E/WindowManager(1086): at com.sunil.upload.MainActivity.onClick(MainActivity.java:67)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.View.performClick(View.java:4084)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.View$PerformClick.run(View.java:16966)
03-30 09:00:45.634: E/WindowManager(1086): at android.os.Handler.handleCallback(Handler.java:615)
03-30 09:00:45.634: E/WindowManager(1086): at android.os.Handler.dispatchMessage(Handler.java:92)
03-30 09:00:45.634: E/WindowManager(1086): at android.os.Looper.loop(Looper.java:137)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-30 09:00:45.634: E/WindowManager(1086): at java.lang.reflect.Method.invokeNative(Native Method)
03-30 09:00:45.634: E/WindowManager(1086): at java.lang.reflect.Method.invoke(Method.java:511)
03-30 09:00:45.634: E/WindowManager(1086): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-30 09:00:45.634: E/WindowManager(1086): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-30 09:00:45.634: E/WindowManager(1086): at dalvik.system.NativeStart.main(Native Method)
03-30 09:00:45.906: I/Process(1086): Sending signal. PID: 1086 SIG: 9
Code:
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://localhost/UploadFile.php";
ImageView img= new ImageView(this);
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
UploadFile.php :
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
Check your logs : you have NullPonterException in line :
File sourceFile = new File(sourceFileUri); // your sourceFileUri = null here,
since you call uploadFile() with null agrument.
I have two seperate startActivityForResults which utilize different activities. I want to be able to handle the results of these activity all in my main activity.
However, when returning to the main activity, the function is performed (e.g. in the case of requestCodeText the text on btn3 is set to the right value) but then the app freezes.
Here is my code:
final int request_CodeNumber = 1;
final int request_CodeText = 2;
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case request_CodeText:
Uri uri = data.getData();
final Button btn3 = (Button)findViewById(R.id.btnMessage);
if(resultCode == RESULT_OK) {
btn3.setText((String) uri.toString());
}
break;
case request_CodeNumber:
Uri uri2 = data.getData();
Cursor c = null;
try {
c = getContentResolver().query(uri2, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
null, null, null);
if (c!= null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
String contactName = c.getString(2);
showSelectedNumber(type, number, contactName);
}
} finally {
if (c != null) {
c.close();
}
}
break;
}
}
I get the following in the logcat:
11-20 21:52:45.155: D/dalvikvm(655): GC_FOR_ALLOC freed 66K, 4% free 8004K/8259K, paused 85ms, total 97ms
11-20 21:52:45.215: I/dalvikvm-heap(655): Grow heap (frag case) to 10.633MB for 2903056-byte allocation
11-20 21:52:45.485: D/dalvikvm(655): GC_CONCURRENT freed <1K, 3% free 10838K/11143K, paused 122ms+20ms, total 273ms
11-20 21:52:47.055: D/libEGL(655): loaded /system/lib/egl/libEGL_emulation.so
11-20 21:52:47.076: D/(655): HostConnection::get() New Host Connection established 0x2a0d7d68, tid 655
11-20 21:52:47.218: D/libEGL(655): loaded /system/lib/egl/libGLESv1_CM_emulation.so
11-20 21:52:47.236: D/libEGL(655): loaded /system/lib/egl/libGLESv2_emulation.so
11-20 21:52:47.425: W/EGL_emulation(655): eglSurfaceAttrib not implemented
11-20 21:52:47.476: D/OpenGLRenderer(655): Enabling debug mode 0
11-20 21:52:54.076: W/EGL_emulation(655): eglSurfaceAttrib not implemented
11-20 21:52:59.646: W/EGL_emulation(655): eglSurfaceAttrib not implemented