如何根据这些代码从包含使用列表视图的一个活动中将URL中的数据解析为另一个活动?

时间:2015-08-02 10:40:00

标签: android-listview

package list.of.products;



        import java.io.InputStream;
        import java.net.URL;
        import java.util.ArrayList;
        import java.util.List;
        import android.app.ListActivity;

        import android.content.Context;
        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.net.ConnectivityManager;
        import android.net.NetworkInfo;
        import android.os.AsyncTask;
        import android.os.Bundle;

        import android.view.View;

        import android.widget.AdapterView;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ImageView;
        import android.widget.ListView;
        import android.widget.ProgressBar;

        import android.widget.TextView;
        import android.widget.Toast;

        import com.example.huzy_kamz.halaalproject.MainActivity;
        import com.example.huzy_kamz.halaalproject.R;
        import com.example.huzy_kamz.halaalproject.halal.adapter.HalalAdapter;
        import com.example.huzy_kamz.halaalproject.halal.httpmanager.HttpManager;
        import com.example.huzy_kamz.halaalproject.halal.model.HalalModel;
        import com.example.huzy_kamz.halaalproject.halal.parser.HalalParser;

public class ListOfProducts extends ListActivity {

    private static final String PHOTOS_BASE_URL = "http://huxy.byethost15.com/Products/";
    public ListView ListOfProduct;
    TextView output;
    ProgressBar pb;
    List<MyTask> tasks;
    public ListView ListOfProducts;
    List<HalalModel> flowerList;

    private HalalAdapter adapter;
    public static HalalParser mUserClicked;



    // Search EditText
    EditText inputSearch;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listofproducts);


        //list view of the products
        ListOfProducts = (ListView) findViewById(android.R.id.list);
        Button list = (Button) findViewById(R.id.list);
        Button back =(Button)findViewById(R.id.back);

        ImageView imageView = (ImageView) findViewById(R.id.imageView1);
      //listview


        this.ListOfProduct =(ListView) this.findViewById(android.R.id.list);
        ListOfProduct.setAdapter(adapter);

        this.ListOfProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                try {

                   //please what can i put here according to  my codes



                    Intent i = new Intent(ListOfProducts.this,
                            Details.class);

                    startActivity(i);

                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }


            }
        });



    /* progress bar /
        pb = (ProgressBar) findViewById(R.id.progressBar);
        pb.setVisibility(View.INVISIBLE);

        tasks = new ArrayList<>();

    }




//back button


    public void Back(View v){
        Intent MainActivityIntent = new Intent(ListOfProducts.this, MainActivity.class);
        startActivity(MainActivityIntent);
        super.onBackPressed();

    }

    //button for fetching
    public void list(View view){

         try {
             // TODO Auto-generated method stub

             if (view.getId() == R.id.list) {
 // butto is requesting data from the url

                 if (isOnline()) {
                     requestData("http://huxy.byethost15.com/halal.php");


                 } else {
                     Toast.makeText(getApplicationContext(),
                             "Network isn't available", Toast.LENGTH_LONG)
                             .show();
                 }


             }
         }
         catch (Exception e){
             Toast.makeText(getApplicationContext(),
                     "Network isn't available", Toast.LENGTH_LONG)
                     .show();
         }
         }

    private void requestData(String uri) {
        MyTask task = new MyTask();
        task.execute(uri);
    }

    protected void updateDisplay() {
        // Use FlowerAdapter to display data
        HalalAdapter adapter = new HalalAdapter(this, R.layout.listofproducts,
                flowerList);
        setListAdapter(adapter);
    }

    protected boolean isOnline() {

//此方法显示网络连接             ConnectivityManager cm =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);             NetworkInfo netInfo = cm.getActiveNetworkInfo();             if(netInfo!= null&amp;&amp; netInfo.isConnectedOrConnecting()){                 返回true;             } else {                 返回false;             }         }

    private class MyTask extends AsyncTask<String, String, List<HalalModel>> {

        @Override
        protected void onPreExecute() {
            if (tasks.size() == 0) {
                pb.setVisibility(View.VISIBLE);
            }
            tasks.add(this);
        }

        @Override
        protected List<HalalModel> doInBackground(String... params) {

            String content = HttpManager.getData(params[0], "feeduser",
                    "feedpassword");
            flowerList = HalalParser.parseFeed(content);

            for (HalalModel product : flowerList) {
                try {
                    String imageUrl = PHOTOS_BASE_URL + product.getId();
                    InputStream in = (InputStream) new URL(imageUrl)
                            .getContent();
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    product.setBitmap(bitmap);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return flowerList;
        }

        @Override
        protected void onPostExecute(List<HalalModel> result) {

            tasks.remove(this);
            if (tasks.size() == 0) {
                pb.setVisibility(View.INVISIBLE);
            }

            if (result == null) {
                Toast.makeText(ListOfProducts.this, "Web service not available",
                        Toast.LENGTH_LONG).show();
                return;
            }

            flowerList = result;
            updateDisplay();

        }

    }

}




// another class HalalModel

package com.example.huzy_kamz.halaalproject.halal.model;

import android.graphics.Bitmap;

/**
 * Created by HUZY-KAMZ on 7/27/2015.
 */
public class HalalModel {

    private String Id;
    private String ProductName ;
    private String Pbox;
    public String Images;

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    private Bitmap bitmap;

    public String getId() {
        return Id;
    }

    public void setId(String id) {
        Id = id;
    }

    public String getProductName() {
        return ProductName;
    }

    public void setProductName(String productName) {
        ProductName = productName;
    }

    public String getPbox() {
        return Pbox;
    }

    public void setPbox(String pbox) {
        Pbox = pbox;
    }

    public String getImages() {
        return Images;
    }

    public void setImages(String images) {
        Images = images;
    }
}



// another class HalalParse
package com.example.huzy_kamz.halaalproject.halal.parser;

        import com.example.huzy_kamz.halaalproject.halal.model.HalalModel;

        import java.util.ArrayList;
        import java.util.List;

        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;





public class HalalParser {

    public static List<HalalModel> parseFeed(String content) {

        try {
            JSONArray ar = new JSONArray(content);
            List<HalalModel> flowerList = new ArrayList<>();

            for (int i = 0; i < ar.length(); i++) {

                JSONObject obj = ar.getJSONObject(i);
                HalalModel product = new HalalModel();


                product.setId(obj.getString("Id"));
                product.setProductName(obj.getString("ProductName"));
                product.setPbox(obj.getString("Pbox"));




                flowerList.add(product);
            }

            return flowerList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }
}

// another class HalalAdapter
package com.example.huzy_kamz.halaalproject.halal.adapter;


        import java.util.List;



        import android.app.Activity;
        import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ArrayAdapter;
        import android.widget.ImageView;
        import android.widget.TextView;

        import com.example.huzy_kamz.halaalproject.R;
        import com.example.huzy_kamz.halaalproject.halal.model.HalalModel;


public class HalalAdapter extends ArrayAdapter<HalalModel> {

    private Context context;
    private List<HalalModel> flowerList;

    public HalalAdapter(Context context, int resource, List<HalalModel> objects) {
        super(context, resource, objects);
        this.context = context;
        this.flowerList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.productslist, parent, false);

        //Display flower name in the TextView widget
        HalalModel product = flowerList.get(position);
        TextView tv = (TextView) view.findViewById(R.id.YOURTVID);
        TextView tv2 =(TextView) view.findViewById(R.id.price);
        tv.setText(product.getProductName());
        tv2.setText(product.getPbox());

        //Display flower photo in ImageView widget
        ImageView image = (ImageView) view.findViewById(R.id.imageView1);
        image.setImageBitmap(product.getBitmap());

        return view;
    }

}
// This is my HttpManager Class
package com.example.huzy_kamz.halaalproject.halal.httpmanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Base64;
import android.util.Log;

public class HttpManager {

    public static String getData(String uri) {

        BufferedReader reader = null;

        try {
            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

    }

    public static String getData(String uri, String userName, String password) {

        BufferedReader reader = null;
        HttpURLConnection con = null;

        byte[] loginBytes = (userName + ":" + password).getBytes();
        StringBuilder loginBuilder = new StringBuilder()
                .append("Basic ")
                .append(Base64.encodeToString(loginBytes, Base64.DEFAULT));

        try {
            URL url = new URL(uri);
            con = (HttpURLConnection) url.openConnection();

            con.addRequestProperty("Authorization", loginBuilder.toString());

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                int status = con.getResponseCode();
                Log.d("HttpManager", "HTTP response code: " + status);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

    }





    public JSONArray GetCustomerDetails(int CustomerID){

        String url = "http://huxykam.byethost31.com/cafe.php";
        HttpEntity httpEntity = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            httpEntity = httpResponse.getEntity();
        } catch (ClientProtocolException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        JSONArray jsonArray = null;
        if (httpEntity != null) {
            try {
                String entityResponse = EntityUtils.toString(httpEntity);
                Log.e("Entity Response", entityResponse);
                jsonArray = new JSONArray(entityResponse);

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }

        }

        return jsonArray;






    }

}

1 个答案:

答案 0 :(得分:0)

您在点击回调中获得的view参数是您为适配器中的项目构建的视图。因此,您可以使用TextView暂停view.findViewById(...)并以此方式获取数据 - 这样您就可以将其添加到您发送给其他活动的意图(intent.putExtra(...))< / p>

注意:我建议您查看适配器中使用的ViewHolder模式,以便系统可以回收您的视图。

ViewHolder模式非常简单,你可以从无数的地方获得,包括随SDK附带的Android样本。简短版本是:Android不会创建与适配器中的列表项一样多的视图。视图在引擎盖下被回收(重复使用)。但我们也需要允许它。您需要定义ViewHolder类(在适配器中):

public static class ViewHolder
{
    public TextView tv;
    public TextView tv2;
    public ImageView image;
}

将getView方法更改为:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate(R.layout.productslist, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.tv = (TextView)convertView.findViewById(R.id.YOURTVID);
        viewHolder.tv2 =(TextView)convertView.findViewById(R.id.price);
        viewHolder.image = (ImageView)convertView.findViewById(R.id.imageView1);
        convertView.setTag(viewHolder);
    }
    else {
        viewHolder = (ViewHolder)convertView.getTag();
    }
    //Display flower name in the TextView widget
    HalalModel product = flowerList.get(position);
    viewHolder.tv.setText(product.getProductName());
    viewHolder.tv2.setText(product.getPbox());
    viewHolder.image.setImageBitmap(product.getBitmap());

    return convertView;
}

根据您的原始请求,您可以访问您点击的数据,如下所示:

this.ListOfProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            //please what can i put here according to  my codes
            HalalAdapter.ViewHolder viewHolder = (ViewHolder)view.getTag();
            // access your data here:
            // viewHolder.tv
            // viewHolder.tv2
            // ...

            Intent i = new Intent(ListOfProducts.this, Details.class);
            startActivity(i);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
);