Java 从MainActivity填充第二个活动列表视图
我想用url填充secondActivity中的listview当url中的数据被下载时,我尝试了不同的方法,但没有任何效果 MainActivity.javaJava 从MainActivity填充第二个活动列表视图,java,android,listview,android-asynctask,Java,Android,Listview,Android Asynctask,我想用url填充secondActivity中的listview当url中的数据被下载时,我尝试了不同的方法,但没有任何效果 MainActivity.java public class MainActivity extends ActionBarActivity { private static final String DEBUG_TAG = "HttpExample"; private EditText urlText; private TextView textView; Sh
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;
}
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);
}
}
公共类MainActivity扩展了ActionBarActivity{
私有静态最终字符串DEBUG_TAG=“HttpExample”;
私人编辑文本;
私有文本视图文本视图;
编辑器fd;
共享参考FeedPref;
@凌驾
创建时受保护的void(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.GetDefaultSharedReferences(getBaseContext());
fd=FeedPref.edit();
}
公共作废myClickHandler(视图){
//从UI的文本字段获取URL。
字符串stringUrl=urlText.getText().toString();
ConnectivityManager connMgr=(ConnectivityManager)
getSystemService(Context.CONNECTIVITY\u服务);
NetworkInfo NetworkInfo=connMgr.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isConnected()){
新建下载WebPagetAsk().execute(stringUrl);
}否则{
setText(“没有可用的网络连接”);
}
}
公共类下载WebPagetTask扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串…URL){
//params来自execute()调用:params[0]是url。
试一试{
返回下载URL(URL[0]);
}捕获(IOE异常){
return“无法检索网页。URL可能无效。”;
}
}
//onPostExecute显示异步任务的结果。
@凌驾
受保护的void onPostExecute(字符串结果){
setText(结果);
如果(结果!=null)
{
FeedPref=PreferenceManager.GetDefaultSharedReferences(getBaseContext());
fd=FeedPref.edit();
字符串url=urlText.getText().toString();
putString(“url”,url);
fd.commit();}
}
}
私有字符串下载URL(字符串myurl)引发IOException{
InputStream=null;
试一试{
URL=新URL(myurl);
HttpURLConnection connect=(HttpURLConnection)url.openConnection();
connect.setReadTimeout(10000/*毫秒*/);
setConnectTimeout(15000/*毫秒*/);
connect.setRequestMethod(“GET”);
connect.setDoInput(true);
//启动查询
connect.connect();
int response=connect.getResponseCode();
Log.d(DEBUG_标记,“响应为:”+response);
is=connect.getInputStream();
//将InputStream转换为字符串
字符串contentAsString=readIt(is);
返回contentAsString;
//确保在应用程序启动后关闭InputStream
//用完了。
}最后{
如果(is!=null){
is.close();
}
}
}
//读取InputStream并将其转换为字符串。
公共字符串readIt(InputStream流)引发IOException,UnsupportedEncodingException{
if(流!=null){
StringBuilder sb=新的StringBuilder();
弦线;
试一试{
BufferedReader=新的BufferedReader(新的InputStreamReader(流,“UTF-8”));
而((line=reader.readLine())!=null){
某人附加(行);
}
}最后{
stream.close();
}
使某人返回字符串();
}否则{
返回“”;
}
}
公共作废myClickHandler1(查看povijest){
意向意向=新意向(MainActivity.this,SecondActivity.class);
星触觉(意向);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
}
secondactivity.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;
}
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);
}
}
package com.example.networking;
导入java.util.ArrayList;
导入android.support.v7.app.ActionBarActivity;
导入android.content.Context;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.os.Bundle;
导入android.preference.PreferenceManager;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.ArrayAdapter;
导入android.widget.ListView;
导入android.widget.TextView;
公共类SecondActivity扩展了ActionBarActivity{
字符串[]urls1;
列表视图列表视图;
阵列适配器;
共享参考FeedPref;
编辑器fd;
TextView txt1;
创建时受保护的void(Bundle savedInstanceState){
FeedPref=PreferenceManager.GetDefaultSharedReferences(getBaseContext());
字符串urlsa=FeedPref.getString(“URL”,null);
字符串[]值=新字符串[]{urlsa,};
ArrayAdapter=新的ArrayAdapter(这个,android.R.layout.simple_list_item_1,android.R.id.text1,值);
setAdapter(适配器);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.second,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
if(id==R.id.action\u设置){
返回true;
protected void onCreate(Bundle savedInstanceState, String urls)
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);
}
@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();
}