单击ListView将自己的值发送到另一个活动

时间:2017-01-18 08:54:18

标签: android listview android-activity

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变量中。 我在资源Activity中也遇到问题我想要搜索ListView但它不起作用。

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

2 个答案:

答案 0 :(得分:0)

有一个用于将此arraylist转换为str&amp; amp;反之亦然..可以使用..

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

现在您可以在适配器中传递此列表.. 请告诉我们是否需要更多帮助

答案 1 :(得分:0)

首先创建Json数组和数组列表

JSONArray id_array;

ArrayList product_id_list;

product_id_list = new ArrayList();

将ArrayList解析为JsonArray

id_array = new JSONArray(product_id_list);

现在您可以将List值作为String

获取