Miguelct Posted June 4, 2013 at 12:11 AM Report #510804 Posted June 4, 2013 at 12:11 AM Boas pessoal. Não sou programador mas estou a fazer um projeto no Eclipse para Android e gostava de saber se é possível passar a informação de uma listview para outra em layouts diferentes. Na listview principal já tenho os itens da base de dados phpmyadmin e agora precisava de enviar esses dados (só os selecionados) para outra listview. É possível? Se sim, como? Obrigado desde já.
KTachyon Posted June 4, 2013 at 12:50 AM Report #510806 Posted June 4, 2013 at 12:50 AM (edited) Acredito que os layouts estejam em Activities diferentes, certo? Tens que passar os dados seleccionados para a segunda Activity. Na Activity onde estão os dados, colocas os seleccionados num ArrayList (os objectos que lá colocado têm que ser subclasses da classe Parcelable) e colocas num Bundle, que colocas num Intent: Intent i = new Intent(); Bundle b = new Bundle(); b.putParcelableArrayList("selectedList", list); i.putExtras(b); Fazes o push desse Intent com a nova Activity e, nessa nova Activity: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle b = this.getIntent().getExtras(); this.selectedList = b.getParcelableArrayList("selectedList"); // etc… } Não é necessário que utilizes mesmo um ArrayList para fazeres isto. Tudo depende da tua implementação. Podes ver que alternativas tens se recorreres à documentação do Bundle. Edited June 4, 2013 at 12:55 PM by KTachyon “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
Miguelct Posted June 4, 2013 at 11:56 AM Author Report #510888 Posted June 4, 2013 at 11:56 AM (edited) Sim, estão em activities diferentes. Saquei um jasontutorial da net para me fazer a ligação da base de dados para a app e alterei o que precisei para funcionar na minha app, mas não o consigo entender muito bem já que não percebo muito de java. Não sei porquê que não tem a lista daclarada pela id. Envio o código da minha lista: package com.anonimo.json; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.pxr.tutorial.xmltest.R; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import android.view.View.onclickListener; public class TelaMenu extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.telamenu); ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); JSONObject json = JSONfunctions.getJSONfromURL("http://.../Android/produtos.php?"); try{ JSONArray earthquakes = json.getJSONArray("produtos"); for(int i=0;i<earthquakes.length();i++){ HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = earthquakes.getJSONObject(i); map.put("id", e.getString("id_produto")); map.put("produto", e.getString("produto") + " " + e.getString("preco") + "€"); map.put("categoria", e.getString("categoria")); mylist.add(map); } }catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); } ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, new String[] { "produto", "categoria" }, new int[] { R.id.item_title, R.id.item_subtitle }); setListAdapter(adapter); final ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { @SuppressWarnings("unchecked") HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position); Toast.makeText(TelaMenu.this, "Produto'" + o.get("produto") + "' Adicionado ao Pedido.", Toast.LENGTH_SHORT).show(); //devo inserir aqui a ligação não é? } }); Button btMain = (Button) findViewById(R.id.btvoltar); Button btPedido = (Button) findViewById(R.id.btverpedido); btPedido.setonclickListener(new onclickListener() { @Override public void onclick(View v) { startActivity(new Intent(TelaMenu.this, TelaPedido.class)); finish(); } }); btMain.setonclickListener(new onclickListener() { @Override public void onclick(View view) { startActivity(new Intent(TelaMenu.this, TelaPrincipal.class)); finish(); } }); } } Edited June 4, 2013 at 12:42 PM by KTachyon GeSHi
KTachyon Posted June 4, 2013 at 12:58 PM Report #510905 Posted June 4, 2013 at 12:58 PM Eu diria para esqueceres a base de dados. Tu estás a aceder a um endpoint que te permite ir buscar os dados em formato JSON. A base de dados é uma camada que a tua aplicação nem sequer vê. A única coisa que tens que saber é como trabalhar os dados que recebes. A ideia é bastante simples. Quando tencionas mudar para a nova Activity, pegas nos dados que interessam para essa nova Activity e enfia-los num Bundle. Do outro lado vais buscar o Bundle, retiras os dados e montas o resto da view. No teu caso, visto que estás a trabalhar os dados em JSON até pode ser bastante mais simples que andar a criar subclasses da Parcelable para poderes transportar o ArrayList no Bumdle. Basta pegares no JSON que te interessa e passares como String para o Bundle. Bundle b = new Bundle(); b.putString("jsonObject", jsonObject.toString()); E, do outro lado voltas a criar o objecto a partir da String. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
Miguelct Posted June 4, 2013 at 05:20 PM Author Report #511005 Posted June 4, 2013 at 05:20 PM Desculpa se estou a abusar mas não sei muito bem onde inserir o código e se preciso de mais alguma coisa. Não seria possível colocares no meu código, o Bundle da mensagem anterior? O mesmo se passa com o criar na outra activiti o objecto a partir da String. Código java da outra activiti: package com.anonimo.json; import com.pxr.tutorial.xmltest.R; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.Button; import android.view.View.onclickListener; public class TelaPedido extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.telapedido); Button btMain = (Button) findViewById(R.id.btirmenu); btMain.setonclickListener(new onclickListener() { @Override public void onclick(View view) { startActivity(new Intent(TelaPedido.this, TelaMenu.class)); finish(); } }); } }
KTachyon Posted June 4, 2013 at 05:52 PM Report #511027 Posted June 4, 2013 at 05:52 PM Não é assim tão difícil… Tu sabes quando é que queres lançar a Activity. Tens lá uma linha assim: startActivity(new Intent(TelaPedido.this, TelaMenu.class)); Portanto: Intent i = new Intent(); Bundle b = new Bundle(); b.putString("selectedJSON", json_a_ser_enviado_para_a_proxima_activity); i.putExtras(b); i.setClass(TelaPedido.this, TelaMenu.class); startActivity(i); “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
Miguelct Posted June 5, 2013 at 11:57 AM Author Report #511124 Posted June 5, 2013 at 11:57 AM Só tenho mais uma dúvida. Preciso de saber como passar os dados desta última lista para uma lista final (em activities diferentes) através de um botão e como o receber na lista final. A finalidade desta app é ter um layout Menu onde tem a lista principal, enviar os dados seleccionados para um layout Pedido e nesse layout ter um botão para confirmar o pedido enviando os dados para o layout Pedidos final que o administrador poderá ver.
KTachyon Posted June 5, 2013 at 12:08 PM Report #511129 Posted June 5, 2013 at 12:08 PM Essa é a tua dúvida inicial e a resposta continua a ser a mesma. Crias um Bundle e passas para a nova Activity... “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
Miguelct Posted June 24, 2013 at 12:33 PM Author Report #514710 Posted June 24, 2013 at 12:33 PM Obrigado pelo esclarecimento. já consegui fazer a passagem dos dados... 👍
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now