简体   繁体   中英

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?

I am able to have a list view with results pulled from a mysql remote database depending on an input from a user with the code below. The last thing I need to do is add an Icon in the list view with a dynamic Icon coming from a URL for each result. I am trying to keep it within the same activity/java file. Does anyone know how to do this? If so, can you please edit my code to show the results? Thanks.

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

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();
}
}
}

Use the following code its working

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);
        }
        }


}

Define another class

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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