繁体   English   中英

从我的Android Java代码示例中,如何将动态ICON添加到来自URL和远程服务器的列表视图中?

[英]From my Android Java Code example How do I add a dynamic ICON to the List View that comes from a URL and remote server?

我能够有一个列表视图,其结果取决于从用户使用以下代码的输入而从mysql远程数据库中提取的结果。 我需要做的最后一件事是在列表视图中添加一个图标,并为每个结果添加一个来自URL的动态图标。 我试图将其保留在相同的activity / java文件中。 有谁知道如何做到这一点? 如果是这样,您可以编辑我的代码以显示结果吗? 谢谢。

'================================================= ========

package com.packagename;
import android.app.ListActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Users extends ListActivity {
InputStream is;
ArrayList<String> results = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = "";
String uv = "";
uv = getIntent().getExtras().getString("dated");
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year",uv));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/Android53D6E3B5KF83S/users.php");
httppost.setEntity(new
UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
Toast.makeText(getApplicationContext(),"failed"+e.toString(), Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) 
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e)
{
Log.e("log_tag", "Error converting result"+e.toString());
Toast.makeText(getApplicationContext(),"failed"+e.toString(), Toast.LENGTH_SHORT).show();
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
json_data = jArray.getJSONObject(i);
results.add((String) json_data.get("id") + " "+ json_data.get("name")+ " " + json_data.get("sex")+ " " + json_data.get("birthyear"));
}
setListAdapter(new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,results));
ListView lv; lv = getListView(); lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View name, int id, long resultsb) {
Toast.makeText(getApplicationContext(), " (Selection #" + resultsb +") ", Toast.LENGTH_SHORT).show();
}});
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(),"No Entries", Toast.LENGTH_SHORT).show();
}
}
}

使用以下代码可以正常工作

public class ImageActivity extends Activity {

    private  int SIMPLE_NOTFICATION_ID ;

    public DefaultHttpClient DefaultHttpClient;


    private ImageView imageView;

    protected String url;


    /** Called when the activity is first created. */

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        imageView =(ImageView)findViewById(R.id.img);
         url = "http://website.com/Android53D6E3B5KF83S/users.php";

        BitmapFactory.Options bmOptions;
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;     
        DownloadImagesTask imageLoader=new DownloadImagesTask();
        imageLoader.execute();
    }

Handler handler=new Handler(){

    private Bitmap bmp;
    private Intent notificationIntent;
    private PendingIntent pendingIntent;
    private NotificationManager mNotificationManager;
    private Notification mNotification;

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        Context mContext=getApplicationContext();
        switch(msg.what){
        case 0:InputStream inputStream = null;
        URL urls=null;
        try {
            urls = new URL(url);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URLConnection conn=null;
        try {
            conn = urls.openConnection();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try{
            HttpURLConnection httpConn = (HttpURLConnection)conn;
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
            BitmapFactory.Options options;
            options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            bmp = BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();

        }
        catch (Exception e){
            e.printStackTrace();
        }
        case 1:mNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        mNotification=new Notification(R.drawable.icon,"started",System.currentTimeMillis());
        notificationIntent= new Intent(ImageActivity.this, Notifications.class);
        pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
        mNotification.setLatestEventInfo(getApplicationContext()," started", " started ", pendingIntent);
        mNotificationManager.notify(1,mNotification);
        imageView.setImageResource(R.drawable.icon);                   
        break;

        case 2:mNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        mNotification=new Notification(R.drawable.icon,"ended",System.currentTimeMillis());
        notificationIntent = new Intent(ImageActivity.this, Notifications.class);
        pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
        mNotification.setLatestEventInfo(ImageActivity.this, "completed", " completed ", pendingIntent);
        mNotificationManager.notify(1,mNotification);
        imageView.setImageBitmap(bmp);
        break;
        }
    }
};

    public class DownloadImagesTask extends AsyncTask<ImageView, Integer, ImageView> {

        @Override
        protected ImageView doInBackground(ImageView... params) {
            // TODO Auto-generated method stub
            handler.sendEmptyMessage(0);
            return null;
        }
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            handler.sendEmptyMessage(1);                        
        }

        @Override
        protected void onPostExecute(ImageView result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            handler.sendEmptyMessage(2);
        }
        }


}

定义另一个类

public class Notifications extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM