There has a listView and a add button in Activity A. The listView data is retrieved from MySQL.
[![http://i.stack.imgur.com/wVmSK.png][1]][1]
When list is clicked, it will pass the data to Activity B, if add button is clicked, it will go to Activity B for user to add data. I use mClickedPosition to differentiate whether is list clicked or button clicked.
Activity A
ListView listViewUpdate;
ListAdapter adapter;
Button add;
String ID, iD;
public static final int PROJECT_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 2;
int mClickedPosition;
String ReceiveProject, ReceiveDescription, ReceiveTimeIn, ReceiveTimeOut;
Integer ReceiveProgress;
ArrayList<DetailsBean> results = new ArrayList<DetailsBean>();
String myJSON;
JSONArray details = null;
ArrayList<HashMap<String, String>> EditDetails;
listViewUpdate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position; // listView click
HashMap<String, String> clickedItem = EditDetails.get(position);
iD = clickedItem.get(Configs.TAG_ID);
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("iD", iD);
intent.putExtra("ID", ID);
intent.putExtra("mClickedPosition",mClickedPosition);
//Toast.makeText(getActivity(),"This is"+iD+ID,Toast.LENGTH_LONG).show();
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mClickedPosition = -1; // if button clicked
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("ID", ID);
startActivity(intent);
}
});
Assume user click add button.(mClickedposition==-1)
Activity B
When save button is clicked, data will get inserted into MySQL since mClickedPosition==-1 After that, I want the new data return to Activity A and adding a new list in A, which mean the Activity A should have 2 list now. How can I achieve this ?
save.setOnClickListener(new View.OnClickListener() { // if save button clicked
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
project1 = Project2.getSelectedItem().toString();
description = Description.getText().toString();
progress = seekBar.getProgress();
timeIn = TimeIn.getText().toString();
timeOut = TimeOut.getText().toString();
if(mClickedPosition==-1)
{
Add(project1,description,progress,timeIn,timeOut);
}
else
{
Update(project1, description, progress, timeIn, timeOut);
}
returnIntent.putExtra("project1", project1);
returnIntent.putExtra("description", description);
returnIntent.putExtra("progress", progress);
returnIntent.putExtra("timeIn", timeIn);
returnIntent.putExtra("timeOut", timeOut);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveProject = data.getStringExtra("project1");
ReceiveDescription = data.getStringExtra("description");
ReceiveProgress = data.getIntExtra("progress", 0);
ReceiveTimeIn = data.getStringExtra("timeIn");
ReceiveTimeOut = data.getStringExtra("timeOut");
Toast.makeText(getActivity(),ReceiveProject+ReceiveDescription+ReceiveProgress+ReceiveTimeIn+ReceiveTimeOut,Toast.LENGTH_LONG).show();
if(mClickedPosition==-1)
{ // add list
HashMap<String, String> clickedItem = new HashMap<>();
clickedItem.put(Configs.TAG_PROJECT, ReceiveProject);
clickedItem.put(Configs.TAG_WORKDESCRIPTION, ReceiveDescription);
clickedItem.put(Configs.TAG_PERCENTAGE, ReceiveProgress + "");
clickedItem.put(Configs.TAG_IN, ReceiveTimeIn);
clickedItem.put(Configs.TAG_OUT, ReceiveTimeOut);
EditDetails.add(clickedItem);
((BaseAdapter) adapter).notifyDataSetChanged();
}
else
{ // update list
HashMap<String, String> clickedItem =EditDetails.get(mClickedPosition);
clickedItem.put(Configs.TAG_PROJECT, ReceiveProject);
clickedItem.put(Configs.TAG_WORKDESCRIPTION, ReceiveDescription);
clickedItem.put(Configs.TAG_PERCENTAGE, ReceiveProgress + "");
clickedItem.put(Configs.TAG_IN, ReceiveTimeIn);
clickedItem.put(Configs.TAG_OUT, ReceiveTimeOut);
((BaseAdapter) adapter).notifyDataSetChanged();
}
//((BaseAdapter) adapter).notifyDataSetChanged();
}
}
}
}
Now I can see a new list added in Activity A. But when I click the new
list and go to Activity B, no data are passed. But if I click the old
list, I can see data passed...
You need add or update the new data in the List and then call notifiDataSetChanged();
Change the code in the onActivity result method of your activity A as below-
HashMap<String, String> item = new HashMap<>();
item.put(Configs.TAG_PROJECT, ReceiveProject);
item.put(Configs.TAG_WORKDESCRIPTION, ReceiveDescription);
item.put(Configs.TAG_PERCENTAGE, ReceiveProgress + "");
item.put(Configs.TAG_IN, ReceiveTimeIn);
item.put(Configs.TAG_OUT, ReceiveTimeOut);
if(mClickedPosition==-1)
{ // add list
EditDetails.add(item);
}
else
{ // update list
EditDetails.remove(mClickedPosition);
mEventsList.add(mClickedPosition,item)
}
((BaseAdapter) adapter).notifyDataSetChanged();
Related
I have a listview which when clicked on listitem opens a new singleitenview activity
The singleitenm view consists of a button which is used to add the corresponding listitem to favorites activity(if not yet added) and changes the button color to yellow indicating it is added to favoorites or else gray if not in favorites
Till here everything works fine but if i close the singleitemview and reopen it the button color changes back to previous color but still in facvorites
What shall i do to retain the button color
onitemclick of my list activity
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ObjectMapper mapper = new ObjectMapper();
Product pro = productListAdapter.getItem(position);
String favimg = ((ImageView) view.findViewById(R.id.imgbtn_favorite)).toString();
try
{
String hi = "this is testint";
String jsonInString = mapper.writeValueAsString(pro);
Intent intent = new Intent(activity.getApplicationContext(), SingleItemView.class);
intent.putExtra("selected item", jsonInString);
;
startActivityForResult(intent, 1);
// startActivity(intent);
}
catch (JsonProcessingException e)
{}
}
favbtn of singleitemview activity
final Button btn = (Button) findViewById(R.id.singleitemButton1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
products=new ArrayList<Product>();
Bundle extras = getIntent().getExtras();
String jsonObj = extras.getString("selected item");
ObjectMapper mapper = new ObjectMapper();
try
{
Product pro = mapper.readValue(jsonObj, Product.class);
if (checkFavoriteItem(pro)) {
sharedPreference.removeFavorite(SingleItemView.this, pro);
btn.setBackgroundColor(Color.GRAY);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
} else {
sharedPreference.addFavorite(SingleItemView.this, pro);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
btn.setBackgroundColor(Color.YELLOW);
}
}
catch (IOException e)
{};
});
I'm having an issue with saving the instance of an ArrayList of custom objects in an Activity and then retreiving it after doing some stuff in another Activity. Inside the first Activity (which has the ArrayList), there is a button to start a second activity. Inside this second Activity the user is asked to create a new object that will be added afterwards in the ArrayList of the first Activity, so that when the second Activity finishes the first Activity is shown again with a ListView of all the objects (including the last one created). The problem I'm facing is that only the last object created is being shown in the ListView.
Here is the code of the first Activity:
public class CargasMin extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_CargasMin;
ImageButton bt_AdDep;
Button bt_CalcCargas;
ListView listView_Dep;
ArrayList<Dependencia> listaDeDependencias = new ArrayList<Dependencia>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.min_cargas);
rl_CargasMin = (RelativeLayout) findViewById(R.id.cargasMinLayout);
bt_AdDep = (ImageButton) findViewById(R.id.bt_AdDep_CargasMin);
bt_CalcCargas = (Button) findViewById(R.id.bt_CalcCargas_CargasMin);
bt_AdDep.setOnClickListener(this);
bt_CalcCargas.setOnClickListener(this);
// This seems not to be working!
if(savedInstanceState == null) { }
else {
listaDeDependencias = savedInstanceState.getParcelableArrayList("key");
}
// Get last object created
Intent intent_de_AdDep = getIntent();
Dependencia dependenciaAAdicionar = (Dependencia) intent_de_AdDep.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar == null) { }
else {
listaDeDependencias.add(dependenciaAAdicionar);
}
//Cria Adapter pra mostrar dependencias na ListView
DependenciaAdapter adapterDeDependencias = new DependenciaAdapter(this, R.layout.adapter_dependencia, listaDeDependencias);
//Seta Adapter
listView_Dep = (ListView) findViewById(R.id.listView_Dep_CargasMin);
listView_Dep.setAdapter(adapterDeDependencias);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivity(intent_AdDep);
break;
case R.id.bt_CalcCargas_CargasMin:
//
break;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// Aqui se salva a listaDeDependencias quando a Atividade eh momentaneamente fechada.
outState.putParcelableArrayList("key", listaDeDependencias);
super.onSaveInstanceState(outState);
}
}
This is the code of my custom class Dependencia:
public class Dependencia implements Parcelable {
String nome;
int tipo;
float largura = 0;
float comprimento = 0;
float area = 0;
float perimetro = 0;
// Constructor da classe Dependencia.
public Dependencia(String nomeDep, int tipoDep) {
nome = nomeDep;
tipo = tipoDep;
}
private Dependencia(Parcel in) {
nome = in.readString();
tipo = in.readInt();
largura = in.readFloat();
comprimento = in.readFloat();
area = in.readFloat();
perimetro = in.readFloat();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(nome);
out.writeInt(tipo);
out.writeFloat(largura);
out.writeFloat(comprimento);
out.writeFloat(area);
out.writeFloat(perimetro);
}
public static final Parcelable.Creator<Dependencia> CREATOR = new Parcelable.Creator<Dependencia>() {
public Dependencia createFromParcel(Parcel in) {
return new Dependencia(in);
}
public Dependencia[] newArray(int size) {
return new Dependencia[size];
}
};
}
And this is the code of the second Activity:
public class AdDep extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_AdDep;
EditText et_Nome;
EditText et_Largura;
EditText et_Comprimento;
EditText et_Area;
EditText et_Perimetro;
Spinner spinner_Tipo;
String vetorTipo[];
int tipoEscolhido;
Button bt_AdDep1;
Button bt_AdDep2;
Dependencia novaDependencia;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dep_ad);
rl_AdDep = (RelativeLayout)findViewById(R.id.adDepLayout);
et_Nome = (EditText) findViewById(R.id.et_Nome_AdDep);
et_Largura = (EditText) findViewById(R.id.et_Largura_AdDep);
et_Comprimento = (EditText) findViewById(R.id.et_Comprimento_AdDep);
et_Area = (EditText) findViewById(R.id.et_Area_AdDep);
et_Perimetro = (EditText) findViewById(R.id.et_Perimetro_AdDep);
spinner_Tipo = (Spinner) findViewById(R.id.spinner_Tipo_AdDep);
bt_AdDep1 = (Button) findViewById(R.id.bt_AdDep1);
bt_AdDep2 = (Button) findViewById(R.id.bt_AdDep2);
// Adicionando opcoes no spinner
vetorTipo = new String[5];
vetorTipo[0] = "Banheiro";
vetorTipo[1] = "Varanda";
vetorTipo[2] = "Cozinha/Copa/Serviço/etc.";
vetorTipo[3] = "Sala/Dormitório";
vetorTipo[4] = "Outro";
// Criando ArrayAdapter de strings pro spinner
ArrayAdapter<String> adapterTipo = new ArrayAdapter<String>(AdDep.this, android.R.layout.simple_spinner_item, vetorTipo);
// Setando o Adapter
spinner_Tipo.setAdapter(adapterTipo);
// Valor default do spinner (hint)
spinner_Tipo.setSelection(0);
bt_AdDep1.setOnClickListener(this);
bt_AdDep2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Banheiro"))
tipoEscolhido = 1;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Varanda"))
tipoEscolhido = 2;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Cozinha/Copa/Serviço/etc."))
tipoEscolhido = 3;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Sala/Dormitório"))
tipoEscolhido = 4;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Outro"))
tipoEscolhido = 5;
novaDependencia = new Dependencia(et_Nome.getText().toString(), tipoEscolhido);
switch(v.getId()) {
case R.id.bt_AdDep1:
novaDependencia.largura = Float.valueOf(et_Largura.getText().toString());
novaDependencia.comprimento = Float.valueOf(et_Comprimento.getText().toString());
break;
case R.id.bt_AdDep2:
novaDependencia.area = Float.valueOf(et_Area.getText().toString());
novaDependencia.perimetro = Float.valueOf(et_Perimetro.getText().toString());
break;
}
AlertDialog.Builder builder2 = new AlertDialog.Builder(v.getContext());
builder2.setMessage("Deseja adicionar T.U.E. nesta dependência?").setPositiveButton("Sim", dialogClickListener).setNegativeButton("Não", dialogClickListener).show();
}
// Objeto tipo dialog criado para perguntar se usario deseja inserir TUEs
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
Intent intent_NovaDep_CargasMin = new Intent(AdDep.this, CargasMin.class);
intent_NovaDep_CargasMin.putExtra("novaDependencia", novaDependencia);
startActivity(intent_NovaDep_CargasMin);
break;
}
}
};
}
If anyone knows how to solve this, please share. Thanks.
The problem is that you're starting a new instance of the CargasMin activity from AdDep activity. Your AdDep activity should just finish and return a result back to the existing instance of CargasMin activity on the back stack for you to see all the previous list data as well.
To retrieve the new list item from AdDep as a result, use startActivityForResult()
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivityForResult(intent_AdDep, ADD_DEP_REQUEST);
break;
where ADD_DEP_REQUEST is just a request code constant
public static final int ADD_DEP_REQUEST = 1;
Now, when AdDep is done collecting data, it returns the new data item as a result.
case DialogInterface.BUTTON_NEGATIVE:
Intent result = new Intent();
result.putExtra("novaDependencia", novaDependencia);
setResult(Activity.RESULT_OK, result);
finish();
break;
Your main CargasMin activity will then receive the new data item as
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_DEP_REQUEST) {
if (resultCode == RESULT_OK) {
// Get last object created
Dependencia dependenciaAAdicionar =
(Dependencia) data.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar != null){
listaDeDependencias.add(dependenciaAAdicionar);
// Refresh Adapter pra mostrar dependenciaAAdicionar na ListView
adapterDeDependencias.notifyDataSetChanged();
}
}
}
}
Note that listaDeDependencias and adapterDeDependencias have been changed to instance members of the activity.
Your current approach would have worked if you were persisting the data to some storage (like in a file or database) but creating a new instance of CargasMin is still not recommended because the one existing on the back stack would suffice.
I have a ListView, which displays a list of notes taken from a table in SQLiteDatabase with ArrayAdapter.
public class NotepadActivity extends ListActivity {
protected static final int ADD_NEW_NOTE = 0;
protected static final int EDIT_NOTE = 1;
ArrayAdapter<Note> adapter;
NotesManager manager;
private Note nNoteToDelete;
ArrayList<Note> lstAllNotes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnAddNewNote).setOnClickListener(addNewNote);
manager = new NotesManager(this);
lstAllNotes = manager.getAllNotes();
adapter = new ArrayAdapter<Note>(this, R.layout.note, lstAllNotes);
setListAdapter(adapter);
getListView().setOnItemClickListener(editNote);
registerForContextMenu(getListView());
}
When I click on an Item in this ListView, it takes this Note object to the EditNote activity:
private OnItemClickListener editNote = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Note currNote = (Note)parent.getItemAtPosition(position);
int curr_note_id = currNote.getId();
String curr_note_title = currNote.getTitle().toString();
String curr_note_details = currNote.getDetails().toString();
Intent editNote = new Intent(NotepadActivity.this, EditNote.class);
editNote.putExtra("CURR_NOTE_ID", curr_note_id);
editNote.putExtra("CURR_NOTE_TITLE", curr_note_title);
editNote.putExtra("CURR_NOTE_DETAILS", curr_note_details);
startActivityForResult(editNote, EDIT_NOTE);
}
};
I can edit the title of the note in there and the content. When I hit the Save button, it sends back to the main activity the Strings of Title and the Details and the ID int:
public class EditNote extends Activity implements OnClickListener {
int curr_note_id;
String curr_note_title;
String curr_note_details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);
curr_note_id = getIntent().getExtras().getInt("CURR_NOTE_ID");
curr_note_title = getIntent().getExtras().getString("CURR_NOTE_TITLE");
curr_note_details = getIntent().getExtras().getString(
"CURR_NOTE_DETAILS");
((EditText) findViewById(R.id.edtTitle)).setText(curr_note_title);
((EditText) findViewById(R.id.edtDetails)).setText(curr_note_details);
findViewById(R.id.btnSave).setOnClickListener(this);
findViewById(R.id.btnCancel).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSave:
String strNoteTitle = ((EditText) findViewById(R.id.edtTitle)).getText().toString().trim();
String strNoteDetails = ((EditText) findViewById(R.id.edtDetails)).getText().toString().trim();
if (!strNoteTitle.equals("")) {
Intent data = new Intent();
data.putExtra("NOTE_ID", curr_note_id);
data.putExtra("NOTE_TITLE", strNoteTitle);
data.putExtra("NOTE_DETAILS", strNoteDetails);
setResult(RESULT_OK, data);
finish();
} else {
((EditText) findViewById(R.id.edtTitle))
.setError("A note must contain a title");
}
break;
case R.id.btnCancel:
setResult(RESULT_CANCELED);
finish();
break;
}
}
}
And in the main activity it should update the DB and the ListView with the new Title, if there were changes. My code does update the DB, but I don't see the change in the ListView immediately, only if I exit the app and open it again. Here's the code (watch the second case, EDIT_NOTE):
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ADD_NEW_NOTE:
String noteTitle = data.getExtras().getString("NOTE_TITLE");
String noteDetails = data.getExtras().getString("NOTE_DETAILS");
Note nNewNote = new Note(-1, noteTitle, noteDetails);
adapter.add(nNewNote);
manager.addNote(nNewNote);
break;
case EDIT_NOTE:
int noteID = data.getExtras().getInt("NOTE_ID");
noteTitle = data.getExtras().getString("NOTE_TITLE");
noteDetails = data.getExtras().getString("NOTE_DETAILS");
nNewNote = new Note(noteID, noteTitle, noteDetails);
Toast.makeText(NotepadActivity.this, noteTitle + "\n" + noteDetails, Toast.LENGTH_SHORT).show();
manager.updateNote(nNewNote);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
After manager.updateNote(nNewNote); I tried to use adapter.notifyDataSetChanged(); but that didn't work - I didn't see the change in the ListView. Perhaps I used it wrong, perhaps I should use something else...
So how can I make the ListView refresh? How can I see change immediately, without restarting the app?
Thank you!
When you return from the edit activity, set the list adapter again to refresh the ListView. You have to manually refresh the ListView each time if you want to see any updates. Hope this helps.
I am trying to pass information form one Activity to the other and while doing that I would like to have a progress dialog show. Mainly when the second activity is processing the information. I have been reading up and the proper way of doing it seems to be asynctask. Or is there another way of doing it?
Here is my code: Activity one
public class SearchActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
return true;
}
return false;
}
});
final Button button = (Button) findViewById(R.id.searchButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
}
});
}
}
This is the Second activity:
public class DissertationActivity extends ListActivity {
/** Called when the activity is first created. */
public ArrayList<String> book_Array = new ArrayList<String>();
ArrayAdapter<String> adapter;
String href = "";
String href1 = "";
String search_Word = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
search_Word = extras.getString("query1");
adapter = new ArrayAdapter<String>(this, R.layout.list_item_1,
book_Array);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
try {
Document doc = null;
Document guestLink = null;
guestLink = Jsoup.connect("https://aulib.abdn.ac.uk:443/F").get();
Element link = guestLink.select("p > a").first();
href1 = link.attr("href");
href = href1.substring(0, href1.length() - 2); // removes -0 from
// the
// href_Array.add(href); //adds href to the array because string
// wont add to the public var.
doc = Jsoup.connect(
href + "&request=" + search_Word
+ "&find_code=WRD&adjacent=N&x=0&y=0").get();
// System.out.println(doc);
Elements headings = doc.select("td:eq(3)");
// System.out.println(headings);
for (Element heading : headings) {
// System.out.println(heading.text());
String j = heading.text();
book_Array.add(j);
}
} catch (IOException e) {
e.printStackTrace();
}
book_Array.remove(0);
adapter.notifyDataSetChanged();
book_Array.remove(1);
adapter.notifyDataSetChanged();
book_Array.remove(2);
adapter.notifyDataSetChanged();
book_Array.remove("Search");
adapter.notifyDataSetChanged();
book_Array.remove(" | ");
adapter.notifyDataSetChanged();
book_Array.remove(0);
adapter.notifyDataSetChanged();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
// Context context = getApplicationContext();
int query = position;
// String text = book_Array.get(position);
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,
// String.valueOf(position), //shows the postion in the array
// list
// duration);
// toast.show();
Intent intent = new Intent(DissertationActivity.this,
FullDetailsActivity.class);
intent.putExtra("href", href);
intent.putExtra("query1", (int) query);
intent.putExtra("search_Word", search_Word);
startActivity(intent);
}
});
}
}
I tried using:
this.pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
But that didn't work.
How would I go about, so that it displays a progress dialog in between the activities?
Thanks for your help!
Calling ProgressDialog.show will block the UI thread. So the progress dialog/bar will not show up until the method has returned. So we can create a thread for our method to run within it. This will avoid blocking the main UI Thread.
Sample code -
ProgressDialog spinnerDialog = ProgressDialog.show(
Placeholder.this, "","Your text ", true);
new Thread(new Runnable() {
public void run() {
//your method code
return;
}
}).start();
Hi I was wondering how I can get my Search Activity to return a result back to the Activity that started it.
I currently have a Search Dialog implemented (meaning the search Activity starts once the Search button on the phone is clicked).
Here is my code for the Search activity which is a list view.
public class ItemFinder extends ListActivity {
public static final int REQUEST_CODE = 1; // get it?
Vector<String> upcCodes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
upcCodes = new Vector<String>();
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String upc = upcCodes.elementAt(position);
setResult(RESULT_OK);
}
});
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ProgressDialog dialog = ProgressDialog.show(ItemFinder.this, "Searching",
"Searching. Please wait...", true);
performSearch(query);
dialog.hide();
dialog.dismiss();
}
}
public void performSearch(String query){
String result = new SmartShopClient().SearchItems(query);
List<String> dataList = new ArrayList<String>();
String _parsedResult[] = result.split("\\n");
for( int i = 0; i<_parsedResult.length; i++){
String _splitData[] = _parsedResult[i].split("\\|");
String itemName = _splitData[0];
String itemUPC = _splitData[1];
dataList.add(itemName);
upcCodes.add(itemUPC);
}
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
this.setListAdapter(arr);
}
}
So the search is working all fine and dandy, but I want it so when I click one of the results in the ListView, for it to return data back to the main activity with some data, say the name of the clicked searched result.
Thanks.
What you want to do is launch the search using startActivityForResult. See an explanation here.
This way, you can pass your search results back to the activity which launched it.
That would happen in your setOnItemClickListener method, where you could launch an explicit intent naming the desired activity with extra data.
Edit : I'm not quite sure of how startActivityForResult() would be implemented since we're talking about the search activity of the application, meaning it's launched by the Android search specific module ; that's why i suggested the above solution.
I ended up doing this:
public boolean onSearchRequested() {
askSearchQuery();
return true;
}
public void sendSearchRequest(String query){
Intent mIntent = new Intent(this, ItemFinder.class);
mIntent.setAction(Intent.ACTION_SEARCH);
mIntent.putExtra(SearchManager.QUERY, query);
startActivityForResult(mIntent, ItemFinder.REQUEST_CODE);
}
public void askSearchQuery() {
final EditText input = new EditText(SmartShop.this);
AlertDialog.Builder adb = new AlertDialog.Builder(SmartShop.this);
adb.setTitle("Search Items");
adb.setMessage("Please input the name of the item you are looking for.");
adb.setView(input);
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable upc = input.getText();
sendSearchRequest(upc.toString());
dialog.cancel();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
adb.create().show();
}
And then I hooked the
protected void onActivityResult (int requestCode, int resultCode, Intent data) {