file writing is not performing in android - java

I need to write the registration credentials into a file during registration and during login will check that file for credentials. but on registration button click nothing is performing.
Manifest file contains this permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
the registration.java part:
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String user=username.getText().toString();
String pwd=password.getText().toString();
String cpwd=confirm.getText().toString();
if(user.equals("")||pwd.equals("")||cpwd.equals("")){
Toast.makeText(getApplicationContext(), "Fields cannot be Blank", Toast.LENGTH_SHORT).show();
}
else if(pwd.equals(cpwd)){
String data=user+","+pwd+":";
try {
FileOutputStream fout = new FileOutputStream(Environment.getExternalStorageDirectory()+"/myapp/userregister.txt/", true);
fout.write(data.getBytes());
Toast.makeText(getApplicationContext(), "Succesfully Register", Toast.LENGTH_SHORT).show();
Intent a=new Intent(getApplicationContext(),LoginActivity.class);
startActivity(a);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(!pwd.equals(cpwd)){
Toast.makeText(getApplicationContext(), "Password not match.. Try again!", Toast.LENGTH_SHORT).show();
}
}
});
In LoginActivity.java
if(username.equals("") || password.equals("")){
Toast.makeText(getApplicationContext(), "Fields Cannot be Blank", Toast.LENGTH_SHORT).show();
}else{
String reply=FileManipulator.authenticateUser(username, password);
if(reply.equals("user")){
Intent gotoNextActivity=new Intent(getApplicationContext(),HomeActivity.class);
startActivity(gotoNextActivity);
}else{
Toast.makeText(getApplicationContext(), "Invalid User.... Try again",Toast.LENGTH_SHORT).show();
}
}
FileManipulator class authenticateUser function:
public static String authenticateUser(String user, String pass){
String data="";
String data1 = "";
try{
FileInputStream fin=new FileInputStream(Path.userregister);
byte[] b=new byte[fin.available()];
fin.read(b);
data=new String(b);
String st=user+","+pass+":";
if(data.contains(st)){
data1="user";
}
}catch(Exception e){
e.printStackTrace();
}
return data1;
}
The log cat shows
09-02 05:48:06.292: D/dalvikvm(1964): GC_CONCURRENT freed 240K, 12% free 2838K/3200K, paused 5ms+32ms, total 177ms
09-02 05:48:06.802: I/Choreographer(1964): Skipped 36 frames! The application may be doing too much work on its main thread.
09-02 05:48:10.362: I/Choreographer(1964): Skipped 32 frames! The application may be doing too much work on its main thread.
09-02 05:48:20.872: W/System.err(1964): java.io.FileNotFoundException: /mnt/sdcard/myapp/userregister.txt: open failed: EACCES (Permission denied)
09-02 05:48:20.872: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:416)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
09-02 05:48:20.882: W/System.err(1964): at com.example.text.RegActivity$1.onClick(RegActivity.java:49)
09-02 05:48:20.892: W/System.err(1964): at android.view.View.performClick(View.java:4204)
09-02 05:48:20.892: W/System.err(1964): at android.view.View$PerformClick.run(View.java:17355)
09-02 05:48:20.902: W/System.err(1964): at android.os.Handler.handleCallback(Handler.java:725)
09-02 05:48:20.912: W/System.err(1964): at android.os.Handler.dispatchMessage(Handler.java:92)
09-02 05:48:20.912: W/System.err(1964): at android.os.Looper.loop(Looper.java:137)
09-02 05:48:20.912: W/System.err(1964): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invokeNative(Native Method)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invoke(Method.java:511)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-02 05:48:20.922: W/System.err(1964): at dalvik.system.NativeStart.main(Native Method)
09-02 05:48:20.932: W/System.err(1964): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.Posix.open(Native Method)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
09-02 05:48:20.952: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:400)
09-02 05:48:20.952: W/System.err(1964): ... 14 more
I'm a newbie to android and java..please help me to find the error.

1) Add android.permission.WRITE_EXTERNAL_STORAGE in AndroidManifest.xml file.
2) Always check for the availability of external storage before writing/reading by :
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
} else {
// Can't read or write
}
3) Create a directory, then make your file in it.
File dir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp");
dir.mkdirs();
File file = new File(dir, "userregister.txt");
NOTE :
If you are using Android 4.4 KitKat, Apps are not allowed to write to secondary external storage devices, except in their package-specific directories
The reason from http://source.android.com/devices/tech/storage/index.html
The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.

Related

File.createNewFile() method throws exception in Android M

I have a problem to create file in Android M.
I use Nexus 9 with Android 6.0.1. Then I set in my project as below:
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
build.gradle
android {
defaultConfig {
targetSdkVersion 23
...
}
}
MainActivity.Java
public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String rootPath = storagePath + "/test";
String fileName = "/test.zip";
File root = new File(rootPath);
if(!root.mkdirs()) {
Log.i("Test", "This path is already exist: " + root.getAbsolutePath());
}
File file = new File(rootPath + fileName);
try {
if (!file.createNewFile()) {
Log.i("Test", "This file is already exist: " + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Build was success and application was launched, but I got exception message like this:
IOExceiption
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory)
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: at java.io.File.createNewFile(File.java:939)
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: at com.sample.myapplication.MainActivity.onCreate(MainActivity.java:36)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.Activity.performCreate(Activity.java:6251)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.-wrap11(ActivityThread.java)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.os.Looper.loop(Looper.java:148)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at java.lang.reflect.Method.invoke(Native Method)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at libcore.io.Posix.open(Native Method)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at java.io.File.createNewFile(File.java:932)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: ... 13 more
How can I solve this problem? I don't catch what I miss....
Please help.
Updated
Replace storagePath to access scoped storage, for Android 10.
Refer this document for more detail.
Thanks, laalto.
I didn't know about runtime permission.
I solved exception like this:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Request user permissions in runtime */
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
100);
/* Request user permissions in runtime */
createTestFile();
}
#TargetApi(23)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// User checks permission.
} else {
Toast.makeText(MainActivity.this, "Permission is denied.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void createTestFile() {
// String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
// If Target API level is 29(Android 10),
// you should access local path in scoped storage mode.
File localStorage = getExternalFilesDir(null);
if (localStorage == null) { return; }
String storagePath = localStorage.getAbsolutePath();
String rootPath = storagePath + "/test";
String fileName = "/test.zip";
File root = new File(rootPath);
if(!root.mkdirs()) {
Log.i("Test", "This path is already exist: " + root.getAbsolutePath());
}
File file = new File(rootPath + fileName);
try {
int permissionCheck = ContextCompat.checkSelfPermission(
MainActivity.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
if (!file.createNewFile()) {
Log.i("Test", "This file is already exist: " + file.getAbsolutePath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
It works!
I was having the same problem. I got an IOException on the file.createNewFile. A closer look at the exception reveals that it was due to "permissions denied". I was writing to my getFilesDir, so I shouldn't need an in the android manifest to accomplish this task. I of course added both READ and WRITE permissions for external storage, and of course, that didn't fix the problem.
I had been testing the code using a NEXUS 6 emulator with sdk 26. Without changing any code, I tried testing using a PIXEL C emulator with sdk 26 and the problem did not occur. So there seems to be some problem with my Nexus 6 emulator.
I suspect that this hasn't always been a problem and that this emulator instance got corrupted, but I haven't verified that. I did take the time to look at the linux file permission on the directories I was creating the file into an it reported "drwxrwxrwx", which is correct. I will add that I've implemented a FileProvider with paths to the directory I'm trying to create the new file at. The code I'm using pretty much looks like the code that Kae10 shows.
I traced the problem down to this code in UnixFileSystem:
public boolean createFileExclusively(String path) throws IOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return createFileExclusively0(path);
}
the exception is thrown from createFileExlussively0, which I not able to debug into. I haven't investigated this issue any further (i.e. 1.) would deleting the avd instance and recreating it help, my guess is that might, 2.) is there a later system image I should be using?)

Button not creating a file and showing email provider option menu when pressed

I've created a button that creates a file then sends it as an attachment to an email,
it grabs the text from one of the textviews, saves it to a .txt and sends it. A small email service option selector should show up too. The code is meant to create a file path if one is not already there. This code is above the onCreate method and in a regular activity.
i keep getting this in the logcat (specific message marked by (-->)):
-->08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ java.io.IOException: open failed: ENOENT (No such file or directory)<---
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:946)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.example.adrian.trucktracker.Locator.clickedUpdate(Locator.java:76)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$1.onClick(View.java:3860)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View.performClick(View.java:4480)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$PerformClick.run(View.java:18686)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Looper.loop(Looper.java:157)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5872)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:939)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ ... 15 more
My code:
public void clickedUpdate(View view)
{
TextView dLong = (TextView) findViewById (R.id.textLong);
TextView dLat = (TextView) findViewById (R.id.textLat);
String dataLat = dLat.getText().toString();
String dataLong = dLong.getText().toString();
boolean UpdateResume;
if(!(dataLat.equals("") && !(dataLong.equals(""))))
{
UpdateResume = true;
}
else
{
UpdateResume = false;
}
TelephonyManager telephonemanager =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String PhoneNumber = telephonemanager.getLine1Number();
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
File Data = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"data" + File.separator+"Locationer.txt");
String datapath = Data + ""
if(!Data.exists())
{
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
while (UpdateResume = true)
{
if (Data.exists())
{
try
{
FileWriter fileWriter = new FileWriter(Data);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write(PhoneNumber + "," + dataLat + "," + dataLong);
bfWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
break;
}
}
Intent emailintent = new Intent(Intent.ACTION_SEND);
emailintent.setType("text/plain");
emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"apraiswater#legion-logistics.com"});
emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
File root = Environment.getExternalStorageDirectory();
String DataAttachment = "Android/data/Locationer.txt";
File filer = new File(root, DataAttachment);
if (!filer.exists() || filer.canRead())
{
return;
}
Uri uri = Uri.fromFile(filer);
emailintent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));
}
A few details seem relevant:
First you check the existence of the dir:
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
according to the documentation, your try{}catch(Exception e){} aren't needed. You just would need to check whether the directory actually exists. There's the additional problem that you seem to create a subdirectory of another subdirectory. So, you might want to exchange it to mkdirs() instead.
Afterwards, you try to create the File if it doesn't exist
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Take a look at the documentation for this method. You might note that it tells you
This method is not generally useful. For creating temporary files, use
createTempFile(String, String) instead. For reading/writing files, use
FileInputStream, FileOutputStream, or RandomAccessFile, all of which
can create files.
but maybe, if you've included the proper permissions, the changes I suggested above will help to make your code work.

java.lang.NoClassDefFoundError

i was implmenting a pdf reader in my project when i got the following error..
E/AndroidRuntime(1495): FATAL EXCEPTION: main
E/AndroidRuntime(1495): Process: com.example.testqstn, PID: 1495
E/AndroidRuntime(1495): java.lang.NoClassDefFoundError: com.questionpoint.pdf.Pdf
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.openPdfIntent(Question_Point_Main.java:272)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.CopyReadAssets(Question_Point_Main.java:266)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.pdfSelection(Question_Point_Main.java:128)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main$2.onClick(Question_Point_Main.java:104)
E/AndroidRuntime(1495): at android.view.View.performClick(View.java:4438)
E/AndroidRuntime(1495): at android.view.View$PerformClick.run(View.java:18422)
E/AndroidRuntime(1495): at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime(1495): at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(1495): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1495): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1495): at dalvik.system.NativeStart.main(Native Method)
I/Process(1495): Sending signal. PID: 1495 SIG: 9
i had imported a project to my code.. my library file is named libs, and i have repeatedly cleaned my project.. but still the error persists.. Thanks in advance..
The code that leads to error
public void CopyReadAssets(String url) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), url);
try {
in = assetManager.open(url);
out = openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getFilesDir() + "/"+url;
openPdfIntent(path);
}
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Try these steps:
Step 1: Create a folder "lib", and copy all third-party jars here;
Step 2: Add these jars to build path;
Step 3: Use the folder as Source Folder(shown below).
Maybe you just forgot the underscore and you meant com.question_point.pdf.Pdf?
It would be easier to tell if you could post the relevant code where you make the call that leads to the Exception.

Show ProgressDialog in SQLiteOpenHelper onCreate method

I'm new in android programming. I'm writing simple application that should execute sql file, in first run. But it seems that this process take couple of seconds so I figure that application should show progressDialog while it will be executing sql file. But when I try to run application, dialog is showing with message "app has stopped ...". Please help me.
#Override
public void onCreate(SQLiteDatabase database)
{
String CREATE_BIBLE_TABLE = "CREATE TABLE bible (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"book INTEGER, " +
"chapter INTEGER NOT NULL, " +
"verse INTEGER NOT NULL, " +
"content TEXT" +
")";
database.execSQL(CREATE_BIBLE_TABLE);
new FirstLoadAsyncTask(database).execute();
}
public class FirstLoadAsyncTask extends AsyncTask<Void, Void, Void>
{
private SQLiteDatabase database;
private ProgressDialog progressDialog;
public FirstLoadAsyncTask(SQLiteDatabase database)
{
this.database = database;
}
#Override
protected void onPreExecute()
{
((Activity) context).runOnUiThread(new Runnable()
{
#Override
public void run()
{
progressDialog = ProgressDialog.show(context, "Loading...", "");
}
});
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream inputStream = context.getAssets().open("bible.sql");
execSqlFile(database, inputStream);
} catch(IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Class extends SQLiteOpenHelper.
Edit:
Logcat:
01-06 18:27:53.221 14118-14118/pl.several27.Biblia_Warszawska E/Trace﹕ error opening trace file: No such file or directory (2)
01-06 18:27:53.891 14118-14118/pl.several27.Biblia_Warszawska I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081_msm7627a_JB_REL_2.0.3_CL2820657_release_AU (CL2820657)
Build Date: 01/22/13 Tue
Local Branch:
Remote Branch: quic/jb_rel_2.0.3
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081 + NOTHING
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska E/copybit﹕ Error opening frame buffer errno=13 (Permission denied)
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska W/Adreno200-EGLSUB﹕ <updater_create_surface_state:342>: updater_create_surface_state failed to open copybit, error: -13
01-06 18:27:54.011 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x53be8000 size:1536000 offset:0 fd:61
01-06 18:27:54.021 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x5083a000 size:4096 offset:0 fd:63
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x541fb000 size:1536000 offset:0 fd:66
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50a50000 size:4096 offset:0 fd:68
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x54472000 size:1536000 offset:0 fd:70
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50c75000 size:4096 offset:0 fd:72
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x545e9000 size:1536000 offset:0 fd:74
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50d4c000 size:4096 offset:0 fd:76
01-06 18:27:57.231 14118-14118/pl.several27.Biblia_Warszawska D/book choosen﹕ 1
01-06 18:27:57.581 14118-14118/pl.several27.Biblia_Warszawska W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40ca4540)
01-06 18:27:57.601 14118-14118/pl.several27.Biblia_Warszawska E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.several27.Biblia_Warszawska/pl.several27.Biblia_Warszawska.ChapterActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at pl.several27.Biblia_Warszawska.Database$FirstLoadAsyncTask.onPreExecute(Database.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at pl.several27.Biblia_Warszawska.Database.onCreate(Database.java:42)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
at pl.several27.Biblia_Warszawska.Database.countChapters(Database.java:148)
at pl.several27.Biblia_Warszawska.ChapterActivity.onCreate(ChapterActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
            at android.app.ActivityThread.access$600(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5520)
            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:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
            at dalvik.system.NativeStart.main(Native Method)
01-06 18:27:59.511 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ killProcess, pid=14118
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.VMStack.getThreadStackTrace(Native Method)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.Thread.getStackTrace(Thread.java:599)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ android.os.Process.killProcess(Process.java:956)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:108)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.NativeStart.main(Native Method)
Also I tried this way display progressdialog in non-activity class but it won't work too.
And here is whole application source code but without dialog: https://github.com/several27/BibliaWarszawska_Android
Please can anyone help me?
I do something like that on my application but I prefer to do that on background, so the user just don't have access to the screens that depend on my database...
You can try something like that:
public class BackgroundSyncService extends IntentService {
public static final String NOTIFICATION = "com.example.sync.service";
public static final String RESULT = "result";
public BackgroundSyncService() {
super("BackgroundSyncService");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do here what you want with your database
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
Create a receiver (I use a inner class on my project)
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
//Do what you want here , like enable a section of your app
}
}
};
Then you need to register the service to your activity adding :
registerReceiver(receiver, new IntentFilter(BackgroundSyncService.NOTIFICATION));
Don't forget to unregister the receiver:
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Also don't forget to register your IntentService on the AndroidManifest.xml
<service android:name="com.example.service.BackgroundSyncService" />
EDIT
Also you need to include the call to start your service where you want, I start mine on App instance:
Intent intent = new Intent(this, BackgroundSyncService.class);
startService(intent);
EXPLANATION
First you are creating a service to do what you want, the service can do whatever you want, in your case you will fill a database...
After you have created this service, you will set when you want to start this service (the edit part)...
After that you will register your activity to listen the service thats why we have created the BroadcastReceiver, the BroadcastReceiver will be called when your Service execute the line:
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
I guess the better way when the app starts you present the user with a message/ an activity that is not database related or just use the splash screen at the time that it is loading and estimate the time it normally finish loading to be the timer of the splash screen

Activity closes when trying to asyncronously connect to twitter

I have been trying to program a twitter client for Android (using twitter4j). So far the idea is to have a simple GUI, and if there is not a file with the OAuth token in the SD Card, connect to the Twitter API using AsyncTask, get the URL for the authorization and open the default browser. However, the browser never runs. Depending on the different modifications I have made trying to fix this, either the Activity starts normally but the browser never starts or the Activity crashes. I have come to a point of a a little of frustation and confussion. Can someone point out what's wrong with my code?
public class StatusActivity extends Activity {
private static final String TAG = "StatusActivity";
EditText editText;
Button updateButton;
File oauthfile = null;
public Context context = getApplicationContext();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
Log.d(TAG, "started");
// Find views
editText = (EditText) findViewById(R.id.editText); //
updateButton = (Button) findViewById(R.id.buttonUpdate);
oauthfile = new File("sdcard/auth_file.txt");
//Check if the file with the keys exist
if (oauthfile.exists()==false){
Log.d(TAG, "file not created");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "file not created.", Toast.LENGTH_SHORT);
toast.show();
new Authorization(context).execute();
}
}
public void openBrowser (View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Log.d(TAG, "onclick");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
}
class Authorization extends AsyncTask <String, Integer, String>{
String url = null;
private Context context;
Authorization(Context context) {
this.context = context.getApplicationContext();
}
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
}
#Override
public String doInBackground(String... params) {
ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true)
//I have eliminated the keys from the question :)
.setOAuthConsumerKey("XXXXXXXXXXXXXX")
.setOAuthConsumerSecret("XXXXXXXXXXXXXXX");
Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
RequestToken requestToken = null;
AccessToken accessToken = null;
do{
try {
requestToken = OAuthTwitter.getOAuthRequestToken();
url = requestToken.getAuthorizationURL();
}
catch (TwitterException ex) {
ex.printStackTrace();
}
}
while (accessToken==null);
return url;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(context, "Opening browser.", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_ALL_APPS, Uri.parse(url));
context.startActivity(browserIntent);
}
}
I know that at least checks if the file for the tokens exists because the toast "file not created" appears, and that the activity is able to run the browser if I press the button. The app has permissions to write in the SD card and use the Internet. Thanks in advance.
Logcat Trace:
03-28 19:02:32.816: E/AndroidRuntime(278): FATAL EXCEPTION: main
03-28 19:02:32.816: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.versec.pardinus/com.versec.pardinus.StatusActivity}: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 19:02:32.816: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.versec.pardinus.StatusActivity.<init>(StatusActivity.java:30)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstanceImpl(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstance(Class.java:1429)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
03-28 19:02:32.816: E/AndroidRuntime(278): ... 11 more
This is what is causing your crash.
public Context context = getApplicationContext();
You're not even using it when you need it, so you can just get rid of this line.
Btw, something else I noticed while looking at your code is this:
oauthfile = new File("sdcard/auth_file.txt");
Don't take the "sdcard/" path for granted. Use this instead:
File dir = Environment.getExternalStorageDirectory();
File oauthfile = new File(dir, "auth_file.txt");

Categories