java - 如何使用 onclick 函数从 MYSQL 加载的 ListView 传递值?

标签 java android mysql json listview

我在使用 JSON 从 MYSQL 数据库填充的 ListView 传递值时遇到了麻烦,该数组使用 for 循环填充,并且我无法使用该值将代码传递给另一个 Activity 。这是代码:

public class SubCategoria extends  ActionBarActivity {

String myJSON;

private static final String TAG_RESULTS="result";
private static final String TAG_ID = "codigo";
private static final String TAG_NAME = "nombre";
String codcat;
public static final String BITMAP_ID = "BITMAP_ID";

JSONArray peoples = null;

ArrayList<HashMap<String, String>> personList;

ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sub_categoria);
    list = (ListView) findViewById(R.id.listView);
    personList = new ArrayList<HashMap<String,String>>();
    getData();

    Intent i = getIntent();
    Bundle a =i.getExtras();

    String dato=(String) a.get("DATO1");
    switch(dato) {
        case "1":
            codcat = "1";
            break;
        case "2":
            codcat = "2";
            break;
        case "3":
            codcat = "3";
            break;
        case "4":
            codcat = "4";
            break;
        case "5":
            codcat = "5";
            break;

        case "6":
            codcat = "6";
            break;

        case "7":
            codcat = "7";
            break;
    }

   /* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView adapterView, View view, int i, long l) {
            Toast.makeText(getApplicationContext(), "posicion " + (i+1), Toast.LENGTH_SHORT).show();
        }
    });*/
}

protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String codigo = c.getString(TAG_ID);
            String nombre = c.getString(TAG_NAME);
            HashMap<String,String> persons = new HashMap<String,String>();

            persons.put(TAG_ID,codigo);
            persons.put(TAG_NAME, nombre);
            personList.add(persons);
        }

        ListAdapter adapter = new SimpleAdapter(
                SubCategoria.this, personList, R.layout.list_item,
                new String []{TAG_ID,TAG_NAME},
                new int[]{R.id.id, R.id.name}

        );

        list.setAdapter(adapter);

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

}

public void getData(){
    class GetDataJSON extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://www.cqbo.cl/get-sc.php?codcat="+codcat);

            // Depends on your web service
            httppost.setHeader("Content-type", "application/json");

            InputStream inputStream = null;
            String result = null;
            try {
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (Exception e) {
                // Oops
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result){
            myJSON=result;
            showList();
        }
    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}}

在代码中,我确实这样写:

/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView adapterView, View view, int i, long l) {
            Toast.makeText(getApplicationContext(), "posicion " + (i+1), Toast.LENGTH_SHORT).show();
        }
    });*/

但是我无法获得任何表单来将子类别代码传递到我想要的其他 Activity 。

如果理解我的问题有点棘手,我提前表示歉意!我的英文很差。非常感谢。

最佳答案

有 CursorAdapter 可以直接从 sqlite 扩展 ListView。您可以考虑使用更强大的工具进行 Rest 查询 - Retrofit 和 RxJava - 请参阅 How to consume this JSON structure via Retrofit 2?

关于java - 如何使用 onclick 函数从 MYSQL 加载的 ListView 传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38019614/

相关文章:

android - 缩放位图的 native sdk 函数?

java - 尝试使用 android SDK 运行 "Panic"程序时出现 "Hello world"错误

Java (Maven) 控制台应用程序。如何将其与 JRE bundle 在一起?

java - 来自 Amazon Web Services 的 Android 移动推送应用程序示例

java - 询问 ZonedDateTime 是否在标准时间或夏令时 (DST)

android - Firebase 云消息传递错误 : Couldn't resolve host 'fcm.googleapis.com'

python - sqlalchemy + flask ,按天获取所有帖子

MySQL 修改表

php - Laravel Collection::toArray() 触发额外的数据库查询

java - Hadoop名称节点secondarynode突然停止