I'm trying to understand how to implement a search with chips (so there should be the chance to add more than one value) and the suggestion list should come from a web service using Retrofit. An example on what I would like to achieve is the search in Pinterest app.
I read online many post where someone uses AutoCompleteTextView and other SearchView and to be honest I'm very confused on which approach to follow.
Could you address me to the right way please?
Thanks
Here is code example of using Retrofit with AutocompleteEditText
public class MainActivity extends Activity {
private interface GooglePlacesClient {
#GET("/maps/api/place/autocomplete/json")
Observable<PlacesResult> autocomplete(
#Query("key") String key,
#Query("input") String input);
}
private class PlacesResult {
#Expose
List<MainActivity.Prediction> predictions;
#Expose
String status;
}
private class Prediction {
#Expose
String description;
}
private static final String LOG_TAG = "RxRetrofitAutoComplete";
private static final String GOOGLE_API_BASE_URL = "https://maps.googleapis.com";
private static final String API_KEY = "XXX";
private static final int DELAY = 500;
GooglePlacesClient mGooglePlacesClient;
#InjectView(R.id.editText1)
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
if (API_KEY.length()<10) {
Toast.makeText(this, "API KEY is unset!", Toast.LENGTH_LONG).show();
return;
}
if (mGooglePlacesClient == null) {
mGooglePlacesClient = new RestAdapter.Builder()
.setConverter(new GsonConverter(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()))
.setEndpoint(GOOGLE_API_BASE_URL)
.setLogLevel(RestAdapter.LogLevel.FULL).build()
.create(GooglePlacesClient.class);
}
Observable<EditText> searchTextObservable = ViewObservable.text(editText);
searchTextObservable.debounce(DELAY, TimeUnit.MILLISECONDS)
.map(new Func1<EditText, String>() {
#Override
public String call(EditText editText) {
return editText.getText().toString();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
#Override
public void call(String s) {
Log.d(LOG_TAG, s);
try {
mGooglePlacesClient
.autocomplete(API_KEY, URLEncoder.encode(s, "utf8"))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<PlacesResult>() {
#Override
public void call(PlacesResult placesResult) {
List<String> strings = new ArrayList<String>();
for (MainActivity.Prediction p : placesResult.predictions) {
strings.add(p.description);
}
ListView listView = (ListView) findViewById(R.id.listView1);
if (listView != null) {
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, strings));
}
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
}
}
Related
I am trying to make generic implementation for adding and showing progress bar in fragment / activity when there are multiple calls.
Anyone have any better solution rather than taking two references of progress bar and toggling its visibility? The implementation should be generic which can be applied to any views.
Add this interface in your Project....
public interface RetrofitCallback {
<T> void getSuccessCallBack(Response<T> response, int position);
void getErrorCallBack(String message, int position);
}
add these methods in your Utility or RetrofitUtility.
public static <T> void callRetrofit(final Context context, final Fragment fragment, Call<T> call, final int position, final RetrofitCallback callback) {
final ProgressDialog pDialog = CommonMethod.showProgressDialog(context, context.getResources().getString(R.string.loading));// progress for whole application
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
pDialog.dismiss();
if (response.isSuccessful()) {
ResultBody result = (ResultBody) response.body();
if (result.isSuccess())
callback.getSuccessCallBack(response, position);
else
callback.getErrorCallBack(result.getMessage(), position);
} else
Toast.makeText(context, response.message(), Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<T> call, Throwable t) {
pDialog.dismiss();
if (CommonMethod.checkconnection(context)) { // checking internet connection
Toast.makeText(context, "Server_error", Toast.LENGTH_SHORT).show();
} else {
CommonMethod.showconnectiondialog(context, fragment);
}
}
});
}
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("XXXXXXXXXXXXX")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
All Retrofit API
public interface RetrofitApi {
#POST("allData")
Call<UserData> getAllData();
}
Implement RetrofitCallback in your Activity and Fragment
Call Api like this
Call<UserData> call = ApiClient.getClient().create(RetrofitApi.class).getAllData();
ApiClient.callRetrofit(context, this, call, 0, this);
and you will get data from RetrofitCallback override methods below
#Override
public <T> void getSuccessCallBack(Response<T> response, int position) {
UserData userData = ((UserData) response.body());
// do your operation over here
}
#Override
public void getErrorCallBack(String message, int position) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
Here is all models file....
ResultBody.class
public class ResultBody {
private String message;
private boolean success;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}
UserData.class
public class UserData extends ResultBody {
private User userData;
public User getUserData() {
return userData;
}
public void setUserData(User user) {
this.userData = user;
}
}
Let me know if you stuck anywhere.....
Relative Posts or Questions
Android:dynamically pass model class to retrofit callback
I have navigationdrawer with nav menus. When clicking on each nav menus, specific fragment opened. Each fragment display recylerviews who fetch data from SQLite external database.Now when open new fragment, little seconds must wait and when to click on each item for go to next activity for display details information about the item, 5 seconds must wait to open Details Activity. I know this is a problem for fetching data in main Thread and fetch bitmap in the main thread.But I don't know how to solve this problem with use AsyncTask.My big problem is an open new activity for display information and waiting for 5 seconds.
This is my asiafragment.
AsiaFragment
public class AsiaFragment extends Fragment {
private static final String ASIA_FRAGMENT = "asia_fragment";
ArrayList<AsiaCountry> asiaCountries = new ArrayList<>();
ContentAdapter contentAdapter;
RecyclerView recyclerView;
private boolean isListView;
private Menu menu;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private MyAsyncTas myAsyncTas;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.asia_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
getActivity().setTitle("Asia");
isListView = true;
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new MyAsyncTas().execute();
}
// When click on grid icon, view items must be convert to grid.
public void toggle() {
MenuItem item = menu.findItem(R.id.grid);
if (isListView) {
staggeredGridLayoutManager.setSpanCount(2);
item.setIcon(R.drawable.ic_vertical);
item.setTitle("Show as list");
isListView = false;
} else {
staggeredGridLayoutManager.setSpanCount(1);
item.setIcon(R.drawable.ic_grid);
item.setTitle("Show grid");
isListView = true;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.grid_item, menu);
this.menu = menu;
Log.d("Menu created", "grid");
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.grid) {
Toast.makeText(getActivity(), "Grid item touched", Toast.LENGTH_SHORT).show();
toggle();
return true;
}
if (id == R.id.settings) {
Toast.makeText(getActivity(), "Setting clicked", Toast.LENGTH_SHORT).show();
return true;
}
return onOptionsItemSelected(item);
}
// When loading AsiaFragment, database loading from Eternal database.
public void loadDataBase() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getActivity());
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d("TAG", "Database open");
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("Tag", o.getMessage());
}
try {
// Tell to database , take name and viewImage from worldCountries .
Cursor cursor = worldCountryDatabase.QueryData("SELECT name, Image FROM country WHERE continent ='آسیا'");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
AsiaCountry asiaCountry = new AsiaCountry();
asiaCountry.setName(cursor.getString(0));
asiaCountry.setFlag(cursor.getString(1));
Log.d(ASIA_FRAGMENT, cursor.getString(1));
asiaCountries.add(asiaCountry);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
}
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("TAG", o.getMessage());
}
// When loading RecylerView staggeredGridLayout loading.
staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
contentAdapter = new ContentAdapter(getActivity(), asiaCountries);
contentAdapter.notifyDataSetChanged();
contentAdapter.setListener(new ContentAdapter.Listener() {
#Override
public void onClick(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setAdapter(contentAdapter);
}
public class MyAsyncTas extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
loadDataBase();
}
}
This is my DetailCountry fragment, who must be displayed detatail country clicked.
DetailsCountry
public class DetailsCountry extends AppCompatActivity implements
TabLayout.OnTabSelectedListener,
EconomicFragment.EconomicOnFragmentInteractionListener,
SummarizeFragment.SummarizeOnFragmentInteractionListener,
HistoryFragment.HistoryOnFragmentInteractionListener,
GeographyFragment.GeographyOnFragmentInteractionListener,
TipsFragment.TipsOnFragmentInteractionListener,
DescriptionFragment.OtherOnFragmentInteractionListener,
PeopleFragment.PeopleOnFragmentInteractionListener {
public static String NAME_COUNTRY = "name";
public final String pageTitle[] = {"خلاصه",
"تاریخ",
"جغرافی",
"اقتصاد",
"مردم",
"غیره",
"نکات"};
ArrayList<AsiaCountry> asiaList = new ArrayList<>();
ImageView imageHistory;
TabLayout tabLayout;
ViewPager viewPager;
String content;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detial_country);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
viewPager = (ViewPager) findViewById(R.id.viewPager_detail_country);
tabLayout = (TabLayout) findViewById(R.id.tabLayout_detail_country);
imageHistory = (ImageView) findViewById(R.id.image_detail_country);
bundle = getIntent().getExtras();
if (bundle != null) {
content = bundle.getString("name");
Log.d("contentDetail", content);
}
// Set title for activity title.
getSupportActionBar().setTitle(content);
retrieveData();
if (asiaList != null && asiaList.size() > 0) {
for (int i = 0; i < asiaList.size(); i++) {
imageHistory.setImageBitmap(loadBitmapFromAssets(getApplicationContext(),
asiaList.get(i).getImageResourceID()));
}
}
int numberPage = 7;
for (int i = 0; i < numberPage; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPagerCountryAdapter viewPagerAdapter = new ViewPagerCountryAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
private void retrieveData() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getApplicationContext());
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d(ARG_PARAM1, "Database opened");
try {
Cursor cursor = worldCountryDatabase.QueryData("SELECT viewImage FROM country WHERE name = '" + content + "'");
Log.d("CURSOR", cursor.toString());
if (cursor.moveToFirst()) {
do {
AsiaCountry asia = new AsiaCountry();
asia.setImageResourceID(cursor.getString(0));
Log.d("image", cursor.getString(0));
asiaList.add(asia);
} while (cursor.moveToNext());
cursor.close();
}
} catch (SQLException e) {
e.printStackTrace();
Log.d("TAG", e.getMessage());
}
}
#Nullable
private Bitmap loadBitmapFromAssets(Context context, String path) {
InputStream stream = null;
try {
stream = context.getAssets().open(path);
return BitmapFactory.decodeStream(stream);
} catch (Exception ignored) {
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ignored) {
}
}
return null;
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(base));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void economiOnFragmentInteraction(Uri uri) {
}
#Override
public void tipsOnFragmentInteraction(Uri uri) {
}
#Override
public void otherOnFragmentInteraction(Uri uri) {
}
#Override
public void peopleOnFragmentInteraction(Uri uri) {
}
#Override
public void historyOnFragmentInteraction(Uri uri) {
}
#Override
public void geographyOnFragmentInteraction(Uri uri) {
}
#Override
public void summarizeOnFragmentInteraction(Uri uri) {
}
public class DetailTask extends AsyncTask<Void, Void, Boolean>{
#Override
protected Boolean doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
Please help me, good friends. Thanks
I am right now fetching movies to my MainActivity.
I need infinite scroll on my RecycleView inside MainActivity.
Can someone tell me where to set code so I can have infinite scroll?
If you need more data, tell me.
Thank you.
MainActivity Code is bellow:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
#Override
protected void onResume() {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String order = sharedPref.getString("order", "popular");
if (order.equals("popular")) {
getPopularMovies();
} else {
getTopRatedMovies();
}
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// uci i postaviti order -> popular
Log.d("NESTO", "NESTO-onCreate");
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
mAdapter = new MoviesAdapter(MainActivity.this);
mRecyclerView.setAdapter(mAdapter);
}
private void getTopRatedMovies() {
RestAdapter.getMovieService().getTopRatedMovies(new Callback<MovieResult>() {
#Override
public void success(MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
private void getPopularMovies() {
RestAdapter.getMovieService().getPopularMovies(new Callback<MovieResult>() {
#Override
public void success(MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public MovieViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
I'm not sure how to add a progress bar or make a loading dialog while the data is being retrieved from parse.
This is my code below for retrieving the data from parse. I've tried few tutorials but none have seemed to work for me.
public class HolidayActivity extends AppCompatActivity {
private HolidayAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holiday);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(R.drawable.dl);
ParseObject.registerSubclass(Holiday.class);
mAdapter = new HolidayAdapter(this, new ArrayList<Holiday>());
ListView mListView = (ListView) findViewById(R.id.holiday_list);
mListView.setAdapter(mAdapter);
updateData();
}
public void updateData() {
ParseQuery<Holiday> query = ParseQuery.getQuery(Holiday.class);
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Holiday>() {
#Override
public void done(List<Holiday> holidays, com.parse.ParseException e) {
if (holidays != null) {
mAdapter.clear();
for (int i = 0; i < holidays.size(); i++) {
mAdapter.add(holidays.get(i));
}
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Add this to your updateData():
public void updateData() {
final ProgressDialog progressDialog = ProgressDialog.show(this, null, "Loading…");
(…)
#Override
public void done(List<Holiday> holidays, com.parse.ParseException e) {
progressDialog.dismiss();
(…)
}
}
Hope it helps!
I'm trying to get working a native android project that uses Worklight form based authentication. I'm already able to authenticate the user through the native APIs. The problem appears when I change between activities (intents). Once the user enters his information and submits the form, it is authenticated but the worklight server connection is lost.
This is the code:
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, "BasicAuth");
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "RSSReader";
String procedureName = "getStoriesFiltered";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
Object[] parameters = new Object[] {"world"};
invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyInvokeListener(), options);
}
});
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MyChallengeHadler challengeHandler = new MyChallengeHadler(LoginActivity.this, "BasicAuth");
challengeHandler.submitLogin(0, "maria", "maria", false);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
this.parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
Intent login = new Intent(parentActivity, MainActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
I have already solved my code's problem. I was using wrongly android's intents. This is the new version of the code:
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit;
private Intent result;
public static final String Back = "back";
public static final String UserNameExtra = "username";
public static final String PasswordExtra = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
result = new Intent();
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
result.putExtra(UserNameExtra, "maria");
result.putExtra(PasswordExtra, "maria");
result.putExtra(Back, false);
setResult(RESULT_OK, result);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
private String realm = "BasicAuth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, realm);
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "SOAPAdapter";
String procedureName = "getStories";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
//Object[] parameters = new Object[] {"world"};
//invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyResponseListener(), options);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
boolean back = data.getBooleanExtra(LoginActivity.Back, true);
String username = data.getStringExtra(LoginActivity.UserNameExtra);
String password = data.getStringExtra(LoginActivity.PasswordExtra);
challengeHandler.submitLogin(resultCode, username, password, back);
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
if (resultCode != Activity.RESULT_OK || back) {
submitFailure(cachedResponse);
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
}
}
}