2014-09-01 2 views
0

Я делаю простой браузер, и я пытаюсь сделать страницу избранных.Пытается начать новую деятельность и передать строку со списком ListActivity

До сих пор я создал класс HomePage, который имеет код:

package com.example.browser3; 

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.provider.Browser; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.inputmethod.InputMethodManager; 
import android.webkit.WebView; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

@SuppressLint("SetJavaScriptEnabled") 
// Indicates that Lint should ignore the specified warnings for the annotated 
// element. 
public class HomePage extends Activity implements OnClickListener { 

WebView ourBrow; // create a WebView object 
EditText url; // create an EditText object 
String theWebsite; 
String theHomePage; 


public String getTheHomePage() { 
    return theHomePage; 
} 


public void setTheHomePage(String theHomePage) { 
    this.theHomePage = theHomePage; 
} 






public String readFile(String fileName,String a){ 
    try { 
     InputStream in=openFileInput(fileName); 
     if(in!=null){ 
      InputStreamReader reader= new InputStreamReader(in); 
      BufferedReader buffreader= new BufferedReader(reader); 

      StringBuilder builder= new StringBuilder(); 
      String str; 
      while((str=buffreader.readLine())!=null){ 
       builder.append(str+ "\n"); 

       a= builder.toString(); 
      } 
      in.close(); 

     } 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return a; 

} 



    public void writeFile(String fileName, String x){ 

    try { 
     OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,MODE_APPEND)); 
     out.write(x+"\n"); 

     out.close(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 


@Override 
protected void onResume() { 
    ourBrow.loadUrl(theHomePage); 
super.onResume(); 
} 


@Override 
protected void onCreate(Bundle savedInstanceState) { // onCreate is called 
                 // in order to initialize(Start) 
                 // our activity. 
                 // 
                 // This is where 
                 // most 
                 // initialization 
                 // goes 
    super.onCreate(savedInstanceState); // Derived class onCreate(bundle) 
             // method must call super class 
             // implementation of this method. If 
             // you do not then an exception will 
             // be thrown SuperNotCalledException 
    setContentView(R.layout.fragment_main); // Set the activity content from 
              // a layout resource using 
              // findViewById to interact with 
              // widgets 

    ourBrow = (WebView) findViewById(R.id.wvBrowser); // finds the webView 
                 // identified in 
                 // fragment_main by 
                 // the id 
                 // "wvBrowser" 
    ourBrow.getSettings().setJavaScriptEnabled(true); // Enables JavaScript 
    ourBrow.getSettings().setLoadWithOverviewMode(true); // Zooms out the 
                  // page for easy 
                  // navigation 
    ourBrow.getSettings().setUseWideViewPort(true); // Allow us to set the 
                // normal view point. 
                // Not to be too small 
                // or too big for the 
                // screen 
    ourBrow.setWebViewClient(new ourViewClient()); // Overrides the 
                // emulator's browser 
                // because it can 
                // interfere with this 
                // one 
    try { 
     ourBrow.loadUrl(readFile("home.txt",theHomePage)); // We must throw and catch 
                // an exception for 
                // example when it 
                // cannot load because 
                // it doesn't have 
                // Internet 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    Button go = (Button) findViewById(R.id.bGo); // Set buttons from 
                // fragment_main with 
    Button menu= (Button) findViewById(R.id.bMenu);           // different IDs 
    Button back = (Button) findViewById(R.id.bBack); 
    Button forw = (Button) findViewById(R.id.bForward); 
    Button ref = (Button) findViewById(R.id.bRefresh); 


    url = (EditText) findViewById(R.id.tUrl); // Finds the text identified 
               // in fragment_main by the 
    menu.setOnClickListener(this);           // id "tUrl" 
    go.setOnClickListener(this); 
    back.setOnClickListener(this); 
    ref.setOnClickListener(this); // Registers a callback to be invoked when 
            // this view is clicked 
    forw.setOnClickListener(this); 

} 
private void clickHome(){ 
    startActivity(new Intent("com.example.browser3.MENU")); 
} 
@Override 
public void onClick(View v) { // This function is called when a view is 
           // clicked 
    switch (v.getId()) { // Used to identify the view by id 
    case R.id.bMenu: 
     clickHome(); 

    case R.id.bGo: 



     theWebsite = url.getText().toString(); // Returns the text 
                 // which textView is 
                 // displaying as an 
                 // identical String 
                 // in the variable 
                 // theWebsite 
     writeFile("history.txt", theWebsite); 

     ourBrow.loadUrl(theWebsite); // Loads the given Url, in our case 
             // (thewebsite) 
     InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); // We 
                             // set 
                             // up 
                             // our 
                             // inputManager 
     imm.hideSoftInputFromWindow(url.getWindowToken(), 0); // We use the 
                   // method 
                   // that will 
                   // hide our 
                   // keyboard 
     break; 
    case R.id.bBack: 
     if (ourBrow.canGoBack()) // Gets whether the WebView has a back 
            // history item 
      ourBrow.goBack(); // Goes back in the history of the WebView. 
     break; 
    case R.id.bForward: 
     if (ourBrow.canGoForward()) // Gets whether the WebView has a 
            // forward history item. 
      ourBrow.goForward(); // Goes forward in the history of the 
            // WebView. 
     break; 
    case R.id.bRefresh: 
     ourBrow.reload(); // Reloads the current URL. 
     break; 
    } 

} 


} 

и класс ListActivity с кодом:

package com.example.browser3; 

import java.util.ArrayList; 

import android.app.ListActivity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class Favorite2 extends ListActivity { 

String[] elements={"http://www.yahoo.com","http://www.facebook.com"}; 
ArrayAdapter<String> adapter; 
HomePage object=new HomePage(); 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setListAdapter(new ArrayAdapter<String>(Favorite2.this , android.R.layout.simple_list_item_1 , elements)); 
} 

protected void onListItemClick(ListView l, View v, int position, long id) { 
    super.onListItemClick(l, v, position, id); 

    try{ 
    Class ourClass = Class.forName("com.example.browser3.HomePage");// ce e aici aia porneste la click 
    Intent ourIntent = new Intent(Favorite2.this , ourClass); 
    String s=elements[position]; 
    object.ourBrow.loadUrl(s); 
    startActivity(ourIntent); 


      } 
    catch(ClassNotFoundException e){ 
     e.printStackTrace(); 
    } 
} 
} 

Все, что я хочу, когда я нажимаю один из ListActivity членов класса Favorite2, чтобы запустить операцию HomePage и взять имя, которое является строкой в ​​элементах массива String, и загрузить его в webview или просто ввести его в EditText с именем url. Может кто-нибудь мне помочь?

ответ

0

Добавить это как дополнительный, чтобы ваши намерения:

Intent ourIntent = new Intent(Favorite2.this , ourClass); 
ourIntent.putExtra("name", your_string); 
startActivity(ourIntent); 

А в вашей деятельности получить дополнительные и установить его на EditText:

url = (EditText) findViewById(R.id.tUrl); // Finds the text identified 
String name = getIntent().getStringExtra("name"); 
if (name != null) { 
    url.setText(name); 
} 
+0

, когда я получаю дополнительный, где я помещаю этот код? в новом методе или в onCreate? Я уже пробовал это раньше в новом методе, но я думаю, что я испортил. –

+0

@ PetrescuRadu-Tiberiu Вы можете получить дополнительные услуги в 'onCreate'. Как и в коде, который я показал, это делается после того, как вы нашли свое представление «EditText». – Simas

+0

, и если я добавлю его в метод onCreate, не будет ли он использовать его всякий раз, когда я открою домашнюю страницу? –

Смежные вопросы