我正在开发一个需要访问网站以获取数据的应用程序,并将在设备上显示该数据。我想在后台从 Internet 获取数据并在检索数据时显示 ProgressDialog ...
但是当我运行它时,它不会显示任何内容,包括布局,因为后台从网络检索数据......请提供任何帮助
package com.hive.listviewimgtext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import static com.hive.listviewimgtext.Contants.XML_URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
;
public class CustomizedListView extends Activity {
private int e2;
public static final String KEY_SONG = "song";
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_ARTIST = "artist";
public static final String KEY_DURATION = "duration";
public static final String KEY_IMG_URL = "thumb_url";
public ArrayList<HashMap<String, String>> songlist;
public LazyAdapter adapter;
public ListView lv;
public LinearLayout linlaHeaderProgress;
AsyncTask<Void, Void, Void> ast;
@TargetApi(9)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customized_list_view);
linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
linlaHeaderProgress.setVisibility(View.VISIBLE);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
lv = (ListView)findViewById(R.id.list);
songlist = new ArrayList<HashMap<String,String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
String lol = ((TextView)view.findViewById(R.id.rowid)).getText().toString();
Toast.makeText(getApplicationContext(), lol, Toast.LENGTH_LONG).show();
Intent _intent = new Intent(getApplicationContext(),jsonactivity.class);
startActivity(_intent);
}
});
Log.d("Reach", "I don reach here");
ast = new AsyncTask<Void, Void, Void>(){
protected void onPreExecute() {
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable(){
@TargetApi(9)
public void run() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String xml = getXmlFromUrl("http://api.androidhive.info/music/music.xml");
if(xml.isEmpty()){
dialogConnection();
}else{
Document doc = getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_SONG);
for(int i = 0;i < nl.getLength();i++){
Element e = (Element) nl.item(i);
HashMap<String, String> maps = new HashMap<String, String>();
maps.put(KEY_ID, getValue(e, KEY_ID));
maps.put(KEY_TITLE, getValue(e, KEY_TITLE));
maps.put(KEY_ARTIST, getValue(e, KEY_ARTIST));
maps.put(KEY_DURATION,getValue(e, KEY_DURATION));
maps.put(KEY_IMG_URL, getValue(e, KEY_IMG_URL));
songlist.add(maps);
}
adapter = new LazyAdapter(CustomizedListView.this, songlist);
}
}else{
dialogConnection();
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
});
return null;
}
protected void onPostExecute(Void unused){
lv.setAdapter(adapter);
linlaHeaderProgress.setVisibility(View.GONE);
}
};
//ast.execute(null,null,null);
}
@SuppressWarnings("deprecation")
private void dialogConnection(){
AlertDialog alertDialog = new AlertDialog.Builder(
CustomizedListView.this).create();
alertDialog.setTitle("No Connection");
alertDialog.setMessage("No Internet Connection");
alertDialog.setButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
ast.execute(null,null,null);
}
});
alertDialog.show();
}
private String getValue(Element item, String key){
NodeList n = item.getElementsByTagName(key);
return getElementValue(n.item(0));
}
private final String getElementValue(Node elem){
Node child;
if(elem != null){
if(elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling()){
if(child.getNodeType() == Node.TEXT_NODE){
return child.getNodeValue();
}
}
}
}
return "";
}
private Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
doc.getDocumentElement().normalize();
} catch (Exception e) {
e2 = Log.e("Error : ", e.getMessage());
return null;
}
return doc;
}
private String getXmlFromUrl(String pointer){
String xml = null;
InputStream is = null;
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(pointer);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
String line;
StringBuffer response = new StringBuffer();
try {
BufferedReader br = new
BufferedReader(new InputStreamReader(is));
while((line = br.readLine() )!= null){
response.append(line);
}
} catch (Exception e) {
dialogConnection();
}
xml = response.toString();
Log.d("oh oh", "The response is: " + xml);
} else {
dialogConnection();
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
return xml;
}
}
我的布局
<LinearLayout 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:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cool Stuff"
/>
<LinearLayout
android:id="@+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="@+id/pbHeaderProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ProgressBar>
</LinearLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/list"
android:listSelector="@drawable/gradient_bg_hover"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
/>
</LinearLayout>
LazyAdapter.java
package com.hive.listviewimgtext;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d){
activity = a;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int pos) {
return pos;
}
public long getItemId(int pos) {
return pos;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if(convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title);
TextView artist = (TextView)vi.findViewById(R.id.artist);
TextView duration = (TextView)vi.findViewById(R.id.duration);
TextView rowid = (TextView)vi.findViewById(R.id.rowid);
ImageView list_image = (ImageView)vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
title.setText(song.get(CustomizedListView.KEY_TITLE));
rowid.setText(song.get(CustomizedListView.KEY_ID));
artist.setText(song.get(CustomizedListView.KEY_ARTIST));
duration.setText(song.get(CustomizedListView.KEY_DURATION));
ImageLoader il = new ImageLoader(activity.getApplicationContext());
il.DisplayImage(song.get(CustomizedListView.KEY_IMG_URL), list_image);
return vi;
}
}