user5212915
user5212915

Reputation:

How to run Java jdt AST in Android Application

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>

Upvotes: 1

Views: 628

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

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.

Upvotes: 2

Related Questions