当我按下一个按钮时,它应该从网页中检索数据并根据我的布局显示它。这样做很好,但只有当我单击返回时,才返回我的主要活动(家庭活动)并再次按下按钮。
我第一次按下按钮时加载需要很长时间,有时不起作用。但第二次是即时加载[工作正常]。
这是代码 - 三个类 - HomeActivity.java、News.Java 和 MyNewsHandler.java
public class HomeActivity extends Activity
{
String username = " ";
Button alog;
Button news;
Button forumTime;
EditText usernameEntry;
SharedPreferences preferences;
ImageView image;
TextView usernametv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
forumTime = (Button)findViewById(R.id.timeButton);
news = (Button) findViewById(R.id.newsButton); // <--- Heres the problem
alog = (Button) findViewById(R.id.alogButton);
usernameEntry = (EditText) findViewById(R.id.username);
//For news button
OnClickListener newsListener = new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(HomeActivity.this, News.class);
startActivity(intent);
}
};
//Attaching listeners
//forumTime.setOnClickListener(timeListener);
//alog.setOnClickListener(alogListener);
news.setOnClickListener(newsListener);
}
public void display(String string)
{
Toast.makeText(getBaseContext(), string, 300000).show();
}
}
public class MyNewsHandler extends DefaultHandler
{
private Boolean inTitle = false;
private Boolean inDescription = false;
private Boolean inItem = false;
private Boolean inCategory = false;
static public ArrayList<String> title = new ArrayList<String>(),
description = new ArrayList<String>(), category = new ArrayList<String>();
private StringBuilder buff = null;
// All methods auto called in this order - start, characters, end
/*
* Called when an xml tag starts
* imgView.setImageResource(R.drawable.newImage);
*/
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes)
{
if (inItem)
{
if (localName.equals("title"))
{
inTitle = true;
buff = new StringBuilder();
}
if (localName.equals("description"))
{
inDescription = true;
buff = new StringBuilder();
}
if (localName.equals("category"))
{
inCategory = true;
buff = new StringBuilder();
}
}
if (localName.equals("item"))
{
inItem = true;
}
}
/*
* Called when an xml tag ends
*/
@Override
public void endElement(String uri, String localName, String qName)throws SAXException
{
if (!inTitle && !inDescription && !inCategory)
{
inItem = false;
}
else
{
if (inTitle)
{
String check = buff.toString().trim();
title.add(check);
inTitle = false;
buff = null;
}
if (inDescription)
{
String check2 = buff.toString().trim();
String array [];
int index = 0;
if (check2.contains("/>"))
{
array = check2.split("/>");
index = check2.indexOf("10;");
description.add(array[array.length - 1].trim());
}
else description.add(check2);
//description.add(array[1]);
inDescription = false;
buff = null;
}
if(inCategory)
{
String check = buff.toString().trim();
category.add(check);
inCategory = false;
buff = null;
}
}
}
/*
* Called to get tag characters
*/
@Override
public void characters(char ch[], int start, int length)
{
if (buff != null)
{
for (int i = start; i < start + length; i++)
{
buff.append(ch[i]);
}
}
}
}
public class News extends ListActivity
{
String url;
TextView text1;
TextView text2;
static ImageView img;
// newsList contains the list items
static ArrayList<HashMap<String, Object>> newsList = new ArrayList<HashMap<String, Object>>();
// to store drawable id's
static HashMap<String, Integer> images = new HashMap<String, Integer>();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Load xml containing image view and a linear layout with 2 textviews
setContentView(R.layout.aloglistview);
img = (ImageView)findViewById(R.id.imageView2);
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
// url we are retrieving from
url = "http://services.runescape.com/m=news/latest_news.rss";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
String result = ""; // result of http Post
try
{
// Execute HTTP get Request
HttpResponse response = httpclient.execute(httpget);
// Extract the page content returned from the response
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
result = sb.toString(); // resulting content of the page
} catch (ClientProtocolException e)
{
Log.d("ERROR", "ClientProtocolException=" + e);
System.err.println("ClientProtocolException=" + e);
} catch (IOException e)
{
Log.d("ERROR", "IOException=" + e);
System.err.println("IOException=" + e);
}
try
{
//Parse the resulting page
Xml.parse(result, new MyNewsHandler());
} catch (SAXException e)
{
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
//needs to match formulate list thing
SimpleAdapter adapter = new SimpleAdapter(this, newsList,
R.layout.newsitem, new String[] { "Title", "Description", "Image"},
new int[] { R.id.textnews1, R.id.textnews2, R.id.imageView2});
populateList(); //Add all items to the newslist
setListAdapter(adapter);
}
public void populateList()
{
//Method to add to images hashmap
initMap();
//reset each time the list is populated
newsList = new ArrayList<HashMap<String, Object>>();
//Display 10 items
for (int i = 0; i < 11; i++)
{
HashMap<String, Object> temp = new HashMap<String, Object>();
String title = MyNewsHandler.title.get(i);
String category = MyNewsHandler.category.get(i);
//default drawable
int drawable = R.drawable.item;
//Match title text to hash keys to set correct image
for (Map.Entry<String, Integer> entry : images.entrySet())
{
String key = entry.getKey();
Object value = entry.getValue();
if(category.contains(entry.getKey()))
{
drawable = entry.getValue();
break;
}
else drawable = R.drawable.item;
}
temp.put("Title", title);
temp.put("Description", " " + MyNewsHandler.description.get(i));
temp.put("Image",drawable);
newsList.add(temp);
}
}
public void display(String string)
{
Toast.makeText(getBaseContext(), string, 1000202).show();
}
public void initMap()
{
images.put("Behind the Scenes News",R.drawable.behindthescenes);
images.put("Customer Support News",R.drawable.customerservice);
images.put("Game Update News",R.drawable.gameupdate);
images.put("Website News",R.drawable.devblog);
images.put("Technical News",R.drawable.technicalnews);
}
}
对不起,代码太长了..问题是它可以工作(哈..),但是当我第一次想要它时它不会立即加载。
它这样做:启动应用程序>点击新闻按钮>“不加载,空白屏幕”
但是当我这样做时它会起作用:启动应用程序>点击新闻按钮>回击>点击新闻按钮>“即时加载”
我遵循了一个建议,我在点击按钮之前进行了预解析,还做了另一次尝试,我完全摆脱了图像(认为这可能是延迟)。没有不同。仍然是相同的行为。
任何建议表示赞赏!