Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从另一个片段获取EditText值并将其发送到Webview_Javascript_Android - Fatal编程技术网

Javascript 从另一个片段获取EditText值并将其发送到Webview

Javascript 从另一个片段获取EditText值并将其发送到Webview,javascript,android,Javascript,Android,我的主要活动是一个工具栏按钮和两个片段。片段1有一个Edittext,片段2有一个Webview。当我在片段1中输入JS/Html/css代码,然后按下按钮,它将在片段2中的webview中显示Html代码。 这是我的主要活动 ` package com.example.apparatusgunventris.jswizard; public class Overview1 extends AppCompatActivity { private DrawerLayout mDra

我的主要活动是一个工具栏按钮和两个片段。片段1有一个Edittext,片段2有一个Webview。当我在片段1中输入JS/Html/css代码,然后按下按钮,它将在片段2中的webview中显示Html代码。
这是我的主要活动

`      package com.example.apparatusgunventris.jswizard;


public class Overview1 extends AppCompatActivity  {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
NavigationView navigationView;

private EditText txtEditor;
WebView webView,webView2;
Button runButton;
String[] javascript = {"<!DOCTYPE>  \n \n <html>  \n <body>\n</body>\n \n </html>","</html>","<body>","<script> \n </script"};
String data;
Fragment fragment2;
Toolbar mappBar;
TabItem webview_tab;
TabItem compiler_tab;
TabLayout tablayout;
private ViewPager mViewPager;
boolean status = true;



private long backPressedTime;
private String TAG;
private SectionsPagerAdapter mSectionsPagerAdapter;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_overview1);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);



    WebView webView = (WebView) findViewById(R.id.webView);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>
            (this,android.R.layout.simple_spinner_dropdown_item,javascript);



    txtEditor = (EditText)findViewById(R.id.txtEditor);


    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.Open, R.string.Close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();

    Toolbar mappBar = (Toolbar)findViewById(R.id.mappBar);


    txtEditor = (EditText) findViewById(R.id.txtEditor);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    tablayout = (TabLayout)findViewById(R.id.tablayout);
    webview_tab = (TabItem)findViewById(R.id.webView_tab);
    compiler_tab = (TabItem)findViewById(R.id.compiler_tab);
    mViewPager= (ViewPager)findViewById(R.id.view_pager);

    tablayout.setupWithViewPager(mViewPager);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(mSectionsPagerAdapter);






    navigationView = (NavigationView)findViewById(R.id.navView);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            WebView webView = (WebView) findViewById(R.id.webView);
            switch (item.getItemId())
            {
                case R.id.nav_firstlayout:
                    mDrawerLayout.closeDrawer(Gravity.START, false);
                    webView.loadUrl("file:///android_asset/JavaScriptTutorial.html");
                    webView.getSettings().setJavaScriptEnabled(true);
                    webView.setVisibility(View.VISIBLE);
                    navigationView.setCheckedItem(R.id.nav_firstlayout);

                    break;

                case R.id.nav_secondlayout:
                    mDrawerLayout.closeDrawer(Gravity.START, false);
                    webView.loadUrl("file:///android_asset/JavaScript Introduction.html");
                    webView.getSettings().setJavaScriptEnabled(true);
                    webView.setVisibility(View.VISIBLE);
                    navigationView.setCheckedItem(R.id.nav_secondlayout);
                    break;


                case R.id.nav_thirdlayout:
                    mDrawerLayout.closeDrawer(Gravity.START, false);

                    setContentView(R.layout.activity_editor);
                    break;

            }


            return false;
        }
    });
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater appToolbar = getMenuInflater();
    appToolbar.inflate(R.menu.apptoolbar,menu);
    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch (item.getItemId()) {
        case R.id.action_Run:
            // User chose the "Settings" item, show the app settings UI...
            String passCode = txtEditor.getText().toString();

            String state;
            state = Environment.getExternalStorageState();
            File Root = Environment.getExternalStorageDirectory();
            File Dir = new File (Root.getAbsolutePath()+"/JS-Wizard");
            File file = new File(Dir,"example.html");
            if(Environment.MEDIA_MOUNTED.equals(state))
            {


                if(!Dir.exists())
                {
                    Dir.mkdir();
                }

                String txt = txtEditor.getText().toString();
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    fileOutputStream.write(txt.getBytes());
                    fileOutputStream.close();
                    Toast.makeText(Overview1.this, "Running", Toast.LENGTH_SHORT).show();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(Overview1.this, "FNF", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(Overview1.this, "Error", Toast.LENGTH_SHORT).show();

                }
            }
            else
            {
                Toast.makeText(getApplicationContext(),"SD Card Not Found",Toast.LENGTH_SHORT).show();
            }
            String Message;
            FileOutputStream outputStream = null;


            webView = (WebView)findViewById(R.id.webView);

            try {
                FileInputStream fis = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fis);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuffer stringBuffer = new StringBuffer();

                while ((Message=bufferedReader.readLine())!=null){

                    stringBuffer.append(Message+"\n");

                }

                webView.loadUrl("file:///storage/sdcard/JS-Wizard/example.html");
                webView.setVisibility(View.VISIBLE);
                txtEditor.onEditorAction(EditorInfo.IME_ACTION_DONE);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            setContentView(R.layout.activity_webview);


        case R.id.paste_code:


            return true;



    }
    return super.onOptionsItemSelected(item);
}



@Override
public void onBackPressed() {
    WebView webView = (WebView) findViewById(R.id.webView);
    if(backPressedTime+2000 > System.currentTimeMillis()){

        super.onBackPressed();


    }
    else

        webView.setVisibility(View.GONE);
    Toast.makeText(getBaseContext(),"Press Back Again to Exit",Toast.LENGTH_SHORT).show();
    {
        backPressedTime = System.currentTimeMillis();

    }


}
public class SectionPagerAdapter extends FragmentPagerAdapter {
    public SectionPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        switch(position){
            case R.id.compiler_tab:
                editor_fragment editorFragment = new editor_fragment();
                return editorFragment;
            case R.id.webView_tab:
                webview_fragment webviewFragment = new webview_fragment();
                return webviewFragment;



        }
        return null;
    }

    @Override
    public int getCount() {
        return 0;
    }
}{

}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new editor_fragment();
            case 1:
                return new webview_fragment();
            default:
                return null;
        }


    }

    @Override
    public int getCount() {
        return 2;
    }
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position){
            case 0:
                return "Compiler";
            case 1:
                return "HTML View";

        }
        return null;
    }
}`
下面是活动编辑器的xml代码

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


    <EditText
        android:id="@+id/txtEditor"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp" />
这里是活动的xml\u webview

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView"></WebView>

</RelativeLayout>

调用
txtEditor=(EditText)findViewById(R.id.txtEditor)
会返回一个空对象,因为
R.id.txtEditor
不存在于
activity\u overview
上,这个id
R.id.txtEditor
只存在于
activity\u编辑器
,因此,调用
String passCode=txtEditor.getText().toString()
将抛出一个
NullPointerException


尝试调用片段上的click事件

您需要一个接口,可以将其用作回调,以便在片段和活动之间进行通信。这将有任何类型的事件,在这些事件中,您的活动需要从片段接收信息,以便在其他地方进行协调


请阅读本文以供参考

所以我还应该在片段上声明
R.id.action\u run
按钮?关于如何做到这一点,有什么建议吗?我恐怕要说,我还是一个android开发的初学者。
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


    <EditText
        android:id="@+id/txtEditor"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp" />
public class webview_fragment extends Fragment {

View view;

public webview_fragment(){

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.activity_webview,container ,false);
    // Inflate the layout for this fragment
    return view;
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView"></WebView>

</RelativeLayout>
 06-03 20:06:13.626 14999-14999/com.example.apparatusgunventris.jswizard E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.apparatusgunventris.jswizard, PID: 14999
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
    at com.example.apparatusgunventris.jswizard.Overview1.onOptionsItemSelected(Overview1.java:177)
    at android.app.Activity.onMenuItemSelected(Activity.java:2885)
    at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
    at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
    at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:674)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
    at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
    at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
    at android.view.View.performClick(View.java:4780)
    at android.view.View$PerformClick.run(View.java:19866)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at