App just forcecloses and stops working, why? - java

I'm a newbie android developer and I am making, or trying to make a File explorer that wil be capable of opening almost all file types. From music files, through video files, document files and many others. BUT, I came across a huge problem that my app compiled successfully but it does not open. Here is my code:
package com.tstudios.openit;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
String filename = f.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
TextView row=(TextView)findViewById(R.id.rowtext);
//if(extension=="jpg"){
//mImageView.setImageBitmap(BitmapFactory.decodeFile(dirPath));
//}
//if(extension!=null){
//row.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher,0,0,0);
//}
Arrays.sort(files, filecomparator);
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
Comparator<? super File> filecomparator = new Comparator<File>(){
public int compare(File file1, File file2) {
if(file1.isDirectory()){
if (file2.isDirectory()){
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}else{
return -1;
}
}else {
if (file2.isDirectory()){
return 1;
}else{
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}
}
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File file = new File(path.get(position));
String filename = file.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
if (file.isDirectory())
{
if(extension=="jpg"){
mImageView.setImageBitmap(BitmapFactory.decodeFile(filename));
getDir(path.get(position));
}else{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK", null).show();
}
}
}
and this is logcat I get when I lauch the app, btw I am using Sony Xperia Z1 Compact if that helps
08-28 12:10:54.779 4169-4169/com.tstudios.openit D/AndroidRuntime﹕ Shutting down VM
08-28 12:10:54.779 4169-4169/com.tstudios.openit W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4164cd88)
08-28 12:10:54.789 4169-4169/com.tstudios.openit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tstudios.openit, PID: 4169
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.tstudios.openit/com.tstudios.openit.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at com.tstudios.openit.MainActivity.<init>(MainActivity.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:212)
            at android.app.ActivityThread.main(ActivityThread.java:5135)
            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:877)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
         at dalvik.system.NativeStart.main(Native Method)
And another question, how to put icons before file names ? Depending on extension
Thank you very much for your help

Move the
mImageView=(ImageView) findViewById(R.id.gallery);
to onCreate() after setContentView(), leaving just the member variable declaration at the class level:
private ImageView mImageView;
Before onCreate() there's no window yet for the activity and you'll get the NPE.
Before setContentView() there's no view hierarchy to search from and a null is returned.

private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
to use findViewById you need a valid Activity. It happens after the activity has been attached

Place this line private ImageView mImageView=(ImageView) findViewById(R.id.gallery); after setContentView . It will resolve null pointer exception. After this, if you get any other exception, Pls tell.

Related

An Error occurs when I was making a code to create a show list by ListView{in content_main.xml} like contact view

I was making a code to create a show list by ListView{in content_main.xml} like contact view.
I build a database in the (SQLite Expert Professional) with a table(name: "contact") that was contained a few name and family and numbers, with ID,NAME,fAMILY and PHONE NUMBER columns.
ID was unique, auto increment and primary key...other were Text except number that was CHAR.
then I calling them to my ListView as you see in below.(before it I made a row_list activity to made my listview , custom) but there was an Error and I can't find it.
{I could find my database.db file with that's table in the source data files that means my mistake wasn't from creating database.}
plz help me.I wanna learn android (as fast as i can) to get a JOB and I need it..
Errors.Android Monitor.Logcat
09-08 05:27:32.005 5692-5692/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x94c4fb20)
09-08 05:27:32.005 5692-5692/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: mizco.phonebook, PID: 5692
java.lang.RuntimeException: Unable to start activity ComponentInfo{mizco.phonebook/mizco.phonebook.Main}: android.database
.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
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:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at mizco.phonebook.database.getfulllist(database.java:97)
at mizco.phonebook.Main.onCreate(Main.java:36)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
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:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Main.java
package mizco.phonebook;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends AppCompatActivity {
private database db;
private String [][] res ;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = (ListView) findViewById(R.id.main_list);
db = new database(this);
db.startusing();
db.open();
res = db.getfulllist();
db.close();
list.setAdapter(new AA());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
class AA extends ArrayAdapter<String>{
public AA() {
super(Main.this, R.layout.row_list, res[0]);
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater in = getLayoutInflater();
View row = in.inflate(R.layout.row_list,parent,false);
TextView name = (TextView) row.findViewById(R.id.row_name);
TextView number = (TextView) row.findViewById(R.id.row_number);
name.setText(res[0][position]+" "+res[1][position]);
number.setText(res[2][position]);
return row;
}
}
}
Class : database.java
package mizco.phonebook;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Mahdi on 9/2/2017.
*/
public class database extends SQLiteOpenHelper {
public static String dbname= "database";
public static String dbpath="";
private Context mctxt;
private SQLiteDatabase mydb;
public database(Context context) {
super(context, dbname, null, 1);
mctxt = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private boolean existdatabase(){
File m312 = new File(dbpath+dbname);
return m312.exists();
}
private void copydatabase(){
try {
InputStream IS = mctxt.getAssets().open(dbname);
OutputStream OS = new FileOutputStream(dbpath+dbname);
byte[] buffer = new byte[1024];
int length;
while ((length = IS.read(buffer))>0){
OS.write(buffer,0,length);
}
OS.flush();
OS.close();
IS.close();
} catch (Exception e) {
}
}
public void open(){
mydb = SQLiteDatabase.openDatabase(dbpath+dbname, null, SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
mydb.close();
}
public void startusing () {
dbpath = mctxt.getFilesDir().getParent() + "/databases/";
if (!existdatabase()) {
this.getWritableDatabase();
copydatabase();
}
}
public String[][] getfulllist(){
Cursor cu = mydb.rawQuery("select * from Contact",null);
String [][] r = new String[3][cu.getCount()];
for (int i= 0;i<=cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;
}
}
You're stepping off the end of the cursor. Your code should read
for (int i= 0;i < cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;

Check File Extension in android

i made a small method to check whether defined folder has files with a specific extension or not. I m getting null point exception on run.pls help to find mistake.method is checking .mp4 files and returning true if found and message is displayed.
Here is Code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView filecheck;
filecheck = (TextView) findViewById(R.id.filecheck);
filecheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (accept()) {
Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean accept() {
final File pathname = new File("/sdcard/test/");
String files[] = pathname.list();
System.out.println(files.length);
for (String s : files) {
if (s.contains(".mp4")) {
System.out.println(s);
return true;
}
return false;
}
return false;
}
}
Here is exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: jss.testmethods, PID: 23659
java.lang.NullPointerException
at jss.testmethods.MainActivity.accept(MainActivity.java:38)
at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24)
at android.view.View.performClick(View.java:4478)
at android.view.View$PerformClick.run(View.java:18698)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
i was expecting simple error, i missed to add permission for read storage. it is working now.

Android- Null pointer exception from getStringExtra using intent send a value to another activity by button click

I am facing the problem when I use Intent to send a value to another activity by click a button. I have tried to solve it in many ways but it always show NullPointerException although I declared it clearly.
Here is my code.
Manufacturer.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Manufacturer extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manufacturer);
Button toyota = (Button) findViewById(R.id.Toyota);
Button subaru = (Button) findViewById(R.id.Subaru);
Button audi = (Button) findViewById(R.id.Audi);
toyota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Toyota";
goAnother(message.toString());
}
});
subaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Subaru";
goAnother(message);
}
});
audi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Audi";
goAnother(message);
}
});
}
protected void goAnother(String brand){
Intent i = new Intent(Manufacturer.this, ShowCarPrice.class);
i.putExtra("brand", brand);
startActivity(i);
}
}
Showcarprice.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.Window;
import java.util.ArrayList;
public class ShowCarPrice extends AppCompatActivity {
private Cursor cursor;
private ArrayList<String> price;
private ArrayAdapter<String> aa;
private DBprice dbPrice;
private Manufacturer maFact;
SQLiteDatabase db;
ListView list;
Intent intent = getIntent();
String brand = intent.getStringExtra("brand");
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_car_price);
list = (ListView) findViewById(R.id.listView);
dbPrice = new DBprice(this);
db = dbPrice.getWritableDatabase();
cursor = db.rawQuery("SELECT " + dbPrice.KEY_TASK + " FROM " + dbPrice.TABLE_NAME + " WHERE Manufacturer = ?", new String[] {brand});
price = new ArrayList<String>();
cursor.moveToFirst();
while ( !cursor.isAfterLast() ){
price.add(cursor.getString(cursor.getColumnIndex(dbPrice.KEY_TASK)));
cursor.moveToNext();
}
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, price);
list.setAdapter(aa);
}
public void onPause() {
super.onPause();
dbPrice.close();
db.close();
}
}
And the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.macheckcar, PID: 934
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.student.macheckcar/com.example.student.macheckcar.ShowCarPrice}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
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 com.example.student.macheckcar.ShowCarPrice.<init>(ShowCarPrice.java:22)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
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) 
Please help.
UPDATE
public class ShowCarPrice extends AppCompatActivity {
// OK, Create the objects, variables here if needed
Intent intent;
String brand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// You should assign the intent here (in onCreate method)
intent = getIntent();
// Then, the string variable
brand = intent.getStringExtra("brand");
// You can also check whether or not received a valid value
if (brand != null && !brand.isEmpty())
// do something with brand value
else
// brand value is null or empty
}
}
Well, you call getIntent() at the wrong position. You should call getIntent() in method onCreate() , and I don't know why you keep intent as a member of your activity. If I were you I just do
String brand = getIntent().getStringExtra("brand");
in onCreate() method.
get your intent and extras of intent in onCreate() method of activity just check below link for this
https://stackoverflow.com/a/5265952/5316836

Application crashes when trying to take pictures/record video

I've just followed this guide: http://www.androidhive.info/2013/09/android-working-with-camera-api/
Trying to create a camera feature for my app, however when I click either take a picture or record a video (Either of the buttons), it crashes on me. I've checked through the code, but I can't seem to find the error.
CameraActivity.java:
package com.example.frederik.snapsule;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CameraActivity extends AppCompatActivity {
//Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
//Storing of content
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; //Content url storing
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_camera);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
recordVideo();
}
});
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
// code to check capture image response
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void previewCapturedImage() {
try {
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
private void previewVideo() {
try {
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory" );
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
And my logcat:
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: FATAL EXCEPTION: main
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: Process: com.example.frederik.snapsule, PID: 23065
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: java.lang.NullPointerException: file
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.net.Uri.fromFile(Uri.java:452)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity.getOutputMediaFileUri(CameraActivity.java:161)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity.captureImage(CameraActivity.java:72)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity.access$000(CameraActivity.java:26)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity$1.onClick(CameraActivity.java:57)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.view.View.performClick(View.java:5198)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21147)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My guess is it's an issue with Uri, but I'm unsure.
Also, the preview is not showing
It is a null pointer exception at line 161.
Apparently you hand in null into Uri.fromFile().
Therefore getOutputMediaFile(int type) returns null.
That may be the case if you see "Oops! Failed create" in your log.
It may be the case if type is neither MEDIA_TYPE_IMAGE nor MEDIA_TYPE_VIDEO.
It may be the case if new File(...) returned null.
Did you try debugging that method?
Your method
File getOutputMediaFile(int type)
its returning null, you have 2 return null; statements in it.
You should make a null check before calling Uri.fromFile()
EDIT
Just change this code to get rid of the crash, but it will still fail, you need to fix the original cause.
public Uri getOutputMediaFileUri(int type) {
File f = getOutputMediaFile(type);
if(f != null)
return Uri.fromFile(f);
else{
//Show some error message
return null;
}
}
Hope this helps.

Application Closing When Calling Intent

I have 2 classes. I am calling an intent from my menu class, and when I call the intent to go to my MainActivity class, it gives me an error that says, Unfortunately, app name has stopped. I need help figuring out what is happening. I know it is because there is an error somewhere in MainActivity. I just need help finding it.
Here is MainActivity.java's code:
package com.arborhillsvet.arborhillsveterinarianclinic;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ViewAnimator;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "parse information", "parse information");
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
WebView appointWeb = (WebView) findViewById(R.id.appointments);
appointWeb.loadUrl("https://www.google.com");
WebSettings webSettings = appointWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
appointWeb.setWebViewClient(new WebViewClient());
WebView promosWeb = (WebView) findViewById(R.id.promos);
promosWeb.loadUrl("https://www.yahoo.com");
WebSettings webSettings2 = promosWeb.getSettings();
webSettings2.setJavaScriptEnabled(true);
promosWeb.setWebViewClient(new WebViewClient());
WebView infoWeb = (WebView) findViewById(R.id.info);
infoWeb.loadUrl("https://www.bing.com");
WebSettings webSettings3 = infoWeb.getSettings();
webSettings3.setJavaScriptEnabled(true);
infoWeb.setWebViewClient(new WebViewClient());
WebView medsWeb = (WebView) findViewById(R.id.medicines);
medsWeb.loadUrl("https://www.aol.com");
WebSettings webSettings4 = medsWeb.getSettings();
webSettings4.setJavaScriptEnabled(true);
medsWeb.setWebViewClient(new WebViewClient());
Button next = (Button) findViewById(R.id.next);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewAnimator anim = (ViewAnimator) findViewById(R.id.views);
anim.showNext();
}
};
next.setOnClickListener(listener);
Button prev = (Button) findViewById(R.id.prev);
View.OnClickListener listener2 = new View.OnClickListener() {
public void onClick(View view) {
ViewAnimator anim = (ViewAnimator) findViewById(R.id.views);
anim.showPrevious();
}
};
prev.setOnClickListener(listener2);
ImageButton menu = (ImageButton) findViewById(R.id.menu);
View.OnClickListener listener3 = new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, menu.class);
startActivity(intent);
}
};
menu.setOnClickListener(listener3);
}
}
I also have edited this post and added the Logcat after somebody has requested it. I think I see the error and it appears as if it is something wrong with the Parse.initialize and Parse.enableLocalDatastore methods, although I do not see anything wrong with their location. I am wondering if I need to put the thread to sleep for a couple seconds so local datastore can load first. I'm not sure but here is the Logcat.
>08-17 19:39:03.018 4601-4601/com.arborhillsvet.arborhillsveterinarianclinic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.arborhillsvet.arborhillsveterinarianclinic, PID: 4601
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arborhillsvet.arborhillsveterinarianclinic/com.arborhillsvet.arborhillsveterinarianclinic.MainActivity}: java.lang.IllegalStateException: `Parse#enableLocalDatastore(Context)` must be invoked before `Parse#initialize(Context)`
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: `Parse#enableLocalDatastore(Context)` must be invoked before `Parse#initialize(Context)`
at com.parse.Parse.enableLocalDatastore(Parse.java:58)
at com.arborhillsvet.arborhillsveterinarianclinic.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I need help! Please and thank you.
I guess you have to initialize in Application class may be problem arise because you initialize in MainActivity
do like this
public class ParseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
ParseCrashReporting.enable(this);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "xxx", "xxx");
}
}

Categories