Get Search results from Google in android app - android

In my android application I want to get search query from user, and search google with that query, get search results and populate a list with the search results. Custom Search API limits to 100 free searches per day. So is there any alternative for searching?

This is something which you can use.
http://google.com/complete/search?output=toolbar&q=query
It returns an XML file. Parse that xml to get the results.
But google may change the format of the query in future. Thats the only concern here. Otherwise it works great.
For future reference, note the following queries for other useful websites. Some return in JSON and others in XML formats.
http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=query&alt=json
http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?appid=YahooDemo&query=query
http://en.wikipedia.org/w/api.php?action=opensearch&search=query&limit=10&namespace=0&format=json
http://anywhere.ebay.com/services/suggest/?q=query&s=0
http://completion.amazon.com/search/complete?method=completion&q=query&search-alias=aps&mkt=1
http://api.bing.net/osjson.aspx?Query=query&Market=en-us

You can try using this code
MainActivity.java
private EditText editTextInput;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_g__search);
editTextInput = (EditText) findViewById(R.id.editTextInput);
}
public void onSearchClick(View v)
{
try {
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
String term = editTextInput.getText().toString();
intent.putExtra(SearchManager.SUGGEST_URI_PATH_QUERY, term);
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
}
}
Activity_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<EditText
android:id="#+id/editTextInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editTextInput"
android:layout_below="#+id/editTextInput"
android:layout_marginRight="43dp"
android:layout_marginTop="60dp"
android:onClick="onSearchClick"
android:text="CLICK" />
Also add permission for internet

Related

Why is my AutoCompleteTextView not working?

This feels strange as normally the widgets work as they are supposed to. I have an AutoCompleteTextView that I want to populate with a list of city names. It seems simple but doesn't work as I intend to. Here is the resulting output:
Here is the layout in picture:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity1">
<AutoCompleteTextView
android:id="#+id/autocomptv_city_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/bg_edittext_rect_opd"
android:hint="Select City"
android:text=""
android:inputType="text"
android:maxLines="1"
android:completionThreshold="0"
android:padding="10dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
And below is the java code for the same:
public class MainActivity1 extends AppCompatActivity {
AutoCompleteTextView mAutCompleteTextViewSelfCity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
mAutCompleteTextViewSelfCity = ((AutoCompleteTextView) findViewById(R.id.autocomptv_city_list));
setupCityDropdownwidget();
}
private void setupCityDropdownwidget() {
Type listType = new TypeToken<List<CityName>>() {}.getType();
List<CityName> citiesList = Singletons.getGsonInstance().fromJson(TestData.cityDataJson, listType);
CityArrayAdapter adapter = new CityArrayAdapter(this, R.layout.item_spinner_city, citiesList);
mAutCompleteTextViewSelfCity.setAdapter(adapter);
adapter.notifyDataSetChanged();
mAutCompleteTextViewSelfCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CityName selectedCitySelf = ((CityName) parent.getItemAtPosition(position));
mAutCompleteTextViewSelfCity.setText(selectedCitySelf.getCityName());
}
});
}
}
Problem:
Well, I want the view to be such that as soon as the user taps on it, it shows a dropdown of cities and when the user starts typing their city for filtering, the view keeps showing narrowed down suggestions for the same.
Currently, the only time it is able to suggest is when I type in something and empty out the text view. If I change the completion threshold to 1, no suggestions are shown ever.
What's wrong with my code?
Here is the complete source for reference: https://wetransfer.com/downloads/ce4017f5f2488288ef7494dc029e033420191019092536/7afa9a3e64afb257293533bd634d6c3220191019092536/dc2341
So ultimately, it turned out to be about the basics - The data item that ArrayAdapter works with, should provide a meaningful toString() override. That is what had been missing from my implementation.
From the docs:
By default, the array adapter creates a view by calling
Object#toString() on each data object in the collection you provide,
and places the result in a TextView.
I did end up wasting up some time but the experience and knowledge would surely come in handy some day.
YOu don't need to set adapter.notifyDataSetChanged();, just set your adapter and everything goes fine.

Android: single TextView is null

I just updated my test smartphone from Android 4.1.1 to 4.1.2 and I am getting a NullPointerException that didn't show up before.
This is the onCreate() and follow up methods. Note that the function isOnline() is working well.
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
//fillStatusBar(isOnline());
fillStatusBar(false);
}
private void fillStatusBar(boolean isOnline){
TextView txt = (TextView) findViewById(R.id.txt_menu_connection_status);
if(isOnline){
//if(txt != null){
txt.setBackgroundColor(0xFF78AB46); // NullPointerException!!!
txt.setText("online");
//}
}else{
// TODO also an alert
txt.setBackgroundColor(0xFFF08080);
txt.setText("offline");
}
}
In activity_menu.xml (example, the first button here is shown normally):
<!-- (...) -->
<TextView style="#style/MainButton"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:layout_marginBottom="20dip"
android:text="#string/info"
android:onClick="onClickInfo"
/>
<TextView
android:id="#+id/txt_menu_connection_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="2dip"
/>
I commented the line in which the NullPointerException gets thrown. If I make the check if(txt != null), no exception is thrown and the layout is showed normally WITHOUT the single TextView. How is this even possible? What can I provide additionally to evaluate this case?
Following an image of the LogCat. The log disappears after a few seconds, also when saving the log it is empty.

Android toggle button display wrong value after orientation change

Here is my problem.
I've got a simple activity which set a layout, and add rows in a table-layout(itself in a scroll view).
Those table-rows have a custom layout with a text-field and a toggle button.
Each toggle button has a value taken from a database, and when I first create the activity, the values are OK. But when I turn the device and then change the orientation, all the toggles-button take "false" value. I printed the values that I set in the Logcat, and the values are the good ones (those in the database).
I thought something like the layout I want is hidden behind another layout, but I made some tests and the text-fields change with new values, so I really don't understand why the toggle buttons don't work.
Here is the code :
TableRow layout :
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<RelativeLayout
android:id="#+id/relativelayout_row_parametres"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_weight="1.0">
<TextView
android:id="#+id/textview_row_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginLeft="2dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
/>
<ToggleButton
android:id="#+id/togglebutton_row_parametres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="2dp"
android:textOn="#string/togglebutton_on"
android:textOff="#string/togglebutton_off" />
</RelativeLayout>
</TableRow>
Activity Layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView style="#style/header" />
<LinearLayout
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.8"
android:background="#drawable/gradient_bg"
android:padding="10dip"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.85"
android:fillViewport="true"
android:padding="10dip"
android:layout_gravity="center">
<TableLayout
android:id="#+id/tablelayout_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/cornered_bg"
android:paddingTop="5dip"
android:paddingBottom="5dip">
</TableLayout>
</ScrollView>
<Button
android:id="#+id/button_parametres_accept"
android:gravity="center"
android:text="#string/accept_changes"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.15"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
And the activity code:
public class Parameters extends Activity {
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Map<String, Boolean> changes = new HashMap<String, Boolean>();
final Context ctx = getApplicationContext();
LanguageManager.updateConfig(this);
setContentView(R.layout.parametres);
CountryDB[] countries = Database.instance(getApplicationContext()).getCountries();
TableLayout tabLayout = (TableLayout) findViewById(R.id.tablelayout_parametres);
for(int i =0; i<countries.length; i++){
TableRow newRow = (TableRow) getLayoutInflater().inflate(R.layout.row_parametres, null);
TextView textView = (TextView) newRow.findViewById(R.id.textview_row_parametres);
ToggleButton toggleButton = (ToggleButton) newRow.findViewById(R.id.togglebutton_row_parametres);
toggleButton.setChecked(countries[i].isToSynchronize());
toggleButton.setTag(countries[i]);
Log.e("setChecked",""+toggleButton.getId()+"/"+countries[i].isToSynchronize());
textView.setText(countries[i].getLabel());
toggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CountryDB countryTemp = (CountryDB) v.getTag();
changes.put(countryTemp.getLabel(), ((ToggleButton)v).isChecked());
}
});
tabLayout.addView(newRow);
TableRow rowDivider = (TableRow) getLayoutInflater().inflate(R.layout.row_divider, null);
tabLayout.addView(rowDivider);
}
Button buttonValidation = (Button) findViewById(R.id.button_parameters_accept);
buttonValidation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Iterator<String> iterator = changes.keySet().iterator();
while(iterator.hasNext()){
String stringTemp = iterator.next();
Database.instance(ctx).updateCountry(stringTemp, changes.get(stringTemp));
}
Intent intent = new Intent(ctx, Splash.class);
String result = "restart";
String from = "parameters";
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
returnIntent.putExtra("from", from);
setResult(RESULT_OK, returnIntent);
startActivity(intent);
}
});
}
}
In the Log.e, I print the values, and they are good, the display on togglebuttons is wrong, they are just all "false".
Thanks for your help.
Between onCreate() and onResume() , Android tries to restore the old state of the toggle Buttons. Since they don't have unique ID's , Android wont succeed and everything is false again. Try to move your setChecked() calls into onResume() ( maybe onStart() works too).
Here is a pretty good answer to the same Question:
ToggleButton change state on orientation changed
you have to save data before Orientation.
Android have method onSaveImstamceState(Bundle outState) and onRestoreInstanceState(BundleInstaceState)
override these method in Activity.
There's a simpler solution: you only need to add configChanges property to your activity declaration, like stated here. This way you can prevent Activity restart when orientation changes. So in your manifest you should have something like
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden">
or if your buildTarget>=13
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden|screenSize">
Edit: Like reported on comments below, this is not an optimal solution. The main drawback is reported in a note of the document linked above:
Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

Java program does not execute in Android

I am doing a weather project in android. The information is from a given URL which is static and contains a list of cities. For example: HTTP://myexample/info/?cities displays a list of cities. HTTP://myexample/info/?tokyo will display: Tokyo, Japan.
I have done the layout to write down the name of the city to be executed:
xmlns:tools=["http://schemas.android.com/tools"]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Meteo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="40dp"
android:weightSum="4">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/soleil" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="4">
<EditText
android:id="#+id/editText1"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button" />
</LinearLayout>
But the Java program doesn't execute. Only the layout is executed:
public class Demo {
public static void main(String[] args) {
// URL
String url = "$HTTP://myexample/info/?cities$";
// Weather information
String weather = "Tokyo, Japan#15.5#Sun ##";
// Get the city name
String city = url.substring(url.indexOf("?") + 1).trim();
System.out.println(city);
// Check the weather of the city: 15.5#Sun
// Remove city name
// Remove last #
if (weather.toLowerCase().contains(city.toLowerCase())) {
// Get condition:
String condition = weather.substring(weather.indexOf("#") + 1,
weather.length() - 2);
System.out.println(condition);
// Split with # sign and you have a list of conditions
String[] information = condition.split("#");
for (int i = 0; i < information.length; i++) {
System.out.println(information[i]);
}
}
}
}
Where is the problem?
Look up Activities. In Android you'll have to create a class that extends Activity. The equivalent to the main() method is the OnCreate() method. In this method you can set your layout with setContentView(layout id)
Ofcourse main() method is not supported in android.
public static void main(String[] args) {
// ....
}
Use Activity instead.
public class MyActivity extendsActivity
{
#Override
protected void onCreate(Bundle saveInstance)
{
// This method will be called first
super.onCreate(saveInstance);
// Your definition
}
}
Your main problems is that you are trying to run an Android application as a Java application.
public static void main(String[] args)
Is the standard entry point for a Java application.
In Android, things are a little different.
First, class Demo must extend Activity:
public class Demo extends Activity
Second, you have to implement special methods, which are invoked at specific moments of the life time of your application, the most important being:
public void onCreate(Bundle savedInstanceState) { }
protected void onPause() { }
protected void onResume() { }
You should check the corresponding documentation at Android Developers Site.

Coupling Android layout to its logic outside of the owner Activity

I'm facing some complexities when developing a medium-complex Android application. I'm searching for information about the possibility of using code-behind-like techniques for easier maintanability of Android software.
Currently (please highlight anything wrong), I have found that in order to make a multi-step wizard with extra dialogs (eg. dialogs that are not part of the main sequence) I need to code a single XML layout file with a single ViewFlipper containing each subview as child node. Today I discovered how to navigate across views more than forward/backward (viewFlipper.setDisplayedChild(i)), giving access to extra views.
Now all the Java code is contained within the main Activity class, which is beginning to look bad. As an experienced .NET developer I have learned how to use custom controls to wrap both layout and business logic inside modules.
I know that in Android I can define a view programmatically as an independent class and add it to the main layout programmatically, however I want to know if it's possible in Android to define a layout by XML (for easier WYSIWYG creation/editing) and define all the code within a dedicated class, with initialization logic, button callbacks, async tasks, etc.
I'm not sure if it's feasible or there is a good compromise that can be achieved.
I have read this question without clearing my doubts.
Thank you.
Code examples:
An extract of the layout file (I expect 4 wizard steps, a help view and an EULA view)
<?xml version="1.0" encoding="utf-8"?>
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_phone"
style="#android:style/Theme.Light.NoTitleBar"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- First screen/welcome -->
<LinearLayout
android:id="#+id/view_phone_screen1"
style="#android:style/Theme.Light.NoTitleBar"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="100" >
<TextView
android:id="#+id/view_phone_screen1_lblChooseProvider"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="#string/view_phone_lblChooseProvider_1ststep"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageButton
android:id="#+id/view_phone_btnFrecciarossa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:contentDescription="#string/provider_FRECCIAROSSA"
android:gravity="center_vertical|clip_vertical"
android:padding="10dp"
android:src="#drawable/logo_frecciarossa"
android:tag="#+id/provider_FRECCIAROSSA" />
<ImageButton
android:id="#+id/view_phone_btnItalo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:contentDescription="#string/provider_ITALO"
android:gravity="center_vertical|clip_vertical"
android:padding="10dp"
android:src="#drawable/logo_italo"
android:tag="#+id/provider_ITALO" />
</LinearLayout>
<!-- Second screen - will need to do some asynchronous task -->
<RelativeLayout
android:id="#+id/view_phone_screen2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/view_phone_screen2_lblConnectingToWifi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="#string/view_phone_lblConnectToWifi_2ndstep"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/view_phone_step2_lblConnectedToWifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="58dp"
android:text="#string/view_phone_step2_connectingToWifi"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/view_phone_step2_lblPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/view_phone_step2_lblConnectedToWifi"
android:layout_marginTop="51dp"
android:text="#string/view_phone_step2_msgInputPhoneNumber"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/view_phone_step2_lblUnableDetectPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="#string/view_phone_step2_msgUnableDetectPhoneNumber"
android:textAppearance="?android:attr/textAppearanceSmall"
android:visibility="invisible" />
<Button
android:id="#+id/view_phone_screen2_backward"
style="#style/buttonBackward" />
<Button
android:id="#+id/view_phone_screen2_forward"
style="#style/buttonForward_disabled"
android:enabled="false" />
<EditText
android:id="#+id/view_phone_step2_txtPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/view_phone_step2_lblPhoneNumber"
android:layout_below="#+id/view_phone_step2_lblPhoneNumber"
android:inputType="phone"
android:singleLine="true" >
<requestFocus />
</EditText>
</RelativeLayout>
</ViewFlipper>
Code example from Activity (expect to implement ALL the logic of 4+2 step wizard)
public class MyActivity extends Activity {
/** Called when the activity is first created. */
private final static String LOG_TAG = "LOG_TAG";
private int stepNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
this.stepNumber=1;
setContentView(R.layout.view_phone);
//This class wraps the click for the two buttons
ProviderSelectionListener providerSelectionListener = new ProviderSelectionListener(this);
this.findViewById(R.id.view_phone_btnFrecciarossa).setOnClickListener(providerSelectionListener);
this.findViewById(R.id.view_phone_btnItalo).setOnClickListener(providerSelectionListener);
}
#Override
protected void onPause() {
super.onPause();
try {
if (MyApplication.getPlatformManager() != null)
MyApplication.getPlatformManager().onApplicationPause();
} catch (MyCustomException e) {
// WTF (Worse Than Failure!)
Log.e(LOG_TAG, super.getString(R.string.zf_error_unknown_error_pauseactivity), e);
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
try {
if (MyApplication.getPlatformManager() != null)
MyApplication.getPlatformManager().onApplicationResume();
} catch (MyCustomException e) {
// WTF (Worse Than Failure!)
Log.e(LOG_TAG, super.getString(R.string.zf_error_unknown_error_pauseactivity), e);
e.printStackTrace();
}
}
/*
* SLIDE INIZIO
*/
protected void slideNext() {
ViewFlipper vf = (ViewFlipper) findViewById(R.id.view_phone);
vf.setOutAnimation(getApplicationContext(), R.anim.slide_out_left);
vf.setInAnimation(getApplicationContext(), R.anim.slide_in_right);
vf.showNext();
}
protected void slidePrevious() {
ViewFlipper vf = (ViewFlipper) findViewById(R.id.view_phone);
vf.setOutAnimation(getApplicationContext(), R.anim.slide_out_right);
vf.setInAnimation(getApplicationContext(), R.anim.slide_in_left);
vf.showPrevious();
}
/*
* SLIDE FINE
*/
/*
* STEP 1 INIZIO
*/
public void completeStep1(ISmsWifiProvider provider) {
if (provider == null) {
Log.e(LOG_TAG, "Provider nullo");
return;
}
MyApplication.setAuthenticationProvider(provider);
slideNext();
initializeStep2();
}
public void returnToStep1() {
MyApplication.setAuthenticationProvider(null);
slidePrevious();
}
/*
* STEP 1 FINE
*/
/*
* STEP 2 INIZIO
*/
private void initializeStep2() {
// Event handler
Button backButton = (Button) findViewById(R.id.view_phone_screen2_backward), fwButton = (Button) findViewById(R.id.view_phone_screen2_forward);
fwButton.setEnabled(false);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
returnToStep1();
}
});
}
/*
* STEP 2 FINE
*/
#Override
public void onBackPressed() {
// This will be called either automatically for you on 2.0
// or later, or by the code above on earlier versions of the
// platform.
return;
}
}
I want to know if it's possible in Android to define a layout by XML (for easier WYSIWYG creation/editing) and define all the code within a dedicated class, with initialization logic, button callbacks, async tasks, etc.
Yes. It is one of the techniques for creating a custom View. For example, I have a custom ColorMixer widget in this project, which can be used directly in an activity, or in a dialog, or in a custom preference.
I agree with your tactical decision to implement a wizard via a ViewFlipper -- see this answer to another StackOverflow question for "Murphy's Theory of the Activity".
I suspect that the right answer, longer term, is for somebody (who might be me) to come up with a Fragment-based wizard pattern, as that gives you the decoupling you desire.

Categories

Resources