1

I'm creating a project in android application. I've implemented java jdt ast as stand alone application in java eclipse environment, and I get what I needed on console output. Now I want to run that code into my android application project. But when I set all the outputs in textView of android when I start the app, unfortunately it stops, and I don't know why... Would anyone have an idea on why this is happening? Thank you for your help.

package com.example.uiui;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
static TextView tv1;

 private String filename = "MySampleFile.java";
 private static String filepath = "/MyFileStorage";
 File myExternalFile = new File(Environment.getExternalStorageDirectory(),filepath );

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv1=(TextView)findViewById(R.id.txt1); 
    tv1.setMovementMethod(new ScrollingMovementMethod());

    Button readFromExternalStorage = 
               (Button) findViewById(R.id.getExternalStorage);
              readFromExternalStorage.setOnClickListener(this);

              //check if external storage is available and not read only  
              if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  

              } 
              else {
               myExternalFile = new File(getExternalFilesDir(filepath), filename);
              }

}

@Override
public void onClick(View v) {

     // EditText myInputText = (EditText) findViewById(R.id.myInputText);
      TextView responseText = (TextView) findViewById(R.id.responseText);
      String myData = "";
      switch (v.getId()) {
      case R.id.getExternalStorage:
           try {
           FileInputStream fis = new FileInputStream(myExternalFile);
           DataInputStream in = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
             myData = myData + strLine;
            }
            in.close();
           } catch (IOException e) {
           e.printStackTrace();
           }
        //   myInputText.setText(myData);
           responseText
           .setText("MySampleFile.txt data retrieved from Internal Storage...");

           parse(myData);

           break;

      }

}



public void parse(String str) {

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(str.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {

        Set names = new HashSet();

    public boolean visit(VariableDeclarationFragment node) {
            SimpleName name = node.getName();
            this.names.add(name.getIdentifier());
            tv1.setText(tv1.getText()+"Declaration of '" + name + "' at line"+cu.getLineNumber(name.getStartPosition())+"\n");


            return false; // do not continue 
        }


    public boolean visit(SimpleName node) {
        if (this.names.contains(node.getIdentifier())) {
            tv1.setText(tv1.getText()+"Usage of '" + node + "' at line "+ cu.getLineNumber(node.getStartPosition())+"\n");
        }
        return true;
    }           


public boolean visit(MethodInvocation node) {
System.out.println("Method Name: " + node.getName()+"\n");

 Expression expression = node.getExpression();
      if (expression != null) {
          tv1.setText(tv1.getText()+"Expression: " + expression.toString()+"\n");

                        ITypeBinding typeBinding = expression.resolveTypeBinding();

      if (typeBinding != null) {
          tv1.setText(tv1.getText()+"Type: " + typeBinding.getName());
                        }
                    }
           IMethodBinding binding = node.resolveMethodBinding();
      if (binding != null) {
           ITypeBinding type = binding.getDeclaringClass();
      if (type != null) {
          tv1.setText(tv1.getText()+"Decl: " + type.getName());
                        }
                    }

                    return true;
                }
            });
        }



private static boolean isExternalStorageReadOnly() {  
      String extStorageState = Environment.getExternalStorageState();  
      if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
       return true;  
      }  
      return false;  
     }  

     private static boolean isExternalStorageAvailable() {  
      String extStorageState = Environment.getExternalStorageState();  
      if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
       return true;  
      }  
      return false;  
     }  


}

The code shows no error, but the application doesn't work...

Now another question comes into my mind: can we really use java jdt ast as an android application? The same libraries are imported, but the code works fine when it is used as java application project..

In any case, here is the stack trace of from logCat.

09-01 03:38:05.780: E/AndroidRuntime(21566): FATAL EXCEPTION: main
09-01 03:38:05.780: E/AndroidRuntime(21566): java.lang.NoClassDefFoundError:  org.eclipse.jdt.core.dom.ASTParser
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.example.uiui.MainActivity.parse(MainActivity.java:98)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.example.uiui.MainActivity.onClick(MainActivity.java:86)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.view.View.performClick(View.java:4475)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.view.View$PerformClick.run(View.java:18786)  
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.os.Handler.handleCallback(Handler.java:730)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.os.Looper.loop(Looper.java:176)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.app.ActivityThread.main(ActivityThread.java:5419)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at java.lang.reflect.Method.invokeNative(Native Method)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at java.lang.reflect.Method.invoke(Method.java:525)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at dalvik.system.NativeStart.main(Native Method)

And this is my resource layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.uiui.MainActivity" >
 <TextView
   android:id="@+id/txt1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentLeft="true"
   android:layout_alignParentTop="true"
   android:layout_marginLeft="0dp"
   android:layout_marginTop="10dp"
   android:maxLines="200"
   android:scrollbars="vertical"
   android:text="TextView" />

   <Button
   android:id="@+id/getExternalStorage"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/txt1"
   android:layout_alignParentBottom="true"
   android:layout_marginBottom="18dp"
   android:text="Display from External Storage" />

   <EditText
   android:id="@+id/myInputText"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_above="@+id/getExternalStorage"
   android:layout_alignLeft="@+id/getExternalStorage"
   android:layout_marginBottom="75dp"
   android:ems="10"
   android:gravity="top|left"
   android:inputType="textMultiLine"
   android:lines="5"
   android:minLines="3" >
   <requestFocus />
  </EditText>

   <TextView
   android:id="@+id/responseText"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/txt1"
   android:layout_below="@+id/txt1"
   android:layout_marginTop="18dp"
   android:maxLines="200"
   android:scrollbars="vertical"
   android:text=" ad"
   android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

And finally the manifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uiui"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
Gilles
  • 9,269
  • 4
  • 34
  • 53
  • Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare Aug 29 '15 at 22:22
  • i have checked the log cat and edited the question . how can i resolve these log cat issues . i have edited and provided the other files too . please check where the problem is ..?? –  Aug 29 '15 at 23:14

1 Answers1

2

You did not indicate what line in ParseFilesInDir() is where you are crashing. However, this line is completely wrong in Android:

File dirs = new File(".");

So, first, you need to decide where you are going to copy your files onto your Android device. Your Android device is not your development PC, so there is no Java source code on that Android device, unless you copy it there.

Then, given wherever you put the files, you need to adjust ParseFilesInDir() to match.

Your two main options for where to put the files are internal storage and external storage. It is usually easier for you to copy files onto the device if you are copying to external storage.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Suppose i copy the file on external storage in android device . then how can i access the external storage from ParseFilesInDir() ? –  Aug 30 '15 at 00:10
  • @AdnanQureshi: Well, it depends on where on external storage you put the files. See "The Many Paths Under Which External Storage is Stored" in [the external storage blog post that I linked to from my answer](https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html). – CommonsWare Aug 30 '15 at 10:23
  • i checked through these links and got to know much about storages. if i copy java code in external/sdCard dir in some custom folder like abc . which contains the required file, how then should i configure my code in parseFilesDir() in order to read the file from external some static folder ? –  Aug 30 '15 at 21:42
  • @AdnanQureshi: [`Environment.getExternalStorageDirectory()`](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29) will give you the root of external storage. From there, create a `File` object pointing to the relative path where you put your files (e.g., `new File(Environment.getExternalStorageDirectory(), "your/files/went/in/here")`). – CommonsWare Aug 30 '15 at 22:16
  • its worked thanks a lot . now the app is working . and i am trying to run it on my device....bingo :-) –  Aug 30 '15 at 23:04
  • while i created the project .and make it run on application it surprises me . it says FATAL EXCEPTION: main java.lang.NoClassDefFoundError: org.eclipse.jdt.core.dom.ASTParser at com.example.krparse.KrParseActivity.parse(KrParseActivity.java:98) at com.example.krparse.KrParseActivity.onClick(KrParseActivity.java:86) i also changed the code . i should show you in order to get the app running on device . –  Aug 31 '15 at 22:21
  • i have edited the question .. now u can see the logcat displays that Astparser class not found . but i hav all the jars included in the project –  Aug 31 '15 at 22:33
  • 1
    @AdnanQureshi exactly how did you include the jars? Android complains that they aren't there. It could also make sense to post a new question. This one was answered. – zapl Aug 31 '15 at 23:21
  • @zapl: i included them from project->preferences->add external jars and added all the jars for org.eclipse.jdt.core.dom... and my ask question limit was reached but the problem is in this existing project so i edited the question –  Sep 01 '15 at 00:05
  • @AdnanQureshi that doesn't work with android. Remove it (e.g. right click the .jar, BuildPath > Remove from BuildPath) then copy the jar into the `libs` folder and it should appear automatically http://stackoverflow.com/questions/1334802/how-can-i-use-external-jars-in-an-android-project – zapl Sep 01 '15 at 00:13
  • after removong my .jar file from build path and copying them to libs folder the error removed.. but now its showing this error: Error generating final archive: Found duplicate file for APK: about.html Origin 1: C:\Users\Adnan\Desktop\eclipse juno workspace adi\uiui\libs\org.eclipse.core.contenttype_3.4.1.R35x_v20090826-0451.jar Origin 2: C:\Users\Adnan\Desktop\eclipse juno workspace adi\uiui\libs\org.eclipse.osgi_3.5.2.R35x_v20100126.jar –  Sep 01 '15 at 00:53
  • @zapl : adding .jars to libs folder . How its duplicating the files .? I think I should create a new project from scratch and then run the code I guess this would solve the issue . But if it detecting duplicate in these .jars after deleting one of them it shows the duplication with org.eclipse.core.jobs something like this .?? How should I solve this. –  Sep 01 '15 at 01:35
  • @AdnanQureshi Wow, you seem to find all the issues :) So this time it's because Android unpacks all the .jars (they are just .zip files) and makes one big file out of them. Eclipse projects all have an "about.html" file in them. And since you have 2 eclipse jars you have 2 of those about.html files and it doesn't know how to deal with it. If you were using AndroidStudio you could exclude them like https://code.google.com/p/android/issues/detail?id=61573 (using `packagingOptions`) but in your case I'd simply open 1 of the jars with a zip tool (7-zip, winrar, .. ) and delete the html file. – zapl Sep 01 '15 at 08:54
  • @zapl: I appreciate your knowledge . it all worked . thanx a lot :-) –  Sep 01 '15 at 21:21
  • @zapl: i am stuck at the same place ahead . as i deleted the duplicate files from .jars the application runs but does not gives all the supposed output . and also logCat gives : –  Sep 07 '15 at 20:18
  • W/dalvikvm(28727): VFY: unable to find class referenced in signature (Lorg/eclipse/core/runtime/IExtensionRegistry;) I/dalvikvm(28727): Could not find method org.eclipse.core.runtime.IExtensionRegistry.getExtensionPoint, referenced from method org.eclipse.jdt.core.JavaCore.computeClasspathContainerInitializer W/dalvikvm(28727): VFY: unable to resolve interface method 30030: Lorg/eclipse/core/runtime/IExtensionRegistry;.getExtensionPoint (Ljava/lang/String;Ljava/lang/String;)Lorg/eclipse/core/runtime/IExtensionPoint; –  Sep 07 '15 at 20:18
  • not only this error it keeps on producing these errors with different .jars . i dont know how to get rid of this ..? –  Sep 07 '15 at 20:20
  • @AdnanQureshi please ask a new question. – zapl Sep 08 '15 at 06:25
  • http://stackoverflow.com/questions/32463066/how-to-avoid-duplication-of-files-from-jars-when-exporting-to-final-apk here is the link to the new question. –  Sep 08 '15 at 16:47
  • @zapl: any solution to problem ? –  Sep 11 '15 at 22:57