将值从按钮传递到listview

时间:2017-10-02 18:58:34

标签: java android

这是我想要的流程图:

上面的图像就像我想要创建的内容的流程图。我希望第一次使用10个左右的按钮进行活动

               case 0:

                    Intent intent = new Intent(getActivity(), AActivity.class);
                    intent.putExtra("categoryId", 1);
                    intent.putExtra("title", Animal);

                    startActivity(intent);

                    break;


                case 1:

                    Intent e = new Intent(getActivity(), AActivity.class);
                    e.putExtra("categoryId",  2);
                    e.putExtra("title", eletronics);

                    startActivity(e);


                    break;


                case 2:

                    Intent f = new Intent(getActivity(), AActivity.class);
                    f.putExtra("categoryId",  3);
                    f.putExtra("title", fashion);

                    startActivity(f);

                    break;


<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

include_once($_SERVER['DOCUMENT_ROOT']."/config/config.php");

 $id= $_POST['id'];

// Create connection
$conn = new mysqli($host, $user, $pass, $database);

if ($conn->connect_error) {

 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM comments where comment_id = '$id'" ;

$result = $conn->query($sql);

if ($result->num_rows >0) {


 while($row[] = $result->fetch_assoc()) {

 $tem = $row;

 $json = json_encode($tem);

 }

} else {
 echo "No Results Found.";
}
 echo $json;

$conn->close();
}
?>

我需要帮助创建第二个活动,该活动将在listview中从php接收并显示它。因此,如果单击按钮1,它将获取与id 1相关的所有数据

我的问题是我将如何实现第二个活动,它将从mysql获取值并将其显示为列表视图

1 个答案:

答案 0 :(得分:0)

这是我在我的应用程序中使用的那个,如果你可以使用它

package com.fruitmarket;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.utils.StorageUtils;

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

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import Config.ConstValue;
import adapters.ProductsAdapter;
import imgLoader.AnimateFirstDisplayListener;
import imgLoader.JSONParser;
import util.ConnectionDetector;
import util.ObjectSerializer;

@SuppressWarnings("deprecation")
@SuppressLint("NewApi") 

公共类ProductsActivity2扩展了ActionBarActivity {

public SharedPreferences settings;
public ConnectionDetector cd;
static ArrayList<HashMap<String, String>> products_array;
ProductsAdapter adapter;
ListView products_listview;
DisplayImageOptions options;
ImageLoaderConfiguration imgconfig;
ProgressDialog dialog;

TextView txtcount;

private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
HashMap<String, String>  catMap;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
    settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
    cd = new ConnectionDetector(getApplicationContext());

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_products);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
    cd=new ConnectionDetector(this);

    File cacheDir = StorageUtils.getCacheDirectory(this);
    options = new DisplayImageOptions.Builder()
    .showImageOnLoading(R.drawable.loading)
    .showImageForEmptyUri(R.drawable.loading)
    .showImageOnFail(R.drawable.loading)
    .cacheInMemory(true)
    .cacheOnDisk(true)
    .considerExifParams(true)
    .displayer(new SimpleBitmapDisplayer())
    .imageScaleType(ImageScaleType.NONE)
    .build();

    imgconfig = new ImageLoaderConfiguration.Builder(this)
    .build();
    ImageLoader.getInstance().init(imgconfig);

    ArrayList<HashMap<String,String>> categoryArray = new ArrayList<HashMap<String,String>>();
    try {
        categoryArray = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("categoryname", ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));      
    }catch (IOException e) {
            e.printStackTrace();
    }

    catMap = new HashMap<String, String>();
    catMap = categoryArray.get(getIntent().getExtras().getInt("position"));

    products_array = new ArrayList<HashMap<String,String>>();
    try {
        products_array = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("products_"+catMap.get("id"), ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));       
    }catch (IOException e) {
            e.printStackTrace();
    }

    products_listview = (ListView)findViewById(R.id.listView1);
    adapter = new ProductsAdapter(getApplicationContext(), products_array);
    products_listview.setAdapter(adapter);

    TextView txtTitle = (TextView)findViewById(R.id.catname);
    txtTitle.setText(catMap.get("name"));

    txtcount = (TextView)findViewById(R.id.textcount);


    products_listview.setOnItemClickListener(new OnItemClickListener() {

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

            try {
                settings.edit().putString(getString(R.string.productsActivity),ObjectSerializer.serialize(products_array.get(position))).commit();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Intent intent = new Intent(ProductsActivity2.this, ProductdetailActivity.class);
            intent.putExtra("position", position);
            startActivity(intent);

        }
    });


    new loadProductsTask().execute(true);




}
@Override
protected void onNewIntent(Intent intent) {

    handleIntent(intent);
}

private void handleIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (!query.equalsIgnoreCase("")) {
            //use the query to search your data somehow
            new loadProductsTask().execute(true);
        }
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.products, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    SearchManager searchManager =
            (SearchManager) getSystemService(Context.SEARCH_SERVICE);

    searchView.setSearchableInfo(
            searchManager.getSearchableInfo(getComponentName()));

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Intent intent = new Intent(ProductsActivity2.this,MainActivity.class);
        startActivity(intent);
    }
    else if(id==R.id.action_viewcart){
        //Intent intent = new Intent(ProductsActivity.this,ViewcartActivity.class);
        //startActivity(intent);

    }
    else if(id == android.R.id.home){
        finish();
    }
    return super.onOptionsItemSelected(item);
}


public class loadProductsTask extends AsyncTask<Boolean, Void, ArrayList<HashMap<String, String>>> {

    JSONParser jParser;
    JSONObject json;
    String count;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        // TODO Auto-generated method stub
        if (result!=null) {
            //adapter.notifyDataSetChanged();
        }   
        try {
            settings.edit().putString("products_"+catMap.get("id"),ObjectSerializer.serialize(products_array)).commit();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        txtcount.setText(count);
        adapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

    @Override
    protected void onCancelled(ArrayList<HashMap<String, String>> result) {
        // TODO Auto-generated method stub
        super.onCancelled(result);
    }


    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            Boolean... params) {
        // TODO Auto-generated method stub

        try {
            jParser = new JSONParser();

            if(cd.isConnectingToInternet())
            {
                String urlstring = ConstValue.JSON_PRODUCTS+"&id="+catMap.get("id");

                if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
                    String query = getIntent().getStringExtra(SearchManager.QUERY);
                    //use the query to search your data somehow
                    urlstring = urlstring + "&search="+query;
                }

                json = jParser.getJSONFromUrl(urlstring);
                count = json.getString("count");
                if (json.has("data")) {
                    if(json.get("data") instanceof JSONArray){
                        JSONArray jsonDrList = json.getJSONArray("data");
                        products_array.clear();
                        for (int i = 0; i < jsonDrList.length(); i++) {
                            JSONObject obj = jsonDrList.getJSONObject(i);
                            put_object(obj);
                        }
                    }else if(json.get("data") instanceof JSONObject){
                        put_object(json.getJSONObject("data"));
                    }
                }
            }else
            {
                Toast.makeText(ProductsActivity2.this,getString(R.string.internetconnection), Toast.LENGTH_LONG).show();
            }

            jParser = null;
            json = null;

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

                return null;
            }
        return null;
    }

    public void put_object(JSONObject obj){
        HashMap<String, String> map = new HashMap<String, String>();


        try {
        map.put("id", obj.getString("id"));
        map.put("title", obj.getString("title"));
        map.put("slug", obj.getString("slug"));
        map.put("description", obj.getString("description"));       
        map.put("image", obj.getString("image"));

        map.put("price", obj.getString("price"));
        map.put("currency", obj.getString("currency"));
        map.put("discount", obj.getString("discount"));
        map.put("cod", obj.getString("cod"));       
        map.put("emi", obj.getString("emi"));       
        map.put("status", obj.getString("status"));     

        map.put("gmqty", obj.getString("gmqty"));       
        map.put("unit", obj.getString("unit"));     
        map.put("deliverycharge", obj.getString("deliverycharge"));     
        map.put("tax", obj.getString("tax"));       
        map.put("category_id", obj.getString("category_id"));

        map.put("on_date", obj.getString("on_date"));

        map.put("stock", obj.getString("stock"));
        map.put("type", obj.getString("type"));
        map.put("total_qty_stock", obj.getString("total_qty_stock"));
        map.put("consume_qty_stock", obj.getString("consume_qty_stock"));

        products_array.add(map);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}