从mainActivity填充第二个Activity listview

时间:2015-02-12 20:47:28

标签: java android listview android-asynctask

我想在url下载数据时使用url在secondActivity中填充listview我尝试了不同的东西,但没有任何作用

MainActivity.java

    public class MainActivity extends ActionBarActivity {

private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textView;
SharedPreferences.Editor fd;
SharedPreferences FeedPref;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    urlText = (EditText) findViewById(R.id.myurl);
    textView = (TextView) findViewById(R.id.mytext);
    textView.setMovementMethod(ScrollingMovementMethod.getInstance());
    FeedPref=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    fd=FeedPref.edit(); 



}


public void  myClickHandler(View view) {




    // Gets the URL from the UI's text field.
    String stringUrl = urlText.getText().toString();
    ConnectivityManager connMgr = (ConnectivityManager) 
        getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {


        new DownloadWebpageTask().execute(stringUrl);

    } else {
        textView.setText("No network connection available.");
    }
}



 public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {



            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }


       // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);   
            if (result != null  )
            {
           FeedPref=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
           fd=FeedPref.edit();
         String url =urlText.getText().toString(); 
         fd.putString("urls", url);
         fd.commit(); }



       }
    }

 private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;


        try {
            URL url = new URL(myurl);
            HttpURLConnection connect = (HttpURLConnection) url.openConnection();
            connect.setReadTimeout(10000 /* milliseconds */);
            connect.setConnectTimeout(15000 /* milliseconds */);
            connect.setRequestMethod("GET");
            connect.setDoInput(true);
            // Starts the query
            connect.connect();
            int response = connect.getResponseCode();
            Log.d(DEBUG_TAG, "The response is: " + response);
            is = connect.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readIt(is);
            return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
        } finally {
            if (is != null) {
                is.close();
            } 
        }
 }

// Reads an InputStream and converts it to a String.
 public String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
     if (stream != null) {
         StringBuilder sb = new StringBuilder();
         String line;

         try {
             BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
             while ((line = reader.readLine()) != null) {
                 sb.append(line);
             }
         } finally {
             stream.close();
         }
         return sb.toString();
     } else {        
         return "";
     }
 }
 public void myClickHandler1(View povijest){
     Intent intent = new Intent(MainActivity.this, SecondActivity.class);
     startActivity(intent);      

 }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

secondactivity.java

package com.example.networking;

import java.util.ArrayList;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SecondActivity extends ActionBarActivity {
        String[] urls1;
        ListView listView;
        ArrayAdapter<String> adapter;
        SharedPreferences FeedPref;
        SharedPreferences.Editor fd;
        TextView txt1;



    protected void onCreate(Bundle savedInstanceState) {
        FeedPref=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String  urlsa=FeedPref.getString("urls",null);
          String[] values = new String[] {urlsa,};
          ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);



listView.setAdapter(adapter);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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.networking.MainActivity" >

    <EditText
        android:id="@+id/myurl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:inputType="textWebEmailAddress"
        android:ems="10" >

    </EditText>

    <TextView
        android:id="@+id/mytext"
        android:layout_width="200dp"
        android:layout_height="0dp"
        android:layout_marginLeft="38dp"
        android:layout_marginTop="40dp"
        android:layout_weight="0.17"
        android:scrollbars="vertical" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:onClick="myClickHandler1"
        android:text="POVIJEST" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="myClickHandler"
        android:text="Download" />

</LinearLayout>

activity_second.xml

<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.networking.SecondActivity" >

    <ListView
        android:id="@+id/lista"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>

</RelativeLayout>

修改 我尝试将sharedPrefrences与onPostExecute一起使用,但我不起作用。 所以我希望下载的每个ulr都保存到listview。

1 个答案:

答案 0 :(得分:0)

您需要以不同的方式将网址传递给第二个Activity。您不能指望操作系统调用您的自定义onCreate方法:

protected void onCreate(Bundle savedInstanceState, String urls)

它不知道。您可以通过以下几种方式之一传递URL数据:

  1. 通过Intent
  2. 使用SharedPreferences
  3. 将其保存为File
  4. 将它们存储在数据库中
  5. 最有可能你可以使用第一个或第二个。所有这些都有很多参考,所以我没有提供详细信息。

    编辑:

    例如,而不是:

     public void myClickHandler1(View povijest){
         Intent intent = new Intent(MainActivity.this, SecondActivity.class);
         startActivity(intent);      
    
     }
    

    这样做:

     public void myClickHandler1(View povijest){
         Intent intent = new Intent(MainActivity.this, SecondActivity.class);
         intent.putExtra("URL", urlText.getText().toString());
         startActivity(intent);      
    
     }
    

    然后像这样检索onCreate

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        list = (ListView) findViewById(R.id.lista);
        arrayList = new ArrayList<String>();
    
        // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
        // and the array that contains the data
        adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
        // Here, you set the data in your ListView
        list.setAdapter(adapter);
    
        arrayList.add(getIntent().getStringExtra("URL"));
    
        adapter.notifyDataSetChanged();
    }
    

    编辑2:

    您可以传递一个字符串数组。看看这篇文章:

    Passing String array between two class in android application

    您还可以使用分隔符(逗号,大括号等)然后解析它。或者使用JSON。

    您也可以将其中任何一项保存到SharedPreferences,然后在第二项活动中从SharedPreferences加载。