【问题标题】:click on ListView send own value into another activity单击 ListView 将自己的值发送到另一个活动
【发布时间】:2017-01-18 08:54:17
【问题描述】:

Resources.java

package com.synergywebdesigners.nima;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

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

import java.util.ArrayList;
import java.util.HashMap;
public class Resource extends AppCompatActivity {
    //List view
    private ListView lv;
    EditText inputSearch;
    ArrayAdapter<String> adapter;
    private String JSON_STRING;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resource);
        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        getJSON();
        registerForContextMenu(lv);
    }
    String products[] = {"India","Australia","America","SouthAfrica","WestIndia","Dubai"};
    ///showing message
    private void showResources(){
        JSONObject jsonObject = null;
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_RESULT);

            for(int i = 0; i<result.length(); i++){
                JSONObject jo = result.getJSONObject(i);
                String country = jo.getString(Config.TAG_COUNTRY);
                HashMap<String,String> resource = new HashMap<>();
                resource.put(Config.TAG_COUNTRY,country);
                list.add(resource);
            }

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

       final ListAdapter adapter = new SimpleAdapter(
                Resource.this, list, R.layout.list_resources,
                new String[]{Config.TAG_COUNTRY}, new int[]{R.id.resource_name});

      //  adapter = new ArrayAdapter<String>(this, R.layout.list_resources, R.id.resource_name, products);

       /* lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(Resource.this, TourismBoard.class);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("mylist",product);
                intent.putExtras(bundle);
                this.startActivity(intent);

            }
        });*/
        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                Resource.this.adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });
        lv.setAdapter(adapter);
    }
    private void getJSON() {
        class GetJSON extends AsyncTask<Void, Void, String> {

            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Toast.makeText(ChatActivity.this,"Your Message Fetching..",Toast.LENGTH_LONG).show();
                loading = ProgressDialog.show(Resource.this, "Showing Message", "Please Wait...", false, false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showResources();
            }

            @Override
            protected String doInBackground(Void... params) {
                ReuestHandler rh = new ReuestHandler();
                String s = rh.sendGetRequest(Config.URL_GET_ALL_RESOURCES);
                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();

    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Choose Your Category");
        menu.add(0, v.getId(), 0, "TOURISM BOARD");//groupId, itemId, order, title
        menu.add(0, v.getId(), 0, "MICE");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item){
        if(item.getTitle()=="TOURISM BOARD"){
            Toast.makeText(getApplicationContext(),"Wlcome To NIMA Tourism Board",Toast.LENGTH_LONG).show();
            Intent tourism = new Intent(getApplicationContext(),TourismBoard.class);
            startActivity(tourism);
        }
        else if(item.getTitle()=="MICE"){
            Toast.makeText(getApplicationContext(),"Mice Details",Toast.LENGTH_LONG).show();
        }else{
            return false;
        }
        return true;
    }
}

TourismBoard.java

package com.synergywebdesigners.nima;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

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

import java.util.ArrayList;
import java.util.HashMap;

public class TourismBoard extends AppCompatActivity {
    private ListView listView;
    private String JSON_STRING;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tourism_board);
        listView = (ListView) findViewById(R.id.list_tourism);
        getJSON();

    }
    ///showing message
    private void showMesage(){
        JSONObject jsonObject = null;
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_TOURISM);

            for(int i = 0; i<result.length(); i++){
                JSONObject jo = result.getJSONObject(i);
                String detail = jo.getString(Config.TAG_DETAIL);
                HashMap<String,String> tourism = new HashMap<>();
                tourism.put(Config.TAG_DETAIL,detail);
                list.add(tourism);
            }

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

        ListAdapter adapter = new SimpleAdapter(
                TourismBoard.this, list, R.layout.layout_tourism, new String[]{Config.TAG_DETAIL}, new int[]{R.id.tourism});

        listView.setAdapter(adapter);
    }
    private void getJSON() {
        class GetJSON extends AsyncTask<Void, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                 Toast.makeText(TourismBoard.this,"Your List has been Come Please Wait ...",Toast.LENGTH_LONG).show();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                JSON_STRING = s;
                showMesage();
            }

            @Override
            protected String doInBackground(Void... params) {
                ReuestHandler rh = new ReuestHandler();
                String s = rh.sendGetRequest(Config.URL_GET_ALL_TOURISM+"india");
                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }
}

我想将ListView 的数据发送到TourismActivity.java

但我已将这个值放入 String variable 中。 而且我在资源Activity 中也有一个问题,我想让ListView 可搜索,但它不起作用。

请告诉我我是如何解决这个问题的。

【问题讨论】:

  • 你想如何将数据传递给另一个活动?,当你点击 ListView 中的任何项目然后新活动应该开始并且你想要那个值时,是否有任何特定条件?这是实现 ListView 搜索功能的基本教程,androidhive.info/2012/09/…
  • 我希望在单击列表时将该值显示到另一个活动中
  • 致命异常:主进程:com.synergywebdesigners.nima,PID:30604 java.lang.ClassCastException:java.util.HashMap 无法在 com.synergywebdesigners.nima 中转换为 java.lang.String。资源$1.onItemClick(Resource.java:74)

标签: android listview android-activity


【解决方案1】:

有一个库可以将此数组列表转换为 str 或反之亦然..可以使用..

compile 'com.google.code.gson:gson:2.4'

然后为您的资源活动中的列表视图的项目单击添加此内容.. 用于将 arraylist 作为字符串发送到其他类

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //To Convert ArrayList in the string.

                Type listType= new TypeToken<List<HashMap<String,String>>>() {
                }.getType();
                String str = new Gson().toJson(list, listType);

                Intent tourism = new Intent(this,TourismBoard.class);
                tourism.putExtra("list",str);
                startActivity(tourism);
            }
        });

同时从其他活动中接收

    // Receiving the string as string extra
    String str = getIntent().getStringExtra("list");

   // Define a type for the string that which kind of data the string have
    Type listType = new TypeToken<List<HashMap<String, String>>>() {}.getType();

    //Converting the string in arraylist with that type define
    ArrayList<HashMap<String, String>> requiredList = new Gson().fromJson(str, listType);

现在您可以在您的适配器中传递此列表.. 如果需要更多帮助,请告知

【讨论】:

    【解决方案2】:

    首先创建Json数组和数组List

    JSONArray id_array;

    ArrayList product_id_list;

    product_id_list = new ArrayList();

    将ArrayList解析成JsonArray

    id_array = new JSONArray(product_id_list);

    现在您可以将 List 值作为字符串获取

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 2018-12-05
      相关资源
      最近更新 更多