Progress Dialog between to activites/intents - android

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

Related

How to continue typing in edittext in android after poping popupwindow

//imports
public class MainActivity extends Activity implements OnCheckedChangeListener
{
int count=0,ints......;
TextView textviews...;
int itemCode,month;
ArrayList<String> Name = new ArrayList<String>();
AlertDialog alertDialog ;
SharedPreferences sp;
EditText EtItemCode;
Editor editor ;
RadioButton RbForItemCode,RbForItemName;
RadioGroup RgForItemVsName;
PopupWindow popupWindowItems;
String popUpItems[];
ProgressDialog pDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//shared prefs
sp = this.getSharedPreferences("MySharedPrefsFile", Context.MODE_PRIVATE);
editor = sp.edit();
intForShardPref= sp.getInt("NEW_INSTALLATION",1); // getting Integer(1 is for no)
if(intForShardPref==1){
Intent intent = new Intent(this,Verify.class);
startActivityForResult(intent, 1);
}
else{
//do nothing
}
EtItemCode.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ToCheckItemCodeOfEdittext = EtItemCode.getEditableText().toString();
DatabaseHandler db=new DatabaseHandler(MainActivity.this);
List<Item> Items = db.getAllItemWithSubString(ToCheckItemCodeOfEdittext,itemNumberOrNameSelectedInRadioButtonOptions);
if(EtItemCode.length()>2){
if(EtItemCode.length()>3||flagForPopUpWindow>EtItemCode.length())
popupWindowItems.dismiss();
Name.clear();
for (Item cn : Items) {
if(RbForItemCode.isChecked()==true){
Name.add(Integer.toString(cn.getItemNumber()));
}
else{
Name.add(cn.getName());
}
}
popUpItems = new String[Name.size()];
Name.toArray(popUpItems);
popupWindowItems = popupWindowItems();
***popupWindowItems.setFocusable(false);***
popupWindowItems.showAsDropDown(findViewById(R.id.et_item_code), -5, 0);
}
else{
if(flagForPopUpWindow==3&&EtItemCode.length()==2)
popupWindowItems.dismiss();
}
flagForPopUpWindow=EtItemCode.length();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
private void init() {
// TODO Auto-generated method stub
//some code
}
public PopupWindow popupWindowItems() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewItems = new ListView(this);
// set our adapter and pass our pop up window contents
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
this, //context for activity
android.R.layout.simple_list_item_1, //layout used
Name){ //Items to be displayed
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item.toString();
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
//listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
listViewItems.setAdapter(adapter);
// set the item click listener
listViewItems.setOnItemClickListener(new ItemsDropdownOnItemClickListener());
// some other visual settings
//popupWindow.setFocusable(true);
popupWindow.setWidth(EtItemCode.getWidth());
//popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);
popupWindow.setHeight(r.height()-3*EtItemCode.getHeight());
// set the list view as pop up window content
popupWindow.setContentView(listViewItems);
return popupWindow;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.phone_number:
Intent p = new Intent(MainActivity.this,PhoneNumber.class);
startActivity(p);
break;
case R.id.exit:
finish();
break;
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//some code
}
class LoadDataBase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("DataBase Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
Log.d("Reading: ", "Reading all Items..");
List<Item> Items = db.getAllItem();
//some code
//DatabaseHandler db1 = new DatabaseHandler(this);
count= db.getItemCount();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
public class ItemsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "Item is: ", Toast.LENGTH_SHORT).show();
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EtItemCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// dismiss the pop up
popupWindowItems.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
Toast.makeText(MainActivity.this, "Item is: " + selectedItemText, Toast.LENGTH_SHORT).show();
DatabaseHandler db =new DatabaseHandler(MainActivity.this);
Item item= new Item();
if(RbForItemCode.isChecked()==true){
item = db.getItem(Integer.valueOf(selectedItemText));
}
else if(RbForItemName.isChecked()==true){
item = db.getItem(selectedItemText);
}
itemCode=item.getItemNumber();
}
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(RbForItemCode.isChecked()==true){
itemNumberOrNameSelectedInRadioButtonOptions="id";
//some code
}
}
else if(RbForItemName.isChecked()==true){
//some code
}
}
}
This code is working fine on my phone galaxy note 2(custom rom of note 4.. Android 4.4.4).By fine I mean I can type in edittext and popupwidow shows up after 3rd text(because of condition I have put) and I can select an option from the popupwindow. When I try to run the code on any other phone like galaxy grand then callback to ItemsDropdownOnItemClickListener is not registered and I can only scroll the popupwindow and keep on typing in edittext but cannot select any of the options in the popupwindow. If I set popupWindowItems.setFocusable(false) to true i.e popupWindowItems.setFocusable(true), and then as soon as I type 3rd letter in edittext,edittext looses focus and popwindow gains it. Now I can select anything.. But now I cannot continue to type in edittext.I have to manually select edittext and type.
Now I want that after tying 3rd word in edittext a popupwindow should appear(which currently is appearing) and edittext doesn't loose focus(so that i can continue typing).. Further if I select anything from popupwindow ,ItemsDropdownOnItemClickListener should be called which is currently being not called in other phones when popupWindowItems.setFocusable(false);
I am doing this to load data from sqlite database and show in popupwindow once the user types 3rd word. Any suggestion is recommended
Edit: Problem solved. Now using AutoComplete TextView

disable second spinner click till 1st spinner get its value : android

I have a program in android where spinner gets the data dynamically from rest services. what i want to achieve is when the first spinner loads its value, the selected value loads the value of 2nd and third spinner. i want to disable the click of 2nd and third spinner till the spinner gets populated are loaded in all the spinner.
I call the function of populating 2nd & 3rd spinner in the end of the program.
public void addItemsOnSpinner1()
{
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null) {
String value = extras.getString("new_variable_name");
strEmployeeID = value;
}
JSONObject login = new JSONObject();
try
{
login.put("EmployeeID",strEmployeeID);
//login.put("Password", etCountry.getText().toString());
JSONObject finaldata = new JSONObject();
finaldata.put("ProjectRequest", login);
final ConnectToServer connect = new ConnectToServer();
connect.extConnectToServer(HourlyEntry.this,new ConnectToServer.Callback()
{
public void callFinished(String result)
{
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject resp = null;
try
{
resp = new JSONObject(result);
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject Login1Result = resp.getJSONObject("ProjectResult");
JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
// String strMessage = Login1Result.getString("message");
// Toast.makeText(getBaseContext(), Login1Result.getString("ProjectDetails"), Toast.LENGTH_LONG).show();
// List<String> list = new ArrayList<String>();
if (!Login1Result.getString("ProjectDetails").equalsIgnoreCase("null"))
{
//JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
m_Project_list = new ArrayList<String>();
m_projectID_list = new ArrayList<String>();
for (int i = 0; i < DepartmentDetails.length(); i++)
{
JSONObject m_DepartmentDetails = DepartmentDetails.getJSONObject(i);
// Toast.makeText(getBaseContext(),m_DepartmentDetails.toString() , Toast.LENGTH_LONG).show();
if (!m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase(""))
{
// list.add(m_DepartmentDetails.getString("ProjectName"));
m_Project_list.add(m_DepartmentDetails.getString("ProjectName"));
// Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectName"), Toast.LENGTH_LONG).show();
}
if (!m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase(""))
{
m_projectID_list.add(m_DepartmentDetails.getString("ProjectID"));
//Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectID"), Toast.LENGTH_LONG).show();
String strProjectID="";
String item2 = m_DepartmentDetails.getString("ProjectID");
strProjectID = item2;
}
}
}
s1 = (Spinner) findViewById(R.id.spinnerL);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.spin,m_Project_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
if (m_projectID_list.contains(m_ProjectID))
{
s1.setSelection(m_projectID_list.indexOf(m_ProjectID));
}
}
catch (final JSONException e)
{
}
}
}, "http://aapna.azurewebsites.net/Service1/Project", finaldata,
"POST");
connect.execute(finaldata);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
// Toast.makeText(getApplicationContext(),
// SelectedProjectID, Toast.LENGTH_LONG).show();
// Showing selected spinner item
// Toast.makeText(getApplicationContext(),
// "Selected : " + item1, Toast.LENGTH_LONG).show();
s2.setClickable(false);
s3.setClickable(false);
addItemsOnSpinner2(SelectedProjectID);
s2.setClickable(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setClickable(true);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Try this..
Change your first element from m_Project_list ArrayList as Select
And after user selecting spinner you can do other operation below codes inside onCreate
Code
s1.setSelection(0);
s1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
if(pos == 0){
s2.setEnabled(false);
s3.setEnabled(false);
}
else{
// do something
addItemsOnSpinner2(SelectedProjectID);
s2.setEnabled(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setEnabled(true);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
EDIT
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.i("=========="," handler == > ");
Toast.makeText(getBaseContext(), "handler", Toast.LENGTH_LONG).show();
}
}, 5000);
The only solution I got is to use delay function to solve this kind of spinner as told to me by hariharan.
ADD these two statements in spinner 1 function
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id)
{
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
s2.setEnabled(false);
s3.setEnabled(false);
addItemsOnSpinner2(SelectedProjectID);
addItemsOnSpinner3(SelectedProjectID);
delay1();
//
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
then use the below function
public void delay1()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run()
{
s2.setEnabled(true);
s3.setEnabled(true);
}
}, 3000);
}

Passing values to Activities with putExtra()

I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");

adapter.notifyDataSetChanged(); and listview.invalidateViews not refreshing listview

I have an application where the user will click on an item in the listview and either save, cancel, or delete the entry(this is done on a new activity that is started on the item click). so in the activity that is started on item click , after i click either button i call finish() to return to my previous activity and in this case the activity with the listview. However, if I do any change to the item in the list, the list is not changed at all. I tried using both .notifyDataSetChanged() and invalidateViews but neither of the two worked. Here is my code.
public class Flashcards_List extends ListActivity{
String[] All_Cards = null;
ArrayAdapter<String> adapter;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.flashcards_list);
Flashcards Cards = new Flashcards(this);
Cards.open();
All_Cards = Cards.getAllFronts();
listview = (ListView) findViewById(android.R.id.list);
listview.invalidateViews();
adapter = new ArrayAdapter<String>(Flashcards_List.this, android.R.layout.simple_list_item_1, All_Cards);
// Assign adapter to ListView
listview.setAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String Specific_Card = All_Cards[position];
/* Class to assist us in loading the activity */
Class editClass = null;
try {
editClass = Class.forName("com.example.flashcards.Edit_Flashcard");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bundle specificCard = new Bundle();
specificCard.putString("card", Specific_Card);
Intent ourIntent = new Intent(Flashcards_List.this, editClass);
ourIntent.putExtras(specificCard);//passing the bundle to the activity
startActivity(ourIntent);
adapter.notifyDataSetChanged();
}
}
This class edits the DB entry
public class Edit_Flashcard extends Activity implements OnClickListener{
String front_of_card = null;
Bundle bundle_received;
Button cancel, delete, save;
EditText front, back;
String[] card;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_flashcard);
bundle_received = getIntent().getExtras();
front_of_card = bundle_received.getString("card");//current card is the card that was clicked on
Flashcards info = new Flashcards(this);
info.open();
card = info.getCard(front_of_card);
info.close();
initialize();
}
public void initialize(){
front = (EditText) findViewById(R.id.front);
back = (EditText) findViewById(R.id.back);
front.setText(card[1]);
back.setText(card[2]);
cancel = (Button) findViewById(R.id.cancel);
save = (Button) findViewById(R.id.save);
delete = (Button) findViewById(R.id.delete);
cancel.setOnClickListener(this);
save.setOnClickListener(this);
delete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.cancel:
super.finish();//finishes the activity, and returns to previous Activity
break;
case R.id.save:
try{
Flashcards update_entry = new Flashcards(this);
update_entry.open();
update_entry.updateEntry(card[0], front.getText().toString(), back.getText().toString());
update_entry.close();
}catch(Exception e){
String save_text = "The Flashcard could not be saved. Please try again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(Edit_Flashcard.this, save_text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
super.finish();
break;
case R.id.delete:
try{
Flashcards delete_entry = new Flashcards(this);
delete_entry.open();
delete_entry.deleteEntry(card[0]);
delete_entry.close();
}catch(Exception e){
/* set the value to NOT INSERTED */
String delete_text = "The Flashcard could not be deleted. Please try again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(Edit_Flashcard.this, delete_text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
super.finish();
break;
}/* end Switch */
}/* end onClick */
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Launch EditClass activity by startActivityForResult method. Implement onActivityResult method in the calling activity and in that method call adapter.notifyDatasetChanged.
Intent ourIntent = new Intent(Flashcards_List.this, editClass);
ourIntent.putExtras(specificCard);//passing the bundle to the activity
startActivity(ourIntent);
adapter.notifyDataSetChanged();
notifyDataSetChanged is executed IMMEDIATELY after you call startActivity(), it doesn't block. Instead, you should load your data in onResume(), that way the latest data will always be shown when the activity comes back. Basically leave only the setContentView() in your onCreate.

How to select itemclick event for listview with multiple rows in android?

I am trying to get values from server and retrieved response from server, the details responsed from server are need to be displayed in a listview, i achieved that too, but while onitemclick process only first row in list view performs the click action but it is not performing for the remaining rows, how can i achieve it, dat is whatever the row and item i'm selecting it has to be processed by my code, here is my code for the reference, .........
public void userInterface() throws JSONException
{
if(json_user.get(0) != null)
{
downloadList1 = (ListView)findViewById(R.id.lvinbox);
populateData();
downloadList1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
fma=(TextView)findViewById(R.id.src);
st=(TextView)findViewById(R.id.sub);
fma.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String fm=fma.getText().toString();
String s=st.getText().toString();
Intent m = new Intent(getApplicationContext(), InActivity.class);
m.putExtra("f", fm);
m.putExtra("s", s);
startActivity(m);
}
});
st.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String fm=fma.getText().toString();
String s=st.getText().toString();
Intent m = new Intent(getApplicationContext(), InActivity.class);
m.putExtra("f", fm);
m.putExtra("s", s);
startActivity(m);
}
});
}
});
}
else
{
Toast.makeText(getApplicationContext(),"Empty", Toast.LENGTH_LONG).show();
finish();
Intent menu = new Intent(getApplicationContext(), MenActivity.class);
menu.putExtra("username", dest);
startActivity(menu);
}
}
public void populateData() throws JSONException
{
resultVector = new Vector<ListDataItemInbox>();
int len = json_user.length();
System.out.println("length--------------------->"+len);
for(int i=0;i<len;i++)
{
JSONObject obj=json_user.getJSONObject(i);
listData = new ListDataItemInbox();
listData.sets(obj.getString(KEY_S));
listData.setd(obj.getString(KEY_D));
resultVector.add(listData);
myHandler.post(myRunnable);
}
}
private Handler myHandler = new Handler();
private Runnable myRunnable = new Runnable()
{
public void run()
{
customListAdapter = new ListViewAdapterInbox(InActivity.this);
customListAdapter.setResultsData(resultVector);
downloadList1.setAdapter(customListAdapter);
}
};
You can do something like this.
make the ArrayList in list adapter class
ArrayList<Integer> selectedIds = new ArrayList<Integer>();
and create this method also in that same class.
public void toggleSelected(Integer position){
selectedIds.clear();
selectedIds.add(position);
}
Now whenever you click on any item of listview pass that item position to this method. And inside your getView method set the check before setting the text. something like this..
if (selectedIds.contains(position)){
----- your code ----
}else{
----- your code ----
}
it perform the operation only on selected position . Try it.!

Categories

Resources