单击时显示视图(活动)中相关的数据

时间:2016-11-28 16:25:56

标签: java android arrays json button

我从我的Api获取我的Json对象/数组并将其打印到我的视图中, foreach数组我在我的MainActivity中打印id名称。

Foreach数组数据我创建了一个按钮。 我想转移到另一个Activity并显示当前数组的相关数据。

我的观点看起来像这样:

________________________
id     name      button      <- if one clicks on the button another activity shall show the description of it
________________________

我的主要问题是如何在另一项活动中显示相关数据。

我的MainActivity看起来像这样:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    private final static String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://192.168.178.58:8888/test";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        contactList = new ArrayList<>();

        new GetContacts().execute();

        lv = (ListView) findViewById(R.id.list);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    // Getting JSON Array node
                    JSONArray jsonArray = new JSONArray(jsonStr);

                    // looping through All Contacts
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject c = jsonArray.getJSONObject(i);

                        String id = c.getString("id");
                        String name = c.getString("name");
                        String description = c.getString("description");

                        // tmp hash map for single contact
                        HashMap<String, String> data = new HashMap<>();

                        // adding each child node to HashMap key => value
                        data.put("id", id);
                        data.put("name", name);
                        data.put("description", description);

                        // adding contact to contact list
                        contactList.add(data);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        /**
         * In onPostExecute() method the progress dialog is dismissed and the array list data is displayed in list view using an adapter.
         * @param result
         */
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item,
                    new String[]{"name", "description"},
                    new int[]{R.id.name, R.id.description});

            lv.setAdapter(adapter);
        }

    }

}

编辑:

这就是我的意图:

public void openDetails() { // button onclick name
   Intent myIntent = new Intent(MainActivity.this, DetailActivity.class);
    myIntent.putExtra("key", value);
    MainActivity.this.startActivity(myIntent);
}

2 个答案:

答案 0 :(得分:1)

通常,您可以使用单例在活动之间共享非原始数据。

这样的事,

master

然后在第一个活动中:

public class MyData {
  private Object data;
  public Object getData() {
   return data;
  }
  public void setData(Object data) {
   this.data = data;
  }

  private static final MyData myData = new MyData();
  public static MyData getInstance() {
   return myData;
  }
}

在第二个:

MyData.getInstance().setData(objToShare);

答案 1 :(得分:0)

您当前的实施并不知道点击了哪个按钮。所有按钮都将具有相同的点击事件。

解决方案 - 不要在ListView上放置按钮。只需点击&#34;行&#34;即可。

要开始此操作,您需要替换HashMap<String, String>的列表,以支持自定义POJO类。

请参阅 - Parcelable objects

public class Contact implements Parcelable {
    private String id, name, description;

    // TODO: Getters & setters
    // TODO: Actually implement Parcelable
}

然后,更新适配器。而不是SimpleAdapter

请参阅 - Custom Adapter

private ContactAdapter adapter; // Top of class
...
// onCreate
    contactList = new ArrayList<Contact>();
    lv = (ListView) findViewById(R.id.list);
    adapter = new ContactAdapter(MainActivity.this, contactList);
    lv.setAdapter(adapter); // Set this here, not in the AsyncTask
...
// doInBackground
    contactList.add(someContact);
    // adapter.add(someContact); // Can also do this
// onPostExecute
    adapter.notifyDataSetChanged(); // Refresh the adapter, don't lv.setAdapter again. 

你的AsyncTask

    // tmp object for single contact
    Contact c = new Contact();

    // adding each child node to object
    c.setID(id);
    c.setName(name);
    c.setDescription(description);

    // adding contact to contact list
    contactList.add(c);
如果您不想手动执行此操作,

Gson会有所帮助。 改造可以取代你的整个AsyncTask,但我会留给你研究。

现在,回到&#34;点击事件&#34;。
由于此Contact对象为Parcelable,因此您可以将其传递给Intent,就像其他任何内容一样。

// onCreate
    lv = (ListView) findViewById(R.id.list);
    // This is a click per-row
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {    
            Contact clicked = adapter.getItem(position);
            displayContact(clicked);  
        }
    });

我喜欢定义单独的方法来使代码更清晰。

private void displayContact(Contact c) {
    Intent intent = new Intent();
    intent.putExtra("contact", c);  // The piece you're looking for
    startActivity(intent);
}

从另一项活动中获取意图:

Contact c = getIntent().getExtras().getParcelable("contact");

参考 - Android: How to pass Parcelable object to intent and use getParcelable method of bundle?