android putextra without start activity - android

i need help please.
I have two activities and a db. All i want to do is when i press a button in activity A, i send the string in my editText to the activity B. In the activity B i try to insert that string in my db and display it in a listview. All works if i start the activity B in the activity A but i wont display the activity B.
Here my code:
Activity A:
public class Example extends Activity {
public final static String ID_EXTRA2="com.example.activities";
public EditText MyInputText = null;
ImageView MyButton;
TextView MyOutputText, MyInputtext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diccionary);
MyInputText = (EditText)findViewById(R.id.InputText);
MyOutputText = (TextView)findViewById(R.id.OutputText);
MyButton = (ImageView)findViewById(R.id.botonaceptar);
MyButton.setOnClickListener(MyButtonOnClickListener);
public ImageView.OnClickListener MyTranslateButtonOnClickListener = new ImageView.OnClickListener(){
public void onClick(View v) {
String InputString;
InputString = MyInputText.getText().toString();
try{
Intent d = new Intent(Example.this, Secondactivity.class);
d.putExtra(ID_EXTRA2, InputString);
//startActivity(d); <----- If i start the secondactivity, that works...
}catch (Exception e){
}
}
};
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater awesome = getMenuInflater();
awesome.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu1:
startActivity(new Intent("com.example.activities.SECONDACTIVITY"));
return true;
case R.id.menu2:
//something to do
return true;
}
return false;
}
};
Activity B:
public class Secondactivity extends Activity {
NoteAdapter2 adapter = null;
NoteHelper2 helper2 = null;
Cursor dataset_cursor2 = null;
String entriId = null;
public ListView list2;
String passedword = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
try{
list2 = (ListView)findViewById(R.id.list2);
helper2 = new NoteHelper2(this);
---->passedword = getIntent().getStringExtra(Example.ID_EXTRA2);
---->helper2.insert(passedword); //here i insert the string in my db
startManagingCursor(dataset_cursor2);
dataset_cursor2 = helper2.getAll();
adapter = new NoteAdapter2(dataset_cursor2);
list2.setAdapter(adapter);
dataset_cursor2.requery();
adapter.notifyDataSetChanged();
//this is how we know to do when a list item is clicked
list2.setOnItemClickListener(onListClick);
}
catch (Exception e){
// this is the line of code that sends a real error message to the log
Log.e("ERROR", "ERROR IN CODE" + e.toString());
//this is the line that prints out the location in the code where the error ocurred
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
helper2.close();
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
entriId = String.valueOf(id);
}
};
class NoteAdapter2 extends CursorAdapter {
NoteAdapter2(Cursor c){
super(Zhistorytranslate.this, c);
}
public void bindView(View row2, Context ctxt, Cursor c) {
NoteHolder2 holder2 = (NoteHolder2)row2.getTag();
holder2.populateFrom2(c, helper2);
}
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row2 = inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder2 = new NoteHolder2(row2);
row2.setTag(holder2);
return (row2);
}
}
static class NoteHolder2 {
private TextView entriText = null;
NoteHolder2(View row2){
entriText = (TextView)row2.findViewById(R.id.entri);
}
void populateFrom2(Cursor c, NoteHelper2 helper2) {
entriText.setText(helper2.getEntri(c));
}
}

If I understood you correctly, you want to send data from A to B without launching B. In this case, you need to forget about Intents and consider a way to store data in your app. My suggestion is to use SharedPreferences.
Here is how you can use it:
In your Activity A, store the String:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("string_id", InputString); //InputString: from the EditText
editor.commit();
In your Activity B, you can get the value by:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String data = prefs.getString("string_id", "no id"); //no id: default value

Your question is very difficult to understand, but you seem to want to be able to add the EditText's contents into your database without starting another Activity. Simply do this in your Image's OnClickListener:
public void onClick(View v) {
NoteHelper2 helper2 = new NoteHelper2(this);
helper2.insert(MyInputText.getText().toString());
}
You should also read about Java naming convention.

Related

Android: How can I make a listview wait for a variable to fill before setting?

So I have a movie trivia game that I am building. The problem I am running into is on the main user profile page I set 3 listviews. One for games where it is your turn, one for games that are waiting for your opponent, and one for completed games. These list views make calls to Parse.com to fetch the game object. In Order to fetch this info from Parse I need to provide my query with a Facebook user id. My code calls Facebook to get the ID, but the listview adapters run about 5 milliseconds before the call to Facebook returns the ID. When the user refreshes the page, the lists load properly, but when first running the app they are blank. Here is the user profile activity code:
public class UserProfileActivity extends AppCompatActivity {
ParseLogic mPl;
private WfoAdapter wfoAdapter;
private WoyAdapter woyAdapter;
private CompletedGameAdapter completedGameAdapter;
private TicketSystem mTicketsSytem;
String mMyFbId;
String mMyFbName;
int mTickets;
ListView mWfoListView;
ListView mWoyListView;
ListView mCompletedGameListView;
TextView mmTicketNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTicketsSytem = new TicketSystem();
mTickets = mTicketsSytem.getTickets();
setContentView(R.layout.activity_user_profile);
new getFbDeets().execute(); //This is where the async task is called
mPl = new ParseLogic();
mWoyListView = (ListView)findViewById(R.id.waitingForYouListView);
mWfoListView = (ListView)findViewById(R.id.waitingForOpponentListView);
mCompletedGameListView = (ListView)findViewById(R.id.completedGameListView);
mmTicketNumber = (TextView)findViewById(R.id.numberOfTickets);
mmTicketNumber.setText(String.valueOf(mTickets));
FaceBookFriends.getFaceBookFriends();
//Testing start game remove when building rest of page
Button button = (Button)findViewById(R.id.startNewGame);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UserProfileActivity.this, GameStart.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
mTickets = mTicketsSytem.getTickets();
mmTicketNumber.setText(String.valueOf(mTickets));
populateWoyListView();
populateWfoListView();
populateCompleteListView();
}
#Override
public void onBackPressed(){}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//create the logout button in action bar
switch (item.getItemId()){
case R.id.logoutButton:
ParseUser.logOut();
ParseUser currentUser = ParseUser.getCurrentUser(); // this will now be null
Intent intent = new Intent(UserProfileActivity.this, WelcomeActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void populateUI() {
populateWoyListView();
populateWfoListView();
populateCompleteListView();
mWoyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String goTV = ((TextView) view.findViewById(R.id.gameObjectHiddenTextView)).getText().toString();
String score = ((TextView) view.findViewById(R.id.woyScoreNumber)).getText().toString();
Log.v("Clicked Object Id ", goTV);
Intent intent = new Intent(UserProfileActivity.this, AreYouReady.class);
intent.putExtra("Score", score);
intent.putExtra("Object Id", goTV);
startActivity(intent);
}
});
}
private void populateWoyListView() {
//mMfbId is the variable set by the facebook call
woyAdapter = new WoyAdapter(this ,mMyFbId);
woyAdapter.loadObjects();
mWoyListView.setAdapter(woyAdapter);
}
private void populateWfoListView() {
wfoAdapter = new WfoAdapter(this);
wfoAdapter.loadObjects();
mWfoListView.setAdapter(wfoAdapter);
}
private void populateCompleteListView() {
completedGameAdapter = new CompletedGameAdapter(this, mMyFbId);
completedGameAdapter.loadObjects();
mCompletedGameListView.setAdapter(completedGameAdapter);
}
protected class getFbDeets extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
mMyFbId = FaceBookFriends.getMyFbId();
mMyFbName = FaceBookFriends.getMyFbName();
Log.v("getFbDeets() ", "Is Running");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
populateUI();
}
}
}
This is the completed gave adapter:
/**
* Created by Tom Schinler on 9/23/2015.
*/
public class CompletedGameAdapter extends ParseQueryAdapter<Game> {
String mWinnerScore;
String mWinnerName;
String mLoserScore;
String mLoserName;
String mFbName;
public CompletedGameAdapter(Context context, final String myFbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
ParseQuery<Game> queryCreatedBy = new ParseQuery<Game>("Game");
queryCreatedBy.whereEqualTo("Created_By", ParseUser.getCurrentUser());
ParseQuery<Game> queryOppOf = new ParseQuery<Game>("Game");
queryOppOf.whereEqualTo("Opponent_Id", myFbId);
ParseQuery<Game> query = ParseQuery.or(Arrays.asList(queryCreatedBy, queryOppOf));
query.whereNotEqualTo("Creator_Score", "");
query.whereNotEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.completed_game_layout, null);
}
super.getItemView(game, view, parent);
mFbName = FaceBookFriends.getMyFbName();
TextView winOrLose = (TextView)view.findViewById(R.id.winOrLose);
int oppScore = Integer.parseInt(game.getOpponentScore());
int creatScore = Integer.parseInt(game.getCreatorScore());
if(oppScore > creatScore){
mWinnerScore = String.valueOf(oppScore);
mWinnerName = game.getOpponentName();
mLoserScore = String.valueOf(creatScore);
mLoserName = game.getCreatorFbName();
}
else {
mWinnerScore = String.valueOf(creatScore);
mWinnerName = game.getCreatorFbName();
mLoserScore = String.valueOf(oppScore);
mLoserName = game.getOpponentName();
}
TextView winnerName = (TextView)view.findViewById(R.id.winnerName);
winnerName.setText(mWinnerName);
TextView winnerScore = (TextView)view.findViewById(R.id.winnerScore);
winnerScore.setText(mWinnerScore);
TextView loserName = (TextView)view.findViewById(R.id.loserName);
loserName.setText(mLoserName);
TextView loserScore = (TextView)view.findViewById(R.id.loserScore);
loserScore.setText(mLoserScore);
if(mWinnerName.equals(mFbName)){
view.setBackgroundColor(Color.GREEN);
winOrLose.setText("WIN!!");
}
else {
view.setBackgroundColor(Color.RED);
winOrLose.setText("LOSER!!");
}
return view;
}
}
and here is the adapter that sets the listview for games waiting on the user:
/**
* Created by Tom Schinler on 9/22/2015.
*/
public class WoyAdapter extends ParseQueryAdapter<Game>{
public WoyAdapter(Context context, final String fbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
//Log.v("var fbid is ", fbId);
ParseQuery query = new ParseQuery("Game");
query.whereEqualTo("Opponent_Id", fbId);
query.whereEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.waiting_on_you_layout, null);
Log.v("WOY is this", "running");
}
super.getItemView(game, view, parent);
ProfilePictureView friendPic = (ProfilePictureView) view.findViewById(R.id.woyFbPic);
String friendId = game.getCreatorId();
if(friendId != null){
friendPic.setProfileId(friendId);
}
TextView oppName = (TextView)view.findViewById(R.id.woyNameText);
oppName.setText(game.getCreatorFbName());
TextView oppScore = (TextView)view.findViewById(R.id.woyScoreNumber);
oppScore.setText(game.getCreatorScore());
TextView GOTV = (TextView)view.findViewById(R.id.gameObjectHiddenTextView);
GOTV.setText(game.getObjectId());
return view;
}
}
I set mMyFbId with a Facebook method like this:
mMyFbId = FaceBookFriends.getMyFbId();
but it return about 1 second after the code runs to build the lists views, since they do not have the variable, they populate nothing. Please help.

Can't refresh the fragment after combing back from another activity

I'm working on the fragment, when I click a button, it will turn to another activity, after the activity saved data to database, it will return back to the fragment, however, the fragment can't show the newest data, I need to go to the activity of the fragment, then come back to the fragment again, it will show newest data.
Here is my code of fragment. I thought that because I put the setAdapter in the onActivityCreated() method, I tried to put it in onCreate() and onCreateView(), both will return nullpointer error.
public class TodoFragment extends ListFragment {
private TodoDataSource datasource;
private Todo item;
List<Todo> todoList;
MyCustomAdapter adapt;
ListView listTask;
EditText t;
public TodoFragment(){
}
/*#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setHasOptionsMenu(true);
datasource = new TodoDataSource(getActivity());
datasource.open();
todoList = datasource.getAllTodos();
adapt= new MyCustomAdapter(getActivity(), R.layout.todo_list, todoList);
//ListView listTask =(ListView) rootView.findViewById(android.R.id.list);
listTask.setAdapter(adapt);
}*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// if (activity != null) {
// Create an instance of the custom adapter for the GridView. A static array of location data
// is stored in the Application sub-class for this app. This data would normally come
// from a database or a web service.
datasource = new TodoDataSource(getActivity());
datasource.open();
todoList = datasource.getAllTodos();
adapt= new MyCustomAdapter(getActivity(), R.layout.todo_list, todoList);
//ListView listTask =(ListView) rootView.findViewById(android.R.id.list);
listTask.setAdapter(adapt);
Button button = (Button) getActivity().findViewById(R.id.simpleadd);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String summary = t.getText().toString();
Intent i = new Intent(getActivity(), TodoDetailActivity.class);
//Bundle bundle = new Bundle();
// bundle.putString("Summary", summary);
//i.putExtras(bundle);
startActivity(i);
}
});
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_todo, container, false);
t = (EditText) rootView.findViewById(R.id.simple);
listTask = (ListView) rootView.findViewById(android.R.id.list);
return rootView;
}
#Override
public void onResume() {
datasource.open();
super.onResume();
adapt.notifyDataSetChanged();
}
#Override
public void onPause() {
datasource.close();
super.onPause();
}
}
Here is part of my another activity code.
it will update the database and return to the fragment.
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (TextUtils.isEmpty(mTitleText.getText().toString())) {
makeToast();
} else {
final String category = mCategory.getSelectedItem().toString();
final String summary = mTitleText.getText().toString();
final String description = mBodyText.getText().toString();
datasource.createTodo(category, summary, description);
setResult(RESULT_OK);
finish();
}
}
});
It looks like you aren't updating your data source todoList before calling notifyDataSetChanged() in onResume().
Edit: Clear the list first, and then re-populate. Also add logging to help track down the issue:
#Override
public void onResume() {
super.onResume();
datasource.open();
todoList.clear();
todoList.addAll(datasource.getAllTodos());
adapt.notifyDataSetChanged();
Log.d("MyApp", "Size of data: " + todoList.size() );
}
Once you have added that code, try adding a few records, and watch your logcat to see if the size goes up. You can also cycle through each record, if you post your Todo class I can give you some example code.

Confuse about android check list box

I would like to implement products list with checklistbox after select radio button.
And I would like to show chekclistbox as dialog box. My product list data come from sqllite.
It is need to implement adapter class to show data for checklistbox or can I directly implement for checklistbox data in alertDialog . Please clear for me.
In mainActivity
public RadioGroup.OnCheckedChangeListener setOnCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rdoPCode = (RadioButton) findViewById(checkedId);
switch (checkedId) {
case R.id.rdoAll:
Toast.makeText(context, rdoPCode.getText(), Toast.LENGTH_SHORT)
.show();
break;
case R.id.rdoCustom:
Intent localIntent = new Intent(MainActivity.context,
ProductListChkActivity.class);
MainActivity.context.startActivity(localIntent);
break;
}
}
};
In ProductListChkActivity
public class ProductListChkActivity extends Activity {
private static Button button_selectall;
private static Button button_unselectall;
private static CheckBox chkProductCode;
private static CashSaleProductLogic _sellProductLogic;
public static List<CashSaleProductInfo> _SaleProductInfo;
public static ListView lvlchkPrdlist;
private Button btnSelectAll, btnUnSelectAll;
// For chk productcode
private static ProductListChkAdapter _ProductListChkAdapter;
Context context;
#Override
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.productinofchk);
context = this;
init();
ProductCodeChk();
}
private void init() {
button_selectall = (Button) this.findViewById(R.id.button_selectall);
button_unselectall = (Button) this
.findViewById(R.id.button_unselectall);
chkProductCode = (CheckBox) this.findViewById(R.id.chkProductCode);
lvlchkPrdlist = (ListView) this.findViewById(R.id.lvlchkPrdlist);
_sellProductLogic = new CashSaleProductLogic(this);
_SaleProductInfo = _sellProductLogic.getAllsellProductDataLogic();
}
protected void ProductCodeChk() {
try {
_ProductListChkAdapter = new ProductListChkAdapter(context,
_SaleProductInfo, 1);
this.lvlchkPrdlist.setAdapter(_ProductListChkAdapter);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public void OnClickbillbtncancel(View paramView) {
MainActivity.textClear();
Intent localIntent = new Intent(ProductListChkActivity.this,
MainActivity.class);
ProductListChkActivity.this.startActivity(localIntent);
}
}
I would like to show productinofchk layout as dialogbox
You need to go through floating dialogs in android. check out this documentation :
link

Passing the same object from one activity to another activity

I have a Mainactivity that contains the list of Trainings. And on each list is clicked it starts the session of the same training in whole application.
I managed to use Singleton and access that into my main activity. But onItemClick it takes to dialog box and on button click inside dialog it should take to another activity. Now I a getting error like java NullPointerException. Here is the code below;
Remember: I want same training session in second activity also.
MainActivity class;
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentTraining = (Training)arg0.getAdapter().getItem(arg2);
Log.i("DEBUG", currentTraining.getTitle());
CurrentTraining.getInstance().setTraining(currentTraining);
Toast.makeText(
getApplicationContext(),
"You clicked on position : " + arg2 + " and ID : "
+ currentTraining.getId(), Toast.LENGTH_LONG).show();
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(currentTraining.getTitle());
TextView description = (TextView) dialog.findViewById(R.id.textView1);
description.setText("Description: " + currentTraining.getDescription());
TextView location = (TextView) dialog.findViewById(R.id.textView2);
location.setText("Location: " + currentTraining.getLocation());
TextView date = (TextView) dialog.findViewById(R.id.textView3);
date.setText("Date: " + currentTraining.getDate());
Button back_btn = (Button) dialog.findViewById(R.id.button1);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
Button start_btn = (Button) dialog.findViewById(R.id.button2);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
TraineeActivity.class);
//intent.putExtra("trainingId", currentTraining.getId());
//intent.putExtra("title", currentTraining.getTitle().toString());
MainActivity.this.startActivity(intent);
}
});
dialog.show();
}
And in second Activity Class;
Training currentTraining;
private ListView personNamesListView;
// Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter traineeListAdapter;
private TextView TitleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trainees);
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Log.i("DEBUG", ""+currentTraining.getTitle());
TitleView = (TextView)findViewById(R.id.training_title);
TitleView.setText(currentTraining.getTitle());
Button addnew = (Button) findViewById(R.id.add_btn);
addnew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(TraineeActivity.this,
FormActivity.class);
TraineeActivity.this.startActivity(intent);
}
});
personNamesListView = (ListView) findViewById(R.id.traineeslist);
// Create a list that contains only full name of the trainee
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
protected void onResume(){
super.onResume();
traineeListAdapter = new ArrayAdapter<Trainee>(this, android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
My Singleton Class:
public class CurrentTraining {
private Training training ; //Training is my model class
private static CurrentTraining instance;
private CurrentTraining() {
}
public static CurrentTraining getInstance() {
if (instance == null)
instance = new CurrentTraining();
return instance;
}
public Training getTraining() {
return training;
}
public Training setTraining(Training training) {
return this.training = training;
}
}
In onCreate() of your second activity, you do this:
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Since currentTraining is null, this will just set the singleton variable training to null and return null.
Where are you actually setting the value of the one that the user picked?

Progress Dialog between to activites/intents

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

Categories

Resources